rete-core 0.4.0

Core format types for the Rete cloud-native RDF graph file.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
//! The standardized exploration query library (Design B of `dev/pyramid-dev.md`).
//!
//! A vetted set of starter SPARQL queries, **auto-instantiated at build** with a
//! dataset's real vocabulary (`{{TOP_CLASS}}`/`{{TOP_PRED}}`/`{{LABEL_PRED}}`/…)
//! drawn from the enriched [`DatasetCard`] profile, and emitted **only when the
//! required signal is present** (no geo query without geometry, no time query
//! without a time predicate) so the shipped set always returns rows. Every query
//! carries its own `PREFIX` block (the engine injects none) and is tagged with
//! the cheapest [`Tier`] that can answer it.
//!
//! Bodies are **graph-scope aware** (`GraphScope`): a dataset whose statements
//! live entirely in named graphs (`triple_count == 0`, `named_graph_count > 0`)
//! gets `GRAPH ?g`-scoped bodies — a bare `{ ?s ?p ?o }` there can only ever
//! return zero rows — and a dataset with data in **both** the default graph and
//! named graphs gets `UNION`-scoped overview bodies so neither half is silently
//! hidden.
//!
//! # Why a generated query may not return zero rows
//!
//! A starter query that answers nothing is worse than no starter query: the
//! reader concludes the **file** is broken. So every template carries a
//! `NonEmpty` claim — the reason its emitted form cannot come back empty —
//! and `check_body` enforces the one rule that claim rests on:
//!
//! > A body may conjoin substituted vocabulary only when the card **proves the
//! > pieces co-occur**.
//!
//! Presence is not co-occurrence. `{{TOP_CLASS}}` is the class with the most
//! instances and `{{LABEL_PRED}}` the most-used labelling predicate; each is
//! certainly *present*, and instances of that class need never carry that
//! predicate. Conjoining them — which `lb-labels` did — is a guaranteed-empty
//! query whenever the two peaks fall on different parts of the graph, as they
//! do on `mtg` (top class `mtg:Ruling`, which has no `schema:name`) and on
//! `hugging-face` (top class `hf:Model`; `rdfs:label` appears only on the
//! embedded TBox terms). The fix is not to check harder downstream but to make
//! the conjunction unrepresentable: capabilities that appear together in a body
//! must be **jointly derived** (`Cap::joint_with`) — chosen *because* they
//! meet, with a `class_links` row as the witness.
//!
//! Where the card genuinely cannot decide emptiness, the template says so
//! (`NonEmpty::Undecidable`) instead of pretending; `provably_empty` is the
//! last gate, dropping a template the card can prove would answer nothing.
//!
//! # Why a generated query may not cost more than a starter should
//!
//! The other half of "a starter query that answers nothing is worse than
//! none" is a starter query that does not finish. On the OpenCitations sample
//! (18.9 M quads, 1.5 M named graphs, 1.07 GB) eight of the old bodies scanned
//! the whole file — `ov-triples`, `ov-pred-*`, `top-*-hubs`, `top-dangling`,
//! `ng-*` — and every one was killed in a 4 GiB client; `top-dangling` alone
//! peaked at 8.7 GiB. A greeting query is the first thing a newcomer runs, often
//! in a browser tab, so its cost has to be bounded by construction, not by the
//! size of the dataset it happens to greet.
//!
//! Every template therefore declares what its body **reads** (`Scan`), and the
//! card's own counts turn that into a number of statements before the body is
//! written. Within [`STARTER_SCAN_BUDGET`] the exact body ships, unchanged. Past
//! it the template ships its **bounded** form (`Bounded`) — the same question
//! over a fixed-size sample (`LIMIT` inside a sub-select, which the engine
//! evaluates lazily), or a weaker question with an exact bounded answer — and a
//! template with no honest bounded form is not shipped at all: those are the
//! questions (`how many statements?`, `which predicates, how often?`, `which
//! hubs?`) the card already answers from its own precomputed profile, index-free.
//! The build then measures every emitted query through a byte budget
//! ([`STARTER_MAX_BYTES`]) and drops whatever still reads more, so the bound is
//! measured, not only estimated.
//!
//! This is pure serde generation — no format change, no I/O, no threads. It
//! lives in `rete-core` (it used to live in the binary-only `rete-cli`, where no
//! client could reach it — #152) so the CLI, the browser builder and every
//! language binding instantiate one query library from one table.

use serde::Serialize;

use crate::card_derive::{
    DatasetCard, ExampleQuery, Tier, CARD_TOP_N, GEO_ASWKT, GEO_HASGEOMETRY,
    LINK_PREDICATES as LINK_PREDICATE_IRIS, O_LITERAL, WGS_LAT as WGS_LAT_IRI,
    WGS_LONG as WGS_LONG_IRI,
};
use crate::RDF_TYPE;

/// Prepended to every generated query — the engine parses with **zero** implicit
/// prefixes (`Query::parse(q, None)`), so an undeclared prefix is a parse error.
const PREFIXES: &str = "\
PREFIX rdf:  <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX owl:  <http://www.w3.org/2002/07/owl#>
PREFIX void: <http://rdfs.org/ns/void#>
PREFIX dct:  <http://purl.org/dc/terms/>
PREFIX skos: <http://www.w3.org/2004/02/skos/core#>
PREFIX geo:  <http://www.opengis.net/ont/geosparql#>
PREFIX geof: <http://www.opengis.net/def/function/geosparql/>
PREFIX wgs:  <http://www.w3.org/2003/01/geo/wgs84_pos#>
PREFIX time: <http://www.w3.org/2006/time#>
PREFIX xsd:  <http://www.w3.org/2001/XMLSchema#>";

/// A capability the dataset must offer for a template to be emitted (and, for the
/// string-valued ones, the vocabulary substituted into its placeholder).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Cap {
    TopClass,
    TopPred,
    /// The most populous class the card can **prove** carries [`Cap::LabelPred`].
    LabeledClass,
    LabelPred,
    /// The most frequent predicate the card can **prove** has a non-literal
    /// object — the only kind a path query can walk past one hop.
    ObjectPred,
    TimePred,
    NumPred,
    BaseIri,
    /// An IRI the card records that lies **outside** [`Cap::BaseIri`] — the
    /// witness that "links pointing out of this dataset" has something to find.
    ExternalIri,
    GeoLatLong,
    /// The path from a subject to its WKT geometry, as the data actually shapes
    /// it (`geo:asWKT` direct, or through `geo:hasGeometry`).
    WktPath,
    /// The query box for the geometry template.
    Bbox,
    NamedGraphs,
    Link,
    HasLiterals,
    /// At least one statement in this graph is **about a statement** — its
    /// subject is a quoted triple. The gate for the bodies that write
    /// `<< ?s ?p ?o >>` in subject position with nothing substituted into it.
    AnnotatedStatements,
    /// The most frequent predicate that annotates a statement — the outer
    /// predicate of `<< s p o >> :recordedBy :who`.
    AnnotationPred,
    /// The predicate **inside** a quoted triple that [`Cap::AnnotationPred`]
    /// was seen annotating. Jointly derived with it (`annotated_statement` is
    /// the witness), so a body may pin both.
    AnnotatedPred,
    /// The most frequent predicate whose **object** is a quoted triple —
    /// `:claim :states << s p o >>`, the other position a triple term stands
    /// in, and a different query from the annotation one.
    QuotingPred,
}

/// Every capability, in declaration order — the substitution table and the
/// placeholder audit both walk it, so a new `Cap` cannot be half-wired.
const ALL_CAPS: &[Cap] = &[
    Cap::TopClass,
    Cap::TopPred,
    Cap::LabeledClass,
    Cap::LabelPred,
    Cap::ObjectPred,
    Cap::TimePred,
    Cap::NumPred,
    Cap::BaseIri,
    Cap::ExternalIri,
    Cap::GeoLatLong,
    Cap::WktPath,
    Cap::Bbox,
    Cap::NamedGraphs,
    Cap::Link,
    Cap::HasLiterals,
    Cap::AnnotatedStatements,
    Cap::AnnotationPred,
    Cap::AnnotatedPred,
    Cap::QuotingPred,
];

impl Cap {
    /// Stable key recorded in `ExampleQuery.requires`.
    fn key(self) -> &'static str {
        match self {
            Cap::TopClass => "TOP_CLASS",
            Cap::TopPred => "TOP_PRED",
            Cap::LabeledClass => "LABELED_CLASS",
            Cap::LabelPred => "LABEL_PRED",
            Cap::ObjectPred => "OBJECT_PRED",
            Cap::TimePred => "TIME_PRED",
            Cap::NumPred => "NUM_PRED",
            Cap::BaseIri => "BASE_IRI",
            Cap::ExternalIri => "EXTERNAL_IRI",
            Cap::GeoLatLong => "GEO_LATLONG",
            Cap::WktPath => "WKT_PATH",
            Cap::Bbox => "BBOX",
            Cap::NamedGraphs => "NAMED_GRAPHS",
            Cap::Link => "LINK",
            Cap::HasLiterals => "HAS_LITERALS",
            Cap::AnnotatedStatements => "ANNOTATED_STATEMENTS",
            Cap::AnnotationPred => "ANNOTATION_PRED",
            Cap::AnnotatedPred => "ANNOTATED_PRED",
            Cap::QuotingPred => "QUOTING_PRED",
        }
    }

    /// The `{{PLACEHOLDER}}` this capability's value is substituted into, for
    /// the string-valued ones. `None` for the pure gates (they have no text in
    /// the body — they only decide whether it is emitted).
    fn placeholder(self) -> Option<&'static str> {
        Some(match self {
            Cap::TopClass => "{{TOP_CLASS}}",
            Cap::TopPred => "{{TOP_PRED}}",
            Cap::LabeledClass => "{{LABELED_CLASS}}",
            Cap::LabelPred => "{{LABEL_PRED}}",
            Cap::ObjectPred => "{{OBJECT_PRED}}",
            Cap::TimePred => "{{TIME_PRED}}",
            Cap::NumPred => "{{NUM_PRED}}",
            Cap::BaseIri => "{{BASE_IRI}}",
            Cap::WktPath => "{{WKT_PATH}}",
            Cap::Bbox => "{{BBOX_POLYGON}}",
            Cap::AnnotationPred => "{{ANNOTATION_PRED}}",
            Cap::AnnotatedPred => "{{ANNOTATED_PRED}}",
            Cap::QuotingPred => "{{QUOTING_PRED}}",
            Cap::ExternalIri
            | Cap::GeoLatLong
            | Cap::NamedGraphs
            | Cap::Link
            | Cap::HasLiterals
            | Cap::AnnotatedStatements => return None,
        })
    }

    /// The capabilities this one is chosen **together with** — the card holds a
    /// `class_links` row proving they meet on the same subjects, so a body may
    /// conjoin them.
    ///
    /// This is the whole safety property. Every other pair of substitutions is
    /// picked from a different ranking (most instances / most statements / most
    /// labels), and two independent maxima need not describe the same entity;
    /// see the module docs. The relation is symmetric — `check_body` checks
    /// both directions.
    fn joint_with(self) -> &'static [Cap] {
        match self {
            // `LABELED_CLASS` *is* "the class that carries `LABEL_PRED`". The
            // one pair the card can witness, and the one the label queries need.
            Cap::LabeledClass => &[Cap::LabelPred],
            Cap::LabelPred => &[Cap::LabeledClass],
            // `ANNOTATED_PRED` *is* "the predicate inside the statements that
            // `ANNOTATION_PRED` was seen annotating". `signals
            // .annotated_statement` holds the two as they occurred together on
            // one statement, so a body may write them into one pattern. Chosen
            // apart they would be the two-maxima shape again: the most-used
            // annotation predicate need not be the one attached to the
            // most-annotated kind of statement.
            Cap::AnnotatedPred => &[Cap::AnnotationPred],
            Cap::AnnotationPred => &[Cap::AnnotatedPred],
            _ => &[],
        }
    }
}

/// **The** co-occurrence witness: does the card record that some subject of
/// `class` also carries `pred`?
///
/// A `class_links` row is positive evidence — the quotient counts real
/// statements, so a row exists only because a subject classified as `class`
/// really made a `pred` statement. Both the generator (choosing
/// `Cap::LabeledClass`) and the audit ([`audit`]) ask this one question, so
/// "does the card prove these meet?" has exactly one implementation.
fn class_carries(card: &DatasetCard, class: &str, pred: &str) -> bool {
    card.class_links
        .iter()
        .any(|l| l.s_class == class && l.predicate == pred)
}

/// The RDF-star co-occurrence witness, in the one place both halves read it:
/// `(the predicate inside a quoted triple, the predicate annotating it)` for a
/// statement this graph was seen to **assert and annotate**.
///
/// It plays exactly the role [`class_carries`] plays for `LABELED_CLASS`. The
/// derivation records the pair only when it matched an asserted statement
/// against the annotations of that same statement, so a hit proves both halves
/// of `qt-coverage`'s aggregate are non-zero — `?s p ?o` matches, and the
/// `OPTIONAL` binds at least once. Both the generator (resolving
/// [`Cap::AnnotatedPred`]) and [`audit`] ask through here, so "does the card
/// prove these meet?" keeps having exactly one implementation.
fn annotated_statement(card: &DatasetCard) -> Option<(&str, &str)> {
    card.signals
        .annotated_statement
        .as_ref()
        .map(|(quoted, about)| (quoted.as_str(), about.as_str()))
}

/// Why a template's emitted query cannot come back empty. Declared per template
/// and enforced by `check_body` plus the fixture tests, which run every
/// generated query against the very graph it was generated for.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum NonEmpty {
    /// Any non-empty graph answers: the body has no substitution and no filter
    /// that could exclude every statement.
    AnyGraph,
    /// An aggregate with no `GROUP BY` — SPARQL returns exactly one row even
    /// over an empty solution sequence, so "zero rows" is not reachable. (The
    /// row's values may still be unbound; see each template's note.)
    Aggregate,
    /// Every substitution came from a count the card recorded as `> 0`, and any
    /// two that meet in the body are [jointly derived](Cap::joint_with).
    Witnessed,
    /// The card cannot decide it. The string is the reason, and it is the text
    /// a reader deserves when the query does answer nothing.
    Undecidable(&'static str),
}

/// How many statements a starter query's body may have to read before the
/// generator swaps it for its `Bounded` form (or drops it).
///
/// Calibrated on the heaviest exact bodies, measured on the OpenCitations
/// sample's 5.97 M-statement default graph: `top-class-graph` peaked at
/// ~450 B of RSS per statement scanned and the old `top-dangling` at ~570 B, so
/// two million statements keeps the worst of them near 1 GiB — inside a 4 GiB
/// client with room for the reader's own caches — while a full scan of one
/// permutation at this size is a few MB of index. A dataset at or under the
/// budget keeps every exact body, byte for byte.
pub const STARTER_SCAN_BUDGET: u64 = 2_000_000;

/// The most bytes a starter query may read when the build (or `rete recard`)
/// measures it, counted once the file is open — the measured backstop to
/// [`STARTER_SCAN_BUDGET`]'s estimate. A query that asks for more is dropped
/// from the card and the drop is recorded ("did not finish"). The open is not
/// charged: it reads the section directories (~44 MB on a 26 GB file) whatever
/// the query, a cost no starter can change. 64 MiB is ~3× the heaviest exact body on a
/// budget-sized graph and ~40× the heaviest bounded one.
pub const STARTER_MAX_BYTES: u64 = 64 << 20;

/// What a template's body has to read — turned into a number of statements by
/// [`scan_estimate`] from the card's own counts, and compared against
/// [`STARTER_SCAN_BUDGET`].
///
/// An estimate, not a promise (a join's fan-out is not in the card), which is
/// why the build measures every emitted query through [`STARTER_MAX_BYTES`]
/// as well. It errs high: a term the card does not list is charged the
/// largest count it could have.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Scan {
    /// The body bounds itself — a `LIMIT` over a pattern the engine evaluates
    /// lazily, a single seeded lookup, an `ASK`.
    Bounded,
    /// Every statement in the body's graph scope.
    Everything,
    /// Every `rdf:type` statement.
    Types,
    /// Every statement of one substituted predicate.
    Pred(Cap),
    /// Every statement of these fixed predicates.
    Preds(&'static [&'static str]),
    /// The instances of one substituted class.
    Class(Cap),
    /// The instances of one substituted class and every statement they make.
    ClassStar(Cap),
    /// Every statement in a named graph.
    NamedGraphs,
    /// Every statement whose subject is a quoted triple.
    Annotations,
}

/// The form a template takes when its [`Scan`] is over the budget.
///
/// Each bounded body reads a fixed-size slice: a `LIMIT`ed sub-select (the
/// engine stops scanning when it is full) feeding the template's question, or
/// a weaker question whose exact answer is a handful of lookups. The title and
/// question change with it, so the card never presents a sample as the whole
/// graph. Default-graph shaped like a [`Fallback`]: sound on a mixed file (its
/// profile is the default graph's), and skipped on a named-graph-only one
/// unless `named_body` is given.
struct Bounded {
    title: &'static str,
    question: &'static str,
    body: &'static str,
    named_body: Option<&'static str>,
    requires: &'static [Cap],
    nonempty: NonEmpty,
}

/// One query template: a body with `{{PLACEHOLDER}}`s, the tier that answers it,
/// and the capabilities it needs (which also gate emission).
struct Template {
    id: &'static str,
    title: &'static str,
    dimension: &'static str,
    question: &'static str,
    /// The default-graph body — used verbatim when the data lives in the
    /// default graph, so classic (graph-free) cards are byte-identical to
    /// before scope awareness existed.
    body: &'static str,
    /// Body when **every** statement lives in a named graph and the default
    /// graph is empty. On such a file the default-graph `body` can only return
    /// zero rows, so a template without a named-scope body is **skipped**
    /// (unless it is already `GRAPH`-native, i.e. requires [`Cap::NamedGraphs`]).
    named_body: Option<&'static str>,
    /// Body when **both** the default graph and named graphs hold data.
    /// `None` falls back to `body`: sound — the profile that instantiated it
    /// was derived from the (non-empty) default graph — but scoped to it, so
    /// the whole-dataset templates (counts, histograms, hubs) provide a
    /// `UNION`-scoped variant instead of silently hiding the named half.
    mixed_body: Option<&'static str>,
    tier: Tier,
    requires: &'static [Cap],
    /// Why the emitted query cannot return zero rows.
    nonempty: NonEmpty,
    /// A weaker body for when `requires` is **not** met: the template degrades
    /// to a still-answerable question instead of vanishing. Without it a
    /// capability that only sharpens a query (`LABELED_CLASS`) would also be
    /// able to delete it — on `hugging-face` the label query would disappear
    /// even though the dataset has labels, which is not an improvement over
    /// shipping one that returns nothing.
    fallback: Option<Fallback>,
    /// Decides emptiness from the card, in **default-graph scope only** (the
    /// card profiles the default graph, so its counts witness nothing about a
    /// `GRAPH`-scoped body). `Some(f)` and `f(card)` true ⇒ the query would
    /// answer nothing ⇒ it is not emitted. The generator's last gate.
    provably_empty: Option<fn(&DatasetCard) -> bool>,
    /// Is `Template::provably_empty` an **equivalence** in default-graph
    /// scope — does `false` prove the query answers, and not merely fail to
    /// prove it empty?
    ///
    /// True only where the card's precompute *is* this query's result:
    /// `top-in-hubs` is `card.in_hubs`, row for row and by construction (see
    /// the in-degree tally in `derive_card_from`). `top-dangling` shares the
    /// hook — no IRI object means nothing can dangle — without the converse, so
    /// it stays honestly undecidable. Nothing in generation reads this; it is
    /// what lets [`audit`] tell a query the card decides from one it does not,
    /// instead of counting both as unknown.
    hook_is_exact: bool,
    /// What the body reads — see [`Scan`] and [`STARTER_SCAN_BUDGET`].
    scan: Scan,
    /// What ships instead when `scan` is over the budget. `None` ⇒ nothing
    /// ships: the template is a question the card's own profile already
    /// answers index-free (counts, predicate and class histograms, hubs,
    /// datatypes, extents), so a sample of it would only be a worse copy.
    bounded: Option<Bounded>,
}

/// The reduced form of a [`Template`], used when its full `requires` are not
/// available. Default-graph shaped (no scope variants), so it is skipped on a
/// named-graph-only file exactly like a template without a `named_body`.
struct Fallback {
    body: &'static str,
    requires: &'static [Cap],
    nonempty: NonEmpty,
}

/// The library. Order is fixed → deterministic output (folded into the hash).
const TEMPLATES: &[Template] = &[
    // --- Overview ---
    Template {
        id: "ov-one-row",
        title: "One statement, now",
        dimension: "overview",
        question: "Return exactly one statement — did this file open and answer?",
        // The smoke test (issue #153): guaranteed one row on ANY non-empty
        // file. A COUNT can honestly return 0 (named-graph-only files) and
        // read as failure; one concrete row is unambiguous.
        body: "SELECT ?s ?p ?o WHERE { ?s ?p ?o } LIMIT 1",
        named_body: Some("SELECT ?g ?s ?p ?o WHERE { GRAPH ?g { ?s ?p ?o } } LIMIT 1"),
        mixed_body: Some(
            "SELECT ?s ?p ?o WHERE { { ?s ?p ?o } UNION { GRAPH ?g { ?s ?p ?o } } } LIMIT 1",
        ),
        tier: Tier::Index,
        requires: &[],
        nonempty: NonEmpty::AnyGraph,
        fallback: None,
        provably_empty: None,
        hook_is_exact: false,
        scan: Scan::Bounded,
        bounded: None,
    },
    Template {
        id: "ov-triples",
        title: "How many statements?",
        dimension: "overview",
        question: "How big is this graph — how many triples?",
        body: "SELECT (COUNT(*) AS ?n) WHERE { ?s ?p ?o }",
        named_body: Some("SELECT (COUNT(*) AS ?n) WHERE { GRAPH ?g { ?s ?p ?o } }"),
        mixed_body: Some(
            "SELECT (COUNT(*) AS ?n) WHERE { { ?s ?p ?o } UNION { GRAPH ?g { ?s ?p ?o } } }",
        ),
        tier: Tier::Summary,
        requires: &[],
        nonempty: NonEmpty::Aggregate,
        fallback: None,
        provably_empty: None,
        hook_is_exact: false,
        scan: Scan::Everything,
        bounded: None,
    },
    Template {
        id: "ov-pred-list",
        title: "What relationships exist?",
        dimension: "overview",
        question: "Which predicates (relationships) appear in the data?",
        body: "SELECT DISTINCT ?p WHERE { ?s ?p ?o }",
        named_body: Some("SELECT DISTINCT ?p WHERE { GRAPH ?g { ?s ?p ?o } }"),
        mixed_body: Some(
            "SELECT DISTINCT ?p WHERE { { ?s ?p ?o } UNION { GRAPH ?g { ?s ?p ?o } } }",
        ),
        tier: Tier::Summary,
        requires: &[],
        nonempty: NonEmpty::AnyGraph,
        fallback: None,
        provably_empty: None,
        hook_is_exact: false,
        scan: Scan::Everything,
        bounded: None,
    },
    Template {
        id: "ov-pred-hist",
        title: "How frequent is each relationship?",
        dimension: "overview",
        question: "How many statements use each predicate?",
        // No ORDER BY — keeps it on the index-free summary fast path; sort client-side.
        body: "SELECT ?p (COUNT(*) AS ?n) WHERE { ?s ?p ?o } GROUP BY ?p",
        named_body: Some("SELECT ?p (COUNT(*) AS ?n) WHERE { GRAPH ?g { ?s ?p ?o } } GROUP BY ?p"),
        mixed_body: Some(
            "SELECT ?p (COUNT(*) AS ?n) WHERE { { ?s ?p ?o } UNION { GRAPH ?g { ?s ?p ?o } } } GROUP BY ?p",
        ),
        tier: Tier::Summary,
        requires: &[],
        // A GROUP BY yields no groups over an empty sequence — but every
        // statement has a predicate, so a non-empty graph has at least one.
        nonempty: NonEmpty::AnyGraph,
        fallback: None,
        provably_empty: None,
        hook_is_exact: false,
        scan: Scan::Everything,
        bounded: None,
    },
    Template {
        id: "ov-ask-pred",
        title: "Does the top predicate occur?",
        dimension: "overview",
        question: "Is the most common predicate present at all?",
        body: "ASK { ?s {{TOP_PRED}} ?o }",
        named_body: Some("ASK { GRAPH ?g { ?s {{TOP_PRED}} ?o } }"),
        mixed_body: None, // the profiled predicate lives in the default graph
        tier: Tier::Summary,
        requires: &[Cap::TopPred],
        // One substitution, from a predicate the card counted; nothing to
        // conjoin it with, so the ASK cannot be false.
        nonempty: NonEmpty::Witnessed,
        fallback: None,
        provably_empty: None,
        hook_is_exact: false,
        scan: Scan::Bounded,
        bounded: None,
    },
    // --- Identity & labels ---
    Template {
        id: "id-sample",
        title: "A real entity to start from",
        dimension: "identity",
        question: "Give me one concrete entity of the most common type.",
        body: "SELECT ?s WHERE { ?s a {{TOP_CLASS}} } LIMIT 1",
        named_body: None,
        mixed_body: None,
        tier: Tier::Index,
        requires: &[Cap::TopClass],
        nonempty: NonEmpty::Witnessed,
        fallback: None,
        provably_empty: None,
        hook_is_exact: false,
        scan: Scan::Bounded,
        bounded: None,
    },
    Template {
        id: "lb-labels",
        title: "Readable names for entities",
        dimension: "labels",
        question: "What are the human-readable names of some entities?",
        //
        // The class is `{{LABELED_CLASS}}`, NOT `{{TOP_CLASS}}`. Both name a
        // class the dataset certainly has, and only one of them is proven to
        // carry the label predicate this body joins it to. Picking the two
        // maxima independently — the class with the most instances, the
        // predicate with the most uses — ships a guaranteed-empty query
        // whenever they fall on different parts of the graph:
        //
        //   mtg           top class `mtg:Ruling` (76,990), which has no
        //                 `schema:name` at all — 0 rows, on a plain
        //                 default-graph file.
        //   hugging-face  top class `hf:Model` (2.9 M); `rdfs:label` occurs
        //                 only on the 64 embedded ontology terms — 0 rows.
        //
        // `LABELED_CLASS` walks `card.classes` in descending instance order and
        // takes the first one a `class_links` row proves carries the predicate.
        // That row is a positive witness (some subject has both statements), so
        // the join cannot be empty — and on a dataset where the top class *is*
        // labelled (the common case: geoadmin, lombardi) it resolves to exactly
        // the top class, leaving those cards byte-identical.
        //
        // Two other shapes were considered:
        //
        //   Drop the class (`?s {{LABEL_PRED}} ?label`). Simplest, and it also
        //   cannot fail — but it answers a strictly weaker question, throws away
        //   the join that is the single most reusable pattern a newcomer copies
        //   out of a starter query, and would rewrite the query on every card
        //   that is already correct.
        //
        //   Emit only when the top class is labelled. Silent and lossy: a
        //   dataset whose labels live off the top class loses its label query
        //   entirely, which is how a reader concludes there are no labels.
        //
        // So: prefer the typed form when the card can prove it, and fall back to
        // the class-free form when it cannot — the case where `class_links` (top
        // 100 rows) truncated the witness away, or where labels sit on untyped
        // subjects. `hugging-face` takes the fallback and answers with 50 rows.
        body: "SELECT ?s ?label WHERE { ?s a {{LABELED_CLASS}} ; {{LABEL_PRED}} ?label } LIMIT 50",
        named_body: None,
        mixed_body: None,
        tier: Tier::Index,
        requires: &[Cap::LabeledClass, Cap::LabelPred],
        nonempty: NonEmpty::Witnessed,
        fallback: Some(Fallback {
            body: "SELECT ?s ?label WHERE { ?s {{LABEL_PRED}} ?label } LIMIT 50",
            requires: &[Cap::LabelPred],
            nonempty: NonEmpty::Witnessed,
        }),
        provably_empty: None,
        hook_is_exact: false,
        scan: Scan::Bounded,
        bounded: None,
    },
    // --- Types ---
    Template {
        id: "ty-class-hist",
        title: "What kinds of things, how many?",
        dimension: "types",
        question: "How many entities of each class are there?",
        body: "SELECT ?c (COUNT(?s) AS ?n) WHERE { ?s a ?c } GROUP BY ?c ORDER BY DESC(?n) LIMIT 50",
        named_body: None,
        mixed_body: None,
        tier: Tier::Index,
        requires: &[Cap::TopClass],
        // Gated on a class existing, and the body substitutes nothing.
        nonempty: NonEmpty::Witnessed,
        fallback: None,
        provably_empty: None,
        hook_is_exact: false,
        scan: Scan::Types,
        bounded: None,
    },
    Template {
        id: "ty-entities",
        title: "How many distinct typed entities?",
        dimension: "types",
        question: "How many distinct entities carry a type?",
        body: "SELECT (COUNT(DISTINCT ?s) AS ?n) WHERE { ?s a [] }",
        named_body: None,
        mixed_body: None,
        tier: Tier::Index,
        requires: &[Cap::TopClass],
        nonempty: NonEmpty::Aggregate,
        fallback: None,
        provably_empty: None,
        hook_is_exact: false,
        scan: Scan::Types,
        bounded: None,
    },
    Template {
        id: "ty-class-shape",
        title: "What does the top class look like?",
        dimension: "types",
        question: "Which predicates describe the most common class?",
        body: "SELECT ?p (COUNT(*) AS ?n) WHERE { ?s a {{TOP_CLASS}} ; ?p ?o } GROUP BY ?p ORDER BY DESC(?n)",
        named_body: None,
        mixed_body: None,
        tier: Tier::Index,
        requires: &[Cap::TopClass],
        // One substitution, conjoined only with a wholly-variable pattern that
        // the class assertion itself already satisfies (`?p ?o` matches the
        // `rdf:type` statement) — so this is not the two-maxima shape.
        nonempty: NonEmpty::Witnessed,
        fallback: None,
        provably_empty: None,
        hook_is_exact: false,
        scan: Scan::ClassStar(Cap::TopClass),
        bounded: Some(Bounded {
            title: "What does the top class look like? (1,000 instances)",
            question: "Which predicates describe a sample of 1,000 instances of the most common class?",
            body: "SELECT ?p (COUNT(*) AS ?n) WHERE { { SELECT ?s WHERE { ?s a {{TOP_CLASS}} } LIMIT 1000 } ?s ?p ?o } GROUP BY ?p ORDER BY DESC(?n)",
            named_body: None,
            requires: &[Cap::TopClass],
            nonempty: NonEmpty::Witnessed,
        }),
    },
    // --- Topology ---
    Template {
        id: "top-class-graph",
        title: "Which classes link to which?",
        dimension: "topology",
        question: "What is the class-to-class schema graph?",
        body: "SELECT ?sC ?p ?oC (COUNT(*) AS ?n) WHERE { ?s a ?sC ; ?p ?o OPTIONAL { ?o a ?oC } } GROUP BY ?sC ?p ?oC ORDER BY DESC(?n)",
        named_body: None,
        mixed_body: None,
        tier: Tier::Index,
        requires: &[Cap::TopClass],
        nonempty: NonEmpty::Witnessed,
        fallback: None,
        provably_empty: None,
        hook_is_exact: false,
        scan: Scan::Everything,
        // No bounded form, deliberately. A sample would join each of its
        // subjects and objects to `?x a ?class`, and an unbound class is a
        // pattern the planner answers by materializing every `rdf:type`
        // statement (2.6 GiB on the OpenCitations sample, for a
        // 1,000-statement sample) — and the answer is `card.class_links`,
        // which the card already carries, exact, index-free.
        bounded: None,
    },
    Template {
        id: "top-out-hubs",
        title: "Most connected sources",
        dimension: "topology",
        question: "Which subjects make the most statements?",
        body: "SELECT ?s (COUNT(*) AS ?d) WHERE { ?s ?p ?o } GROUP BY ?s ORDER BY DESC(?d) LIMIT 25",
        named_body: Some(
            "SELECT ?s (COUNT(*) AS ?d) WHERE { GRAPH ?g { ?s ?p ?o } } GROUP BY ?s ORDER BY DESC(?d) LIMIT 25",
        ),
        mixed_body: Some(
            "SELECT ?s (COUNT(*) AS ?d) WHERE { { ?s ?p ?o } UNION { GRAPH ?g { ?s ?p ?o } } } GROUP BY ?s ORDER BY DESC(?d) LIMIT 25",
        ),
        tier: Tier::Index,
        requires: &[],
        nonempty: NonEmpty::AnyGraph,
        fallback: None,
        provably_empty: None,
        hook_is_exact: false,
        scan: Scan::Everything,
        bounded: None,
    },
    Template {
        id: "top-in-hubs",
        title: "Most referenced entities",
        dimension: "topology",
        question: "Which resources are referenced most often?",
        body: "SELECT ?o (COUNT(*) AS ?d) WHERE { ?s ?p ?o FILTER(!isLiteral(?o)) } GROUP BY ?o ORDER BY DESC(?d) LIMIT 25",
        named_body: Some(
            "SELECT ?o (COUNT(*) AS ?d) WHERE { GRAPH ?g { ?s ?p ?o FILTER(!isLiteral(?o)) } } GROUP BY ?o ORDER BY DESC(?d) LIMIT 25",
        ),
        mixed_body: Some(
            "SELECT ?o (COUNT(*) AS ?d) WHERE { { ?s ?p ?o } UNION { GRAPH ?g { ?s ?p ?o } } FILTER(!isLiteral(?o)) } GROUP BY ?o ORDER BY DESC(?d) LIMIT 25",
        ),
        tier: Tier::Index,
        requires: &[],
        // A graph whose objects are ALL literals (a flat table of values, no
        // `rdf:type` anywhere) has no group to return. `card.in_hubs` is
        // exactly this query's precompute, so in default-graph scope the
        // emptiness is decidable — see `provably_empty`. In `GRAPH` scope the
        // card profiles the wrong half and cannot say.
        nonempty: NonEmpty::Undecidable(
            "no non-literal object exists; decidable (and refused) in default-graph scope only, \
             since the card profiles the default graph and this body may be GRAPH-scoped",
        ),
        fallback: None,
        provably_empty: Some(|card| card.in_hubs.is_empty()),
        // `in_hubs` is this query's own precompute, so the hook decides it in
        // both directions once the body is default-graph scoped.
        hook_is_exact: true,
        scan: Scan::Everything,
        bounded: None,
    },
    Template {
        id: "top-dangling",
        title: "Referenced but undescribed IRIs",
        dimension: "topology",
        question: "Which IRIs are referenced as objects but never described?",
        // `OPTIONAL … FILTER(!BOUND(…))`, not `FILTER NOT EXISTS`: the same
        // rows, but the engine probes the OPTIONAL once per streamed row and
        // stops at the LIMIT, while NOT EXISTS materializes its whole inner
        // pattern first. On the OpenCitations sample's 5.97 M-statement default
        // graph that is 18 MB and 0.02 s against 3.4 GB and 4.8 s.
        body: "SELECT ?o WHERE { ?s ?p ?o FILTER(isIRI(?o)) OPTIONAL { ?o ?p2 ?o2 } FILTER(!BOUND(?p2)) } LIMIT 100",
        named_body: Some(
            "SELECT ?o WHERE { GRAPH ?g { ?s ?p ?o FILTER(isIRI(?o)) } FILTER NOT EXISTS { GRAPH ?h { ?o ?p2 ?o2 } } } LIMIT 100",
        ),
        mixed_body: Some(
            "SELECT ?o WHERE { { ?s ?p ?o } UNION { GRAPH ?g { ?s ?p ?o } } FILTER(isIRI(?o)) FILTER NOT EXISTS { ?o ?p2 ?o2 } FILTER NOT EXISTS { GRAPH ?h { ?o ?p3 ?o3 } } } LIMIT 100",
        ),
        tier: Tier::Index,
        requires: &[],
        // The honest one: a fully-described graph legitimately has none, and
        // "is every referenced IRI described?" is precisely what the card does
        // not record. Only the trivial half is decidable (no IRI object at all).
        nonempty: NonEmpty::Undecidable(
            "a fully-described graph has no dangling IRI — emptiness here is the answer, \
             not a failure, and the card does not record which objects are also subjects",
        ),
        fallback: None,
        provably_empty: Some(|card| card.in_hubs.is_empty()),
        hook_is_exact: false,
        scan: Scan::Everything,
        bounded: Some(Bounded {
            title: "Referenced but undescribed IRIs (1,000 statements)",
            question: "Which IRIs referenced by a sample of 1,000 statements are never described in the default graph?",
            body: "SELECT DISTINCT ?o WHERE { { SELECT ?o WHERE { ?s ?p ?o } LIMIT 1000 } FILTER(isIRI(?o)) OPTIONAL { ?o ?p2 ?o2 } FILTER(!BOUND(?p2)) } LIMIT 100",
            named_body: None,
            requires: &[],
            nonempty: NonEmpty::Undecidable(
                "a sample of a fully-described graph has no dangling IRI, and the card does not record which objects are also subjects",
            ),
        }),
    },
    Template {
        id: "top-reach",
        title: "What's reachable by following one relation?",
        dimension: "connectivity",
        question: "Following the most common entity-to-entity relation, what is reachable from a node?",
        //
        // Was `{{HUB_IRI}} {{TOP_PRED}}+ ?y`: the busiest subject and the most
        // frequent predicate, chosen independently and then conjoined — the
        // same defect as `lb-labels`, and live. On `hugging-face` the hub is a
        // User and the top predicate `schema:keywords` (which only Models
        // carry): 0 rows. Nothing in the card ties a specific subject to a
        // specific predicate, so that pair can never be witnessed and the seed
        // has to come from the relation itself.
        //
        // The sub-SELECT picks one real subject OF the relation, so the outer
        // path always has at least the seed's own edge to return; the seed stays
        // a single bound term, so the traversal costs what it did before (a
        // bare `?x p+ ?y` would enumerate the whole closure, and these queries
        // are measured at build time).
        //
        // `OBJECT_PRED`, not `TOP_PRED`: the most frequent predicate is usually
        // a labelling one, whose objects are literals — a `+` over it can never
        // walk past one hop. A `class_links` row with a non-literal `o_class`
        // proves the relation goes entity-to-entity. A self-referential one
        // (`s_class == o_class`) would chain deeper still, but its closure is
        // unbounded — `hf:follows` is 886 k edges of social graph — so
        // frequency, not recursion, picks the winner.
        body: "SELECT ?x ?y WHERE { { SELECT ?x WHERE { ?x {{OBJECT_PRED}} ?o } LIMIT 1 } ?x {{OBJECT_PRED}}+ ?y } LIMIT 100",
        named_body: None,
        mixed_body: None,
        tier: Tier::Index,
        requires: &[Cap::ObjectPred],
        nonempty: NonEmpty::Witnessed,
        fallback: None,
        provably_empty: None,
        hook_is_exact: false,
        scan: Scan::Bounded,
        bounded: None,
    },
    // --- Connectivity / completeness ---
    Template {
        id: "cmp-coverage",
        title: "Do all entities of the labelled class have a label?",
        dimension: "connectivity",
        question: "How complete is labelling on the class that carries labels?",
        // `{{LABELED_CLASS}}` for the same reason as `lb-labels`, plus one of
        // its own: with `{{TOP_CLASS}}` this reported `76990 / 0` on mtg — a
        // row, so never caught by a zero-rows gate, and a measurement of the
        // wrong class. Pairing it with `lb-labels` also keeps the two label
        // queries talking about the same entities.
        body: "SELECT (COUNT(?s) AS ?total) (COUNT(?l) AS ?have) WHERE { ?s a {{LABELED_CLASS}} OPTIONAL { ?s {{LABEL_PRED}} ?l } }",
        named_body: None,
        mixed_body: None,
        tier: Tier::Index,
        requires: &[Cap::LabeledClass, Cap::LabelPred],
        nonempty: NonEmpty::Aggregate,
        fallback: None,
        provably_empty: None,
        hook_is_exact: false,
        scan: Scan::Class(Cap::LabeledClass),
        bounded: Some(Bounded {
            title: "Do the labelled class's entities have a label? (1,000 instances)",
            question: "How complete is labelling on a sample of 1,000 instances of the class that carries labels?",
            body: "SELECT (COUNT(?s) AS ?total) (COUNT(?l) AS ?have) WHERE { { SELECT ?s WHERE { ?s a {{LABELED_CLASS}} } LIMIT 1000 } OPTIONAL { ?s {{LABEL_PRED}} ?l } }",
            named_body: None,
            requires: &[Cap::LabeledClass, Cap::LabelPred],
            nonempty: NonEmpty::Aggregate,
        }),
    },
    // --- Links ---
    Template {
        id: "lk-sameas",
        title: "Aligned to which external datasets?",
        dimension: "links",
        question: "Which entity-alignment predicates are used, and how often?",
        // The VALUES list must cover the gate exactly. It listed three of the
        // four predicates `signals.link_predicates` is detected from, so a
        // dataset aligned only with `skos:closeMatch` passed the gate and then
        // grouped nothing. Adding the fourth makes emptiness unreachable.
        body: "SELECT ?p (COUNT(*) AS ?n) WHERE { ?s ?p ?o VALUES ?p { owl:sameAs skos:exactMatch skos:closeMatch rdfs:seeAlso } } GROUP BY ?p",
        named_body: None,
        mixed_body: None,
        tier: Tier::Index,
        requires: &[Cap::Link],
        nonempty: NonEmpty::Witnessed,
        fallback: None,
        provably_empty: None,
        hook_is_exact: false,
        scan: Scan::Preds(LINK_PREDICATE_IRIS),
        bounded: Some(Bounded {
            title: "Aligned to which external datasets?",
            question: "Which entity-alignment predicates are used?",
            body: "SELECT ?p WHERE { VALUES ?p { owl:sameAs skos:exactMatch skos:closeMatch rdfs:seeAlso } FILTER EXISTS { ?s ?p ?o } }",
            named_body: None,
            requires: &[Cap::Link],
            nonempty: NonEmpty::Witnessed,
        }),
    },
    Template {
        id: "lk-external",
        title: "Which predicates link out?",
        dimension: "links",
        question: "Which predicates point to IRIs outside this dataset?",
        // `EXTERNAL_IRI` is the witness that the FILTER keeps something: an IRI
        // in `classes` or `in_hubs` that does not start with the base IRI.
        // Without it a self-contained dataset — every object either a literal
        // or an in-namespace IRI — emitted a query that grouped nothing.
        body: "SELECT ?p (COUNT(*) AS ?n) WHERE { ?s ?p ?o FILTER(isIRI(?o) && !STRSTARTS(STR(?o), \"{{BASE_IRI}}\")) } GROUP BY ?p ORDER BY DESC(?n) LIMIT 50",
        named_body: None,
        mixed_body: None,
        tier: Tier::Index,
        requires: &[Cap::BaseIri, Cap::ExternalIri],
        nonempty: NonEmpty::Witnessed,
        fallback: None,
        provably_empty: None,
        hook_is_exact: false,
        scan: Scan::Everything,
        bounded: Some(Bounded {
            title: "Which predicates link out? (1,000 statements)",
            question: "In a sample of 1,000 statements, which predicates point to IRIs outside this dataset?",
            body: "SELECT ?p (COUNT(*) AS ?n) WHERE { { SELECT ?p ?o WHERE { ?s ?p ?o } LIMIT 1000 } FILTER(isIRI(?o) && !STRSTARTS(STR(?o), \"{{BASE_IRI}}\")) } GROUP BY ?p ORDER BY DESC(?n) LIMIT 50",
            named_body: None,
            requires: &[Cap::BaseIri, Cap::ExternalIri],
            nonempty: NonEmpty::Undecidable(
                "the card records an IRI outside the base IRI somewhere in the graph, not in the 1,000-statement sample this body reads",
            ),
        }),
    },
    // --- Literals ---
    Template {
        id: "lt-datatypes",
        title: "What value types appear?",
        dimension: "literals",
        question: "Which literal datatypes are used, and how often?",
        body: "SELECT ?dt (COUNT(*) AS ?n) WHERE { ?s ?p ?o FILTER(isLiteral(?o)) } GROUP BY (DATATYPE(?o) AS ?dt) ORDER BY DESC(?n)",
        named_body: None,
        mixed_body: None,
        tier: Tier::Index,
        requires: &[Cap::HasLiterals],
        nonempty: NonEmpty::Witnessed,
        fallback: None,
        provably_empty: None,
        hook_is_exact: false,
        scan: Scan::Everything,
        bounded: None,
    },
    Template {
        id: "lt-langs",
        title: "What languages?",
        dimension: "literals",
        question: "Which language tags appear on literals, and how often?",
        body: "SELECT ?l (COUNT(*) AS ?n) WHERE { ?s ?p ?o FILTER(isLiteral(?o)) } GROUP BY (LANG(?o) AS ?l) ORDER BY DESC(?n)",
        named_body: None,
        mixed_body: None,
        tier: Tier::Index,
        requires: &[Cap::HasLiterals],
        nonempty: NonEmpty::Witnessed,
        fallback: None,
        provably_empty: None,
        hook_is_exact: false,
        scan: Scan::Everything,
        bounded: None,
    },
    Template {
        id: "lt-numrange",
        title: "Range of a numeric property",
        dimension: "literals",
        question: "What is the min / average / max of the top numeric property?",
        // BIND the cast first — aggregating over a function expression is rejected.
        body: "SELECT (MIN(?v) AS ?lo) (AVG(?v) AS ?avg) (MAX(?v) AS ?hi) WHERE { ?s {{NUM_PRED}} ?o BIND(xsd:double(?o) AS ?v) }",
        named_body: None,
        mixed_body: None,
        tier: Tier::Index,
        requires: &[Cap::NumPred],
        nonempty: NonEmpty::Aggregate,
        fallback: None,
        provably_empty: None,
        hook_is_exact: false,
        scan: Scan::Pred(Cap::NumPred),
        bounded: None,
    },
    // --- Time ---
    Template {
        id: "ti-extent",
        title: "What period does it span?",
        dimension: "time",
        question: "What is the earliest and latest value of the top time predicate?",
        body: "SELECT (MIN(?d) AS ?from) (MAX(?d) AS ?to) WHERE { ?s {{TIME_PRED}} ?d }",
        named_body: None,
        mixed_body: None,
        tier: Tier::Index,
        requires: &[Cap::TimePred],
        nonempty: NonEmpty::Aggregate,
        fallback: None,
        provably_empty: None,
        hook_is_exact: false,
        scan: Scan::Pred(Cap::TimePred),
        bounded: None,
    },
    Template {
        id: "ti-histogram",
        title: "Distribution over time",
        dimension: "time",
        question: "How are entities distributed by year?",
        body: "SELECT ?yr (COUNT(*) AS ?n) WHERE { ?s {{TIME_PRED}} ?d BIND(SUBSTR(STR(?d),1,4) AS ?yr) } GROUP BY ?yr ORDER BY ?yr",
        named_body: None,
        mixed_body: None,
        tier: Tier::Index,
        requires: &[Cap::TimePred],
        nonempty: NonEmpty::Witnessed,
        fallback: None,
        provably_empty: None,
        hook_is_exact: false,
        scan: Scan::Pred(Cap::TimePred),
        bounded: None,
    },
    // --- Space (WKT is always CRS84 lon/lat) ---
    Template {
        id: "sp-bbox",
        title: "Geographic extent",
        dimension: "space",
        question: "What is the bounding box of the wgs84 coordinates? (lon/lat)",
        // NOTE: the two predicates are conjoined on ONE subject, while the gate
        // (`geo_latlong`) is `lat seen` AND `long seen`, tallied independently —
        // the same shape as the `lb-labels` bug. It cannot produce zero rows
        // (an un-grouped aggregate always returns one), so the worst case is a
        // row of unbound values rather than a missing answer, and the card
        // cannot do better: `class_links` collapses every untyped subject into
        // one `(untyped)` bucket, so rows for `wgs:lat` and `wgs:long` under it
        // are not evidence that any single subject carries both.
        body: "SELECT (MIN(?lon) AS ?minLon) (MIN(?lat) AS ?minLat) (MAX(?lon) AS ?maxLon) (MAX(?lat) AS ?maxLat) WHERE { ?s wgs:long ?lon ; wgs:lat ?lat }",
        named_body: None,
        mixed_body: None,
        tier: Tier::Index,
        requires: &[Cap::GeoLatLong],
        nonempty: NonEmpty::Aggregate,
        fallback: None,
        provably_empty: None,
        hook_is_exact: false,
        scan: Scan::Preds(&[WGS_LAT_IRI, WGS_LONG_IRI]),
        bounded: None,
    },
    Template {
        id: "sp-within",
        title: "Features inside a box",
        dimension: "space",
        question: "Which features fall inside the dataset's bounding box? (WKT is lon/lat)",
        //
        // The access path is `{{WKT_PATH}}`, read off the predicates the card
        // recorded, because the fixed `geo:hasGeometry/geo:asWKT` was a third
        // instance of the same bug — and a live one. The gate, `signals.geo_wkt`,
        // is a three-way OR (`geo:asWKT` seen, OR `geo:hasGeometry` seen, OR a
        // `wktLiteral` datatype seen) while the body demanded BOTH steps of the
        // chain: `geoadmin` hangs `geo:asWKT` straight off each District and has
        // no `geo:hasGeometry` at all, so its published card ships a query that
        // cannot match — 0 rows on 52,959 geometries. `geo:hasGeometry?/geo:asWKT`
        // covers both layouts in one path (the optional step binds `?s` to the
        // feature when there is a geometry node, to the feature itself when the
        // WKT hangs off it directly).
        body: "SELECT ?s WHERE { ?s {{WKT_PATH}} ?w FILTER(geof:sfWithin(?w, \"{{BBOX_POLYGON}}\"^^geo:wktLiteral)) } LIMIT 100",
        named_body: None,
        mixed_body: None,
        tier: Tier::Index,
        requires: &[Cap::WktPath, Cap::Bbox],
        // The path is witnessed; the FILTER is not, and cannot be. The box is
        // derived from `wgs84:lat`/`wgs84:long` literals — a different signal
        // from the geometries this body reads, on possibly different subjects —
        // and a GeoSPARQL `wktLiteral` may carry a projected CRS whose
        // coordinates fall outside any lon/lat box, so not even the whole-world
        // fallback box is a proof. Emptiness here means "nothing in that box",
        // which is a real answer about the data, and the box is the parameter
        // the reader is meant to edit.
        nonempty: NonEmpty::Undecidable(
            "the box is derived from wgs84 lat/long literals, not from the WKT geometries this \
             query reads, and the card records no coordinate extent for them",
        ),
        fallback: None,
        provably_empty: None,
        hook_is_exact: false,
        scan: Scan::Preds(&[GEO_ASWKT]),
        bounded: Some(Bounded {
            title: "Features inside a box (1,000 geometries)",
            question: "Which of a sample of 1,000 geometries fall inside the dataset's bounding box? (WKT is lon/lat)",
            body: "SELECT ?s WHERE { { SELECT ?s ?w WHERE { ?s {{WKT_PATH}} ?w } LIMIT 1000 } FILTER(geof:sfWithin(?w, \"{{BBOX_POLYGON}}\"^^geo:wktLiteral)) } LIMIT 100",
            named_body: None,
            requires: &[Cap::WktPath, Cap::Bbox],
            nonempty: NonEmpty::Undecidable(
                "the box is derived from wgs84 lat/long literals, not from the WKT geometries this query reads, and the card records no coordinate extent for them",
            ),
        }),
    },
    // --- Named graphs ---
    Template {
        id: "ng-list",
        title: "What graphs partition this?",
        dimension: "graphs",
        question: "Which named graphs does the dataset contain?",
        body: "SELECT DISTINCT ?g WHERE { GRAPH ?g { ?s ?p ?o } }",
        named_body: None,
        mixed_body: None,
        tier: Tier::Index,
        requires: &[Cap::NamedGraphs],
        nonempty: NonEmpty::Witnessed,
        fallback: None,
        provably_empty: None,
        hook_is_exact: false,
        scan: Scan::NamedGraphs,
        bounded: Some(Bounded {
            title: "What graphs partition this? (first 100)",
            question: "Which named graphs does the dataset contain? (the first 100)",
            body: "SELECT DISTINCT ?g WHERE { GRAPH ?g { ?s ?p ?o } } LIMIT 100",
            named_body: Some(
                "SELECT DISTINCT ?g WHERE { GRAPH ?g { ?s ?p ?o } } LIMIT 100",
            ),
            requires: &[Cap::NamedGraphs],
            nonempty: NonEmpty::Witnessed,
        }),
    },
    Template {
        id: "ng-sizes",
        title: "Which graphs are biggest?",
        dimension: "graphs",
        question: "Which named graphs hold the most statements?",
        // LIMIT keeps this a starter on a file with tens of thousands of graphs.
        body: "SELECT ?g (COUNT(*) AS ?n) WHERE { GRAPH ?g { ?s ?p ?o } } GROUP BY ?g ORDER BY DESC(?n) LIMIT 25",
        named_body: None,
        mixed_body: None,
        tier: Tier::Index,
        requires: &[Cap::NamedGraphs],
        nonempty: NonEmpty::Witnessed,
        fallback: None,
        provably_empty: None,
        hook_is_exact: false,
        scan: Scan::NamedGraphs,
        bounded: None,
    },
    Template {
        id: "ng-sample",
        title: "A peek inside the graphs",
        dimension: "graphs",
        question: "What do statements in the named graphs look like?",
        // `?g` in the projection on purpose: each sample row says where it lives.
        body: "SELECT ?g ?s ?p ?o WHERE { GRAPH ?g { ?s ?p ?o } } LIMIT 10",
        named_body: None,
        mixed_body: None,
        tier: Tier::Index,
        requires: &[Cap::NamedGraphs],
        nonempty: NonEmpty::Witnessed,
        fallback: None,
        provably_empty: None,
        hook_is_exact: false,
        scan: Scan::Bounded,
        bounded: None,
    },
    // --- Statements about statements (RDF-star) ---
    //
    // Emitted only for a dataset whose own statements were seen to quote
    // other statements, and written in the RDF-star surface `<< s p o >>`,
    // which is what the SPARQL parser accepts (`docs/sparql.md#rdf-star`).
    // The RDF 1.2 spelling `<<( s p o )>>` is an EXPORT surface, not a query
    // one, and a body written in it would not parse — the worst thing a card
    // can carry.
    //
    // None of these has a `named_body`: the profile they are instantiated from
    // is derived from the default graph, so on a named-graph-only file the
    // capabilities are simply absent and nothing is emitted.
    Template {
        id: "qt-sample",
        title: "A statement someone made a statement about",
        dimension: "statements",
        question: "Which statements does this dataset say something about, and what does it say?",
        // The family's entry point, and the one shape worth copying: the inner
        // variables bind the quoted statement's own subject, predicate and
        // object, so one row shows both the assertion and what qualifies it.
        // The annotation predicate is pinned rather than left a variable so
        // the scan routes on a predicate instead of walking the whole index.
        body: "SELECT ?s ?p ?o ?value WHERE { << ?s ?p ?o >> {{ANNOTATION_PRED}} ?value } LIMIT 25",
        named_body: None,
        mixed_body: None,
        tier: Tier::Index,
        // One substitution, from a predicate the derivation counted on a
        // statement whose subject really is a quoted triple.
        requires: &[Cap::AnnotationPred],
        nonempty: NonEmpty::Witnessed,
        fallback: None,
        provably_empty: None,
        hook_is_exact: false,
        scan: Scan::Bounded,
        bounded: None,
    },
    Template {
        id: "qt-about",
        title: "What gets said about statements?",
        dimension: "statements",
        question: "Which predicates qualify a statement rather than an entity, and how often?",
        // The annotation schema: the `ov-pred-hist` of the star layer. The
        // annotation predicate is a variable here on purpose — that IS the
        // question — so the gate is the pure "such statements exist" bool.
        body: "SELECT ?about (COUNT(*) AS ?n) WHERE { << ?s ?p ?o >> ?about ?value } GROUP BY ?about ORDER BY DESC(?n) LIMIT 50",
        named_body: None,
        mixed_body: None,
        tier: Tier::Index,
        requires: &[Cap::AnnotatedStatements],
        // A GROUP BY yields no group over an empty sequence — but the card
        // counted at least one statement whose subject is a quoted triple, and
        // every statement has a predicate to group by.
        nonempty: NonEmpty::Witnessed,
        fallback: None,
        provably_empty: None,
        hook_is_exact: false,
        scan: Scan::Annotations,
        bounded: None,
    },
    Template {
        id: "qt-qualifiers",
        title: "Who (or what) qualifies the assertions?",
        dimension: "statements",
        question: "How many assertions does each distinct qualifier value account for?",
        // "Count assertions by whatever qualifies them" — the recorder, the
        // source, the confidence band. Grouping on the VALUE, not on the
        // predicate, is what makes this a different question from `qt-about`.
        body: "SELECT ?value (COUNT(*) AS ?n) WHERE { << ?s ?p ?o >> {{ANNOTATION_PRED}} ?value } GROUP BY ?value ORDER BY DESC(?n) LIMIT 50",
        named_body: None,
        mixed_body: None,
        tier: Tier::Index,
        requires: &[Cap::AnnotationPred],
        nonempty: NonEmpty::Witnessed,
        fallback: None,
        provably_empty: None,
        hook_is_exact: false,
        scan: Scan::Pred(Cap::AnnotationPred),
        bounded: None,
    },
    Template {
        id: "qt-coverage",
        title: "How much of the data is qualified?",
        dimension: "statements",
        question: "Of the statements that get annotated most, how many actually carry an annotation?",
        // The `cmp-coverage` of the star layer, and the question a provenance
        // graph is really about: 40,000 assertions, 300 of them sourced.
        //
        // `{{ANNOTATED_PRED}}` is written twice — once in a regular pattern to
        // enumerate the assertions, once inside the quoted pattern to reach
        // their annotations. `?s`/`?o` are bound by the regular pattern, so
        // the quoted occurrence lowers to a join on them (`sameTerm`), not a
        // second enumeration. The two predicates conjoined here are the ONE
        // pair the derivation saw on a single statement
        // (`signals.annotated_statement`), never two independent maxima.
        body: "SELECT (COUNT(*) AS ?asserted) (COUNT(?value) AS ?qualified) WHERE { ?s {{ANNOTATED_PRED}} ?o OPTIONAL { << ?s {{ANNOTATED_PRED}} ?o >> {{ANNOTATION_PRED}} ?value } }",
        named_body: None,
        mixed_body: None,
        tier: Tier::Index,
        requires: &[Cap::AnnotatedPred, Cap::AnnotationPred],
        nonempty: NonEmpty::Aggregate,
        fallback: None,
        provably_empty: None,
        hook_is_exact: false,
        scan: Scan::Pred(Cap::AnnotatedPred),
        bounded: Some(Bounded {
            title: "How much of the data is qualified? (1,000 assertions)",
            question: "Of a sample of 1,000 statements of the most-annotated kind, how many carry an annotation?",
            body: "SELECT (COUNT(*) AS ?asserted) (COUNT(?value) AS ?qualified) WHERE { { SELECT ?s ?o WHERE { ?s {{ANNOTATED_PRED}} ?o } LIMIT 1000 } OPTIONAL { << ?s {{ANNOTATED_PRED}} ?o >> {{ANNOTATION_PRED}} ?value } }",
            named_body: None,
            requires: &[Cap::AnnotatedPred, Cap::AnnotationPred],
            nonempty: NonEmpty::Aggregate,
        }),
    },
    Template {
        id: "qt-quoted-object",
        title: "Statements held as values",
        dimension: "statements",
        question: "Which statements are referenced as the value of another statement?",
        // The OTHER position a triple term stands in — `:claim :states
        // << s p o >>` — and a separate capability, because a dataset can have
        // one shape and not the other: a query written for the subject
        // position returns nothing at all on an object-position file (and the
        // header's presence bit cannot tell them apart).
        body: "SELECT ?s ?qs ?qp ?qo WHERE { ?s {{QUOTING_PRED}} << ?qs ?qp ?qo >> } LIMIT 25",
        named_body: None,
        mixed_body: None,
        tier: Tier::Index,
        requires: &[Cap::QuotingPred],
        nonempty: NonEmpty::Witnessed,
        fallback: None,
        provably_empty: None,
        hook_is_exact: false,
        scan: Scan::Bounded,
        bounded: None,
    },
];

/// What the template behind an emitted query claims about its emptiness — the
/// `NonEmpty` declaration, read back by id.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Claim {
    /// The template asserts the emitted query cannot come back empty
    /// (`NonEmpty::AnyGraph` / `NonEmpty::Aggregate` / `NonEmpty::Witnessed`).
    CannotBeEmpty,
    /// The template admits the card cannot decide it
    /// (`NonEmpty::Undecidable`).
    Undecidable,
    /// No template of this revision owns the id — a curated query, or one an
    /// older revision wrote. It claims nothing, so nothing is contradicted.
    Unknown,
}

/// The [`Claim`] behind a shipped query id.
///
/// The build measures every starter query against the finished file
/// (`commands::buildinfo`), which makes emptiness a **measured** fact rather
/// than a derived one — and where measurement and this claim disagree, the
/// claim is wrong. A query the table swears cannot be empty and that then
/// answers nothing is a defect in the table, not a fact about the dataset, and
/// `commands::build` says so out loud and records it. `Undecidable` is the
/// opposite: the template said in advance it could not know, so a measured zero
/// is expected news, not a contradiction.
///
/// This is the claim of the template's **exact** body. A template can also
/// ship a `Bounded` form with a claim of its own (a sample of a graph that has
/// dangling IRIs need not contain one); [`claim_of_query`] reads the body and
/// answers for whichever form it is.
pub fn claim_of(id: &str) -> Claim {
    match TEMPLATES.iter().find(|t| t.id == id) {
        Some(t) => claim_from(t.nonempty),
        None => Claim::Unknown,
    }
}

/// The [`Claim`] behind a shipped query, read from its **body** as well as its
/// id — the form to use whenever the SPARQL is at hand, because the exact and
/// the bounded form of one template claim different things.
pub fn claim_of_query(id: &str, sparql: &str) -> Claim {
    let Some(t) = TEMPLATES.iter().find(|t| t.id == id) else {
        return Claim::Unknown;
    };
    match variant_of(t, strip_prefixes(sparql).trim()) {
        Some(v) => claim_from(v.nonempty),
        None => claim_from(t.nonempty),
    }
}

fn claim_from(nonempty: NonEmpty) -> Claim {
    match nonempty {
        NonEmpty::Undecidable(_) => Claim::Undecidable,
        _ => Claim::CannotBeEmpty,
    }
}

/// Which of a template's forms a published body is, and the bindings it gave
/// the placeholders.
struct Variant {
    pattern: &'static str,
    binds: Binds,
    nonempty: NonEmpty,
    /// The [`Bounded`] form — a sample, so the card's whole-graph precomputes
    /// stop deciding it in both directions (see `Template::hook_is_exact`).
    bounded: bool,
}

/// Match a published body against every form of `t`: the exact body in each
/// scope, the fallback, the bounded form, then the bodies earlier revisions
/// wrote. The *values* decide a verdict, so two revisions sharing a pattern is
/// not a problem — `revision` already says which one a re-card would write.
fn variant_of(t: &Template, body: &str) -> Option<Variant> {
    let mut forms: Vec<(&'static str, NonEmpty, bool)> = Vec::new();
    for p in [Some(t.body), t.named_body, t.mixed_body]
        .into_iter()
        .flatten()
    {
        forms.push((p, t.nonempty, false));
    }
    if let Some(f) = &t.fallback {
        forms.push((f.body, f.nonempty, false));
    }
    if let Some(b) = &t.bounded {
        for p in [Some(b.body), b.named_body].into_iter().flatten() {
            forms.push((p, b.nonempty, true));
        }
    }
    for l in LEGACY_BODIES.iter().filter(|l| l.id == t.id) {
        forms.push((l.body, t.nonempty, false));
    }
    // The bodies of one template are not prefixes of each other, so an exact
    // match is unambiguous.
    forms.into_iter().find_map(|(pattern, nonempty, bounded)| {
        match_pattern(pattern, body).map(|binds| Variant {
            pattern,
            binds,
            nonempty,
            bounded,
        })
    })
}

/// A query's body without the `PREFIX` lines every generated query carries.
fn strip_prefixes(sparql: &str) -> String {
    sparql
        .lines()
        .filter(|l| !l.starts_with("PREFIX"))
        .collect::<Vec<_>>()
        .join("\n")
}

/// Where the dataset's statements live, decided from the card's own counts —
/// so the emitted queries address the graph(s) that actually hold data instead
/// of scanning a default graph the card itself records as empty.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum GraphScope {
    /// No named graphs — bodies are used verbatim, so classic cards are
    /// byte-identical to pre-scope-awareness builds.
    DefaultOnly,
    /// Every statement lives in a named graph and the default graph is empty
    /// (`triple_count == 0 && named_graph_count > 0`) — a bare `{ ?s ?p ?o }`
    /// can only ever return zero rows here.
    NamedOnly,
    /// Both the default graph and named graphs hold statements.
    Mixed,
}

impl GraphScope {
    fn of(card: &DatasetCard) -> Self {
        if card.named_graph_count == 0 {
            GraphScope::DefaultOnly
        } else if card.triple_count == 0 {
            GraphScope::NamedOnly
        } else {
            GraphScope::Mixed
        }
    }
}

/// The dataset's resolved vocabulary, drawn from the card profile.
///
/// The *jointly derived* fields — [`Caps::labeled_class`], [`Caps::object_pred`],
/// [`Caps::wkt_path`], [`Caps::external_iri`] — are the point of this struct: each
/// is resolved from a `class_links` row (or a predicate list) that **witnesses**
/// the pattern its template will write, rather than from an independent ranking
/// that merely says the term exists somewhere in the graph.
struct Caps {
    top_class: Option<String>,
    top_pred: Option<String>,
    labeled_class: Option<String>,
    label_pred: Option<String>,
    object_pred: Option<String>,
    time_pred: Option<String>,
    num_pred: Option<String>,
    base_iri: Option<String>,
    external_iri: bool,
    wkt_path: Option<String>,
    bbox_polygon: Option<String>,
    geo_latlong: bool,
    named_graphs: bool,
    link: bool,
    has_literals: bool,
    annotated_statements: bool,
    annotation_pred: Option<String>,
    annotated_pred: Option<String>,
    quoting_pred: Option<String>,
}

impl Caps {
    fn from_card(card: &DatasetCard) -> Self {
        let s = &card.signals;
        // The most frequent predicate that is not rdf:type (the interesting
        // relation), falling back to whatever is most frequent.
        let top_pred = card
            .predicates
            .iter()
            .map(|(p, _)| p)
            .find(|p| p.as_str() != RDF_TYPE)
            .or_else(|| card.predicates.first().map(|(p, _)| p))
            .cloned();

        // LABELED_CLASS — the most populous class the card can PROVE carries the
        // label predicate. `card.classes` is ordered by instance count, so the
        // first hit is the biggest labelled class, and it equals `top_class`
        // whenever the top class is labelled (the common case, which therefore
        // produces exactly the query it produced before). A `class_links` row is
        // a positive witness — some subject really has both statements — so a
        // hit is proof, and a miss (a truncated top-100 list, or labels only on
        // untyped subjects) is merely absence of proof, which is why the
        // template keeps a class-free fallback rather than vanishing.
        let label_pred = s.label_predicate.clone();
        let labeled_class = label_pred.as_ref().and_then(|lp| {
            card.classes
                .iter()
                .map(|(c, _)| c)
                .find(|c| class_carries(card, c, lp))
                .cloned()
        });

        // OBJECT_PRED — the most frequent relation the card can PROVE points at
        // something other than a literal, i.e. one a path query can walk.
        // `class_links` is ordered by count and excludes `rdf:type` rows.
        let object_pred = card
            .class_links
            .iter()
            .find(|l| l.o_class != O_LITERAL && l.predicate != RDF_TYPE)
            .map(|l| l.predicate.clone());

        // WKT_PATH — how this dataset actually hangs a geometry off a subject.
        // Read from the predicate list (capped at the top 100, so a miss can
        // only lose the query, never emit a broken one).
        let has_pred = |iri: &str| card.predicates.iter().any(|(p, _)| p == iri);
        let wkt_path = has_pred(GEO_ASWKT).then(|| {
            if has_pred(GEO_HASGEOMETRY) {
                // The optional step covers BOTH layouts at once: `?s` binds to
                // the feature when a geometry node sits in between, and to the
                // feature itself when the WKT hangs off it directly.
                "geo:hasGeometry?/geo:asWKT".to_string()
            } else {
                "geo:asWKT".to_string()
            }
        });
        let bbox_polygon = wkt_path.is_some().then(|| bbox_polygon(s.spatial_bbox));

        // EXTERNAL_IRI — an IRI the card records that does NOT start with the
        // dataset's base IRI, so the "links pointing out" filter keeps at least
        // one statement. Classes count: `?s a foaf:Person` is an IRI object like
        // any other. Blank nodes do not — the query filters on `isIRI`.
        let external_iri = s.base_iri.as_deref().is_some_and(|base| {
            card.classes
                .iter()
                .chain(card.in_hubs.iter())
                .any(|(term, _)| {
                    let iri = term.trim_start_matches('<').trim_end_matches('>');
                    !term.starts_with("_:") && !iri.starts_with(base)
                })
        });

        // RDF-star. The presence signal the card *displays* is read off the
        // header at display time — true for every file ever built, which is
        // what makes it honest about the already-published corpus, and useless
        // here: it names no vocabulary and cannot be written into a query. So
        // the `qt-*` family is gated on the profile derived from the
        // statements instead, which a card only has if it was derived after
        // this existed. Presence keeps answering on old files; queries arrive
        // with the next build.
        //
        // `ANNOTATED_PRED` and `ANNOTATION_PRED` come from the ONE pair the
        // derivation saw on a single statement, never from the two rankings
        // independently — see `Cap::joint_with`.
        let witness = annotated_statement(card);
        let annotated_pred = witness.map(|(quoted, _)| quoted.to_string());
        // The witnessed annotating predicate when there is one — so the pair
        // `qt-coverage` writes really met, and so the whole family talks about
        // one predicate (the reason `cmp-coverage` shares `lb-labels`' class).
        // Otherwise the plain ranking, which is all the single-substitution
        // bodies need; `ANNOTATED_PRED` is then absent and nothing conjoins.
        let annotation_pred = witness
            .map(|(_, about)| about.to_string())
            .or_else(|| s.annotation_predicates.first().cloned());

        Caps {
            top_class: card.classes.first().map(|(c, _)| c.clone()),
            top_pred,
            labeled_class,
            label_pred,
            object_pred,
            time_pred: s.time_predicates.first().cloned(),
            num_pred: s.numeric_predicates.first().cloned(),
            base_iri: s.base_iri.clone(),
            external_iri,
            wkt_path,
            bbox_polygon,
            geo_latlong: s.geo_latlong,
            named_graphs: card.named_graph_count > 0,
            link: !s.link_predicates.is_empty(),
            has_literals: !card.datatypes.is_empty(),
            annotated_statements: !s.annotation_predicates.is_empty(),
            annotation_pred,
            annotated_pred,
            quoting_pred: s.quoting_predicates.first().cloned(),
        }
    }

    /// The text substituted for a capability's placeholder, if it has one.
    fn value(&self, cap: Cap) -> Option<&str> {
        match cap {
            Cap::TopClass => self.top_class.as_deref(),
            Cap::TopPred => self.top_pred.as_deref(),
            Cap::LabeledClass => self.labeled_class.as_deref(),
            Cap::LabelPred => self.label_pred.as_deref(),
            Cap::ObjectPred => self.object_pred.as_deref(),
            Cap::TimePred => self.time_pred.as_deref(),
            Cap::NumPred => self.num_pred.as_deref(),
            Cap::BaseIri => self.base_iri.as_deref(),
            Cap::WktPath => self.wkt_path.as_deref(),
            Cap::Bbox => self.bbox_polygon.as_deref(),
            Cap::AnnotationPred => self.annotation_pred.as_deref(),
            Cap::AnnotatedPred => self.annotated_pred.as_deref(),
            Cap::QuotingPred => self.quoting_pred.as_deref(),
            Cap::ExternalIri
            | Cap::GeoLatLong
            | Cap::NamedGraphs
            | Cap::Link
            | Cap::HasLiterals
            | Cap::AnnotatedStatements => None,
        }
    }

    /// Is a capability available (string caps must resolve; bool caps must hold)?
    fn available(&self, cap: Cap) -> bool {
        match cap {
            Cap::ExternalIri => self.external_iri,
            Cap::GeoLatLong => self.geo_latlong,
            Cap::NamedGraphs => self.named_graphs,
            Cap::Link => self.link,
            Cap::HasLiterals => self.has_literals,
            Cap::AnnotatedStatements => self.annotated_statements,
            other => self.value(other).is_some(),
        }
    }

    /// Substitute every placeholder we have a value for.
    fn substitute(&self, body: &str) -> String {
        let mut out = body.to_string();
        for &cap in ALL_CAPS {
            if let (Some(ph), Some(v)) = (cap.placeholder(), self.value(cap)) {
                out = out.replace(ph, v);
            }
        }
        out
    }
}

/// Audit one body against the co-occurrence rule (see the module docs).
///
/// Two things are checked, and both are properties of the **table**, not of any
/// dataset — so this runs over every template at test time and, in debug builds,
/// over every body the generator actually emits:
///
/// 1. Every `{{PLACEHOLDER}}` names a capability the template *requires*. A body
///    can therefore never be shipped with an unsubstituted hole, whatever the
///    card looks like.
/// 2. Unless the template declares itself `NonEmpty::Undecidable`, any two
///    distinct capabilities appearing in the same body are [jointly
///    derived](Cap::joint_with). This is the rule `lb-labels` broke.
fn check_body(id: &str, body: &str, requires: &[Cap], nonempty: NonEmpty) -> Result<(), String> {
    let used: Vec<Cap> = ALL_CAPS
        .iter()
        .copied()
        .filter(|c| c.placeholder().is_some_and(|ph| body.contains(ph)))
        .collect();
    // (1) Placeholders are accounted for, in both directions.
    for cap in &used {
        if !requires.contains(cap) {
            return Err(format!(
                "{id}: body uses {} but does not require {}",
                cap.placeholder().unwrap_or_default(),
                cap.key()
            ));
        }
    }
    for chunk in body.split("{{").skip(1) {
        let name = chunk.split("}}").next().unwrap_or(chunk);
        let ph = format!("{{{{{name}}}}}");
        if !ALL_CAPS.iter().any(|c| c.placeholder() == Some(&ph[..])) {
            return Err(format!("{id}: body has an unknown placeholder {ph}"));
        }
    }
    // (2) Whatever meets in the body must have been chosen together.
    if matches!(nonempty, NonEmpty::Undecidable(_)) {
        return Ok(());
    }
    for (i, a) in used.iter().enumerate() {
        for b in &used[i + 1..] {
            if !a.joint_with().contains(b) {
                return Err(format!(
                    "{id}: conjoins {} with {}, which are chosen independently — \
                     make one jointly derived (Cap::joint_with) or declare NonEmpty::Undecidable",
                    a.key(),
                    b.key()
                ));
            }
        }
    }
    Ok(())
}

/// A CRS84 lon/lat WKT polygon for the bounding box, or the whole world when the
/// dataset has geometry but no wgs84 extent was derived.
fn bbox_polygon(bbox: Option<[f64; 4]>) -> String {
    let [min_lon, min_lat, max_lon, max_lat] = bbox.unwrap_or([-180.0, -90.0, 180.0, 90.0]);
    format!(
        "POLYGON(({min_lon} {min_lat}, {max_lon} {min_lat}, {max_lon} {max_lat}, {min_lon} {max_lat}, {min_lon} {min_lat}))"
    )
}

/// The count the card records for a predicate, or — when the term fell off the
/// capped list — the most it could be: a list sorted by count that stops at the
/// cap bounds everything below it by its last entry. A complete list that does
/// not name the term proves it absent.
fn bounded_count(card: &DatasetCard, list: &[(String, u64)], term: &str) -> u64 {
    if let Some((_, n)) = list.iter().find(|(t, _)| t == term) {
        return *n;
    }
    if complete(card, list) {
        0
    } else {
        list.last().map_or(u64::MAX, |(_, n)| *n)
    }
}

/// Which form of a template's body was picked — the [`Scan::Everything`]
/// estimate depends on it (a `UNION`/`GRAPH` body reads the named graphs too).
#[derive(Clone, Copy, PartialEq, Eq)]
enum BodyScope {
    Default,
    AllQuads,
}

/// How many statements a body of this [`Scan`] reads, from the card's counts.
fn scan_estimate(scan: Scan, card: &DatasetCard, caps: &Caps, body: BodyScope) -> u64 {
    let pred = |iri: &str| bounded_count(card, &card.predicates, iri);
    let class = |iri: &str| bounded_count(card, &card.classes, iri);
    let named = card.quad_count.saturating_sub(card.triple_count);
    match scan {
        Scan::Bounded => 0,
        Scan::Everything => match body {
            BodyScope::Default => card.triple_count,
            BodyScope::AllQuads => card.quad_count,
        },
        Scan::Types => pred(RDF_TYPE),
        Scan::Pred(cap) => caps.value(cap).map_or(u64::MAX, pred),
        Scan::Preds(list) => list.iter().map(|p| pred(p)).fold(0u64, u64::saturating_add),
        Scan::Class(cap) => caps.value(cap).map_or(u64::MAX, class),
        Scan::ClassStar(cap) => {
            let Some(c) = caps.value(cap) else {
                return u64::MAX;
            };
            // Every statement a subject of the class makes, as the quotient
            // counts them. A class with no row of its own in a truncated
            // quotient is charged the whole graph — the estimate errs high.
            let rows: u64 = card
                .class_links
                .iter()
                .filter(|l| l.s_class == c)
                .map(|l| l.count)
                .sum();
            if rows == 0 && !complete(card, &card.class_links) {
                return card.triple_count;
            }
            class(c).saturating_add(rows)
        }
        Scan::NamedGraphs => named,
        Scan::Annotations => card
            .signals
            .annotation_predicates
            .iter()
            .map(|p| pred(p))
            .fold(0u64, u64::saturating_add),
    }
}

/// Generate the tiered starter-query library for a card: emit each template whose
/// required capabilities are all present, with the body picked for where the data
/// lives (`GraphScope`), placeholders substituted, and the shared PREFIX block
/// prepended. A body whose `Scan` is over [`STARTER_SCAN_BUDGET`] statements is
/// replaced by its bounded form, or dropped when it has none.
pub fn generate(card: &DatasetCard) -> Vec<ExampleQuery> {
    generate_with_budget(card, STARTER_SCAN_BUDGET)
}

/// [`generate`] under an explicit scan budget — the tests' way to exercise the
/// bounded forms on a fixture small enough to build in a unit test.
fn generate_with_budget(card: &DatasetCard, budget: u64) -> Vec<ExampleQuery> {
    let caps = Caps::from_card(card);
    let scope = GraphScope::of(card);
    let mut out = Vec::new();
    for t in TEMPLATES {
        // 1. Capability gate — the full template, or its reduced fallback. A
        //    fallback carries no scope variants, so it is default-graph shaped.
        let all = |rs: &[Cap]| rs.iter().all(|&c| caps.available(c));
        let (base, named, mixed, requires, nonempty) = if all(t.requires) {
            (t.body, t.named_body, t.mixed_body, t.requires, t.nonempty)
        } else if let Some(f) = t.fallback.as_ref().filter(|f| all(f.requires)) {
            (f.body, None, None, f.requires, f.nonempty)
        } else {
            continue;
        };

        // 2. Pick the body for where the data lives. A scope-variant body is
        //    always Index-tier: GRAPH/UNION patterns are not summary-shaped
        //    (`summary_query_shape` recognizes only a bare default-graph
        //    pattern), and the pyramid summary covers the default graph only.
        let (mut body, mut tier, reads) = match scope {
            GraphScope::DefaultOnly => (base, t.tier, BodyScope::Default),
            GraphScope::NamedOnly => match named {
                Some(b) => (b, Tier::Index, BodyScope::AllQuads),
                // GRAPH-native templates (the ng-* family) already address the
                // named graphs; any other default-graph body would be a
                // guaranteed-zero-rows query on a file whose default graph the
                // card itself records as empty — skip it.
                None if requires.contains(&Cap::NamedGraphs) => (base, t.tier, BodyScope::AllQuads),
                None => continue,
            },
            GraphScope::Mixed => match mixed {
                Some(b) => (b, Tier::Index, BodyScope::AllQuads),
                // The default-graph body is sound here — the profile that
                // instantiated it was derived from the (non-empty) default
                // graph — and the ng-* family surfaces the named half.
                None => (base, t.tier, BodyScope::Default),
            },
        };

        // 2b. The cost gate: a body that would read more than the budget is
        //     replaced by its bounded form, or not shipped. See the module docs.
        let (mut title, mut question, mut requires, mut nonempty) =
            (t.title, t.question, requires, nonempty);
        if scan_estimate(t.scan, card, &caps, reads) > budget {
            let Some(b) = t.bounded.as_ref().filter(|b| all(b.requires)) else {
                continue;
            };
            body = match scope {
                GraphScope::NamedOnly => match b.named_body {
                    Some(nb) => nb,
                    None => continue,
                },
                _ => b.body,
            };
            tier = Tier::Index;
            (title, question, requires, nonempty) = (b.title, b.question, b.requires, b.nonempty);
        }

        // 3. The last gate: refuse a query the card can PROVE would answer
        //    nothing. Only in default-graph scope — the card's counts are over
        //    the default graph, so they witness nothing about a GRAPH-scoped
        //    body (and a `GRAPH`-native template is never asking about the
        //    default graph in the first place).
        if scope == GraphScope::DefaultOnly && t.provably_empty.is_some_and(|f| f(card)) {
            continue;
        }

        debug_assert!(
            check_body(t.id, body, requires, nonempty).is_ok(),
            "{}",
            check_body(t.id, body, requires, nonempty).unwrap_err()
        );
        let body = caps.substitute(body);
        debug_assert!(
            !body.contains("{{"),
            "template {} left an unsubstituted placeholder",
            t.id
        );
        out.push(ExampleQuery {
            id: t.id.to_string(),
            title: title.to_string(),
            dimension: t.dimension.to_string(),
            question: question.to_string(),
            sparql: format!("{PREFIXES}\n{body}"),
            tier,
            requires: requires.iter().map(|c| c.key().to_string()).collect(),
        });
    }
    out
}

// ===========================================================================
// Auditing a card that is ALREADY published
// ===========================================================================
//
// [`generate`] decides what a card *should* ship. The audit answers the other
// half of the same question — what does a card that is already on the wire
// ship, and can it answer? — for a file whose queries were written by an older
// revision of the table above.
//
// It is deliberately in this module and not beside it: the one judgement it
// makes ("does the card prove these two pieces meet?") is
// `class_carries`, the same function `Caps::from_card` resolves
// `Cap::LabeledClass` with, and the emptiness gates it applies are the
// templates' own `Template::provably_empty` hooks and `NonEmpty` claims. A
// second, drifting copy of "is this empty" living in a script is how the
// original defect survived four releases.

/// What a published starter query is worth on the file that carries it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum Verdict {
    /// The card **proves** at least one row comes back.
    Answers,
    /// The card **proves** none does. Airtight for the shapes that turn on a
    /// term's existence (a path step missing from a complete predicate list, a
    /// `VALUES` list disjoint from the link predicates, a default-graph body on
    /// an empty default graph); for the class-∧-predicate shape it rests on the
    /// quotient, whose one blind spot `Refuted` documents and narrows.
    Empty,
    /// A row comes back (an un-grouped aggregate always returns one) but it is
    /// vacuous — the thing being counted is provably zero.
    Vacuous,
    /// The card cannot prove the join is non-empty, and bounds how much could
    /// survive it. Not the same as `Empty`: reported separately, never merged.
    Suspect,
    /// Honestly undecidable from a card — the template says so, or the query
    /// conjoins terms nothing in the card can relate.
    Undecidable,
    /// The body matches no known revision of its template, so nothing is
    /// claimed about it.
    Unrecognized,
    /// The query does not parse. Only a curated `example_queries` entry can be
    /// this — the generator's bodies are parsed by the test suite — and it is
    /// the one verdict that needs no run to be certain of.
    Invalid,
}

impl Verdict {
    pub fn as_str(self) -> &'static str {
        match self {
            Verdict::Answers => "answers",
            Verdict::Empty => "empty",
            Verdict::Vacuous => "vacuous",
            Verdict::Suspect => "suspect",
            Verdict::Undecidable => "undecidable",
            Verdict::Unrecognized => "unrecognized",
            Verdict::Invalid => "invalid",
        }
    }
}

/// The id `rete card-audit` gives the curated `example_queries` entry at
/// `index` (0-based): `example-1`, `example-2`, … — curated queries carry no id
/// of their own, and a stable positional one is what `--only` can name.
pub fn example_query_id(index: usize) -> String {
    format!("example-{}", index + 1)
}

/// One published query's verdict, with the evidence behind it.
#[derive(Debug, Clone, Serialize)]
pub struct Finding {
    pub id: String,
    pub verdict: Verdict,
    /// The evidence, in the words a maintainer needs to act on it.
    pub why: String,
    /// What a re-card would do to this query: `current` (byte-identical to what
    /// this generator writes for this very card — nothing to fix),
    /// `superseded` (the generator writes a different body now), or `dropped`
    /// (it would no longer be emitted at all).
    pub revision: &'static str,
    /// The terms substituted into the body, each tagged with the card ranking
    /// it was drawn from. Two terms from **different** rankings conjoined in
    /// one body is the #172 shape — recorded for every query, so the census is
    /// empirical rather than a re-reading of the table.
    pub substitutions: Vec<Substitution>,
    /// True when the body conjoins two or more independently-ranked terms.
    pub conjoined: bool,
    /// What running the query actually did — absent unless `--measure` ran it.
    /// Kept **beside** `verdict`, never merged into it: one is what a card can
    /// prove about a file, the other is what the file did. Where they disagree
    /// the observation wins, and the disagreement is the finding.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub observed: Option<Observation>,
}

/// One starter query, actually run.
#[derive(Debug, Clone, Serialize)]
pub struct Observation {
    /// `answers` (rows with bindings), `vacuous` (rows that bind nothing),
    /// `empty` (no rows at all), or `error` (the run did not finish).
    pub outcome: &'static str,
    pub rows: u64,
    /// Bytes the run read, cold, open included.
    pub bytes: u64,
    /// Range requests the run made, cold, open included.
    pub requests: u64,
    /// Wall clock on the measuring machine — a reference, not a property of the
    /// file. Read it next to `bytes`/`requests`, never on its own.
    pub debug_ms: u64,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
    /// What the file's own build record says this query cost — present only
    /// when the file carries one. That is the single case where a
    /// re-measurement has a **known answer to check itself against**, so it is
    /// checked, and the answer is reported rather than assumed.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub recorded: Option<Recorded>,
}

/// The figures a build wrote into the file, beside the ones just measured.
#[derive(Debug, Clone, Serialize)]
pub struct Recorded {
    pub bytes: u64,
    pub requests: u64,
    pub rows: u64,
    /// All three agree with the run. `bytes` and `requests` are properties of
    /// layout + query, so they should — through the same transport. A
    /// disagreement is worth knowing about: a different reader fan-out, a
    /// different engine, or a file that is not the one the record describes.
    pub agrees: bool,
}

impl Observation {
    /// Does the observation contradict what the card alone concluded? Only
    /// `Answers` and `Empty` are claims strong enough to be wrong; `Suspect`
    /// and `Undecidable` say in so many words that they are not claims.
    pub fn contradicts(&self, verdict: Verdict) -> bool {
        match verdict {
            Verdict::Answers => self.outcome != "answers",
            Verdict::Empty => self.outcome == "answers",
            Verdict::Vacuous => self.outcome == "answers",
            _ => false,
        }
    }
}

/// A substituted term and where in the card profile it came from.
#[derive(Debug, Clone, Serialize)]
pub struct Substitution {
    pub placeholder: String,
    pub value: String,
    /// e.g. `classes[0]`, `predicates[3]`, `signals.label_predicate`. Empty
    /// when the term is in no ranking the card records (a hard-coded IRI, or a
    /// value that fell off a capped list).
    pub origin: Vec<String>,
}

/// Bodies that **earlier revisions** of a template shipped. A published file is
/// not re-cardable for free, so the audit has to read the query text that is
/// actually out there; only the revisions the current bodies no longer match
/// need an entry. Every one is a body `check_body` would reject today — that
/// is why it has an entry.
struct Legacy {
    id: &'static str,
    body: &'static str,
}

const LEGACY_BODIES: &[Legacy] = &[
    // pre-#172 `top-reach`: the busiest subject and the most frequent
    // predicate, chosen from two independent rankings and then conjoined.
    Legacy {
        id: "top-reach",
        body: "SELECT ?y WHERE { {{HUB_IRI}} {{TOP_PRED}}+ ?y } LIMIT 100",
    },
    // pre-#172 `lk-sameas`: the VALUES list covered three of the four
    // predicates the `signals.link_predicates` gate is detected from.
    Legacy {
        id: "lk-sameas",
        body: "SELECT ?p (COUNT(*) AS ?n) WHERE { ?s ?p ?o VALUES ?p { owl:sameAs skos:exactMatch rdfs:seeAlso } } GROUP BY ?p",
    },
    // pre-0.4 `top-dangling`: the same rows as today's body, but `FILTER NOT
    // EXISTS` materializes its inner pattern — 8.7 GiB on the OpenCitations
    // sample. Recognized so a published card audits as `superseded`, not as an
    // unreadable body.
    Legacy {
        id: "top-dangling",
        body: "SELECT ?o WHERE { ?s ?p ?o FILTER(isIRI(?o)) FILTER NOT EXISTS { ?o ?p2 ?o2 } } LIMIT 100",
    },
];

/// The effective top-N cap a card's profile lists were derived under. Cards
/// built before the field existed omit it; they were built by this same builder
/// family, whose cap is a compile-time constant.
fn cap_of(card: &DatasetCard) -> usize {
    if card.top_n > 0 {
        card.top_n as usize
    } else {
        CARD_TOP_N
    }
}

/// Is a capped profile list **complete** — did nothing fall off the end? A list
/// shorter than the cap was never truncated, so absence from it is evidence of
/// absence. A list *at* the cap proves nothing either way.
fn complete<T>(card: &DatasetCard, list: &[T]) -> bool {
    list.len() < cap_of(card)
}

/// How far the card can go towards proving that no instance of `class` carries
/// `pred` — the negative of `class_carries`, which a card can rarely settle
/// outright.
/// The refutation is exact **for singly-typed data only**, and that is the
/// audit's one standing caveat: the quotient gives every subject exactly one
/// class (the last `rdf:type` wins), so a subject typed both `class` and
/// `other` is counted under `other` alone. `?s a class ; pred ?o` then matches a
/// graph whose quotient shows no such row — `vidy` types all 39,723 of its units
/// both `schema:ArchiveComponent` and `vidy:Unit`, the quotient files every one
/// of them under `vidy:Unit`, and the label query the card ships returns 50 rows
/// regardless.
///
/// A card cannot record multi-typing, but it does leave two tells, and
/// [`refute_class_pred`] refuses to claim a refutation when either shows:
///
///  1. **The class is absent from the quotient.** A class with instances but no
///     `class_links` row of its own is a class the quotient is not describing —
///     shadowed, or making no statements at all — so its silence about one
///     predicate means nothing.
///  2. **Another class has exactly the same instance count.** Two classes over
///     the same population is what dual typing looks like from the card (a
///     schema.org type beside a native one — `vidy` and `arxiu` both), and the
///     labelled half may be filed under the twin.
///
/// Neither is a proof of single-typing; together they are what the card can see.
/// Running the query is what closes it.
enum Refuted {
    /// Every use of `pred` is accounted for in the `class_links` quotient, none
    /// of them falls on `class`, and neither multi-typing tell shows.
    Proved,
    /// The quotient is truncated: at most `budget` uses of `pred` are
    /// unaccounted for, so at most that many of the class's `instances` could
    /// be joined. Suspicion, not proof.
    AtMost { budget: u64, instances: u64 },
    /// The quotient accounts for every use of `pred` and none falls on `class`,
    /// but a multi-typing tell shows, so that silence proves nothing.
    Shadowed { described: bool, twin: bool },
    /// `pred` is not in the (capped) predicate list, so there is no total to
    /// account against.
    Unknown,
}

fn refute_class_pred(card: &DatasetCard, class: &str, pred: &str) -> Refuted {
    let instances = card
        .classes
        .iter()
        .find(|(c, _)| c == class)
        .map(|(_, n)| *n)
        .unwrap_or(0);
    // Every non-`rdf:type` statement contributes exactly one `class_links` row,
    // so the rows for a predicate sum to its total use **iff** none was
    // truncated away — the completeness test that makes absence conclusive.
    let accounted: u64 = card
        .class_links
        .iter()
        .filter(|l| l.predicate == pred)
        .map(|l| l.count)
        .sum();
    let Some((_, total)) = card.predicates.iter().find(|(p, _)| p == pred) else {
        return Refuted::Unknown;
    };
    let accounted_for_all = accounted >= *total || complete(card, &card.class_links);
    if !accounted_for_all {
        return Refuted::AtMost {
            budget: total - accounted,
            instances,
        };
    }
    // The two multi-typing tells (see `Refuted`). Either one and the quotient's
    // silence about this class stops being evidence.
    let described = card.class_links.iter().any(|l| l.s_class == class);
    let twin = card
        .classes
        .iter()
        .any(|(c, n)| c != class && *n == instances);
    if described && !twin {
        Refuted::Proved
    } else {
        Refuted::Shadowed { described, twin }
    }
}

/// Which card rankings a substituted term appears in. Read off the card rather
/// than declared by the template, so it also describes a body this table no
/// longer contains.
fn origins(card: &DatasetCard, v: &str) -> Vec<String> {
    let mut o = Vec::new();
    if let Some(i) = card.classes.iter().position(|(c, _)| c == v) {
        o.push(format!("classes[{i}]"));
    }
    if let Some(i) = card.predicates.iter().position(|(p, _)| p == v) {
        o.push(format!("predicates[{i}]"));
    }
    if let Some(i) = card.top_hubs.iter().position(|(h, _)| h == v) {
        o.push(format!("top_hubs[{i}]"));
    }
    let s = &card.signals;
    if s.label_predicate.as_deref() == Some(v) {
        o.push("signals.label_predicate".to_string());
    }
    if let Some(i) = s.time_predicates.iter().position(|p| p == v) {
        o.push(format!("signals.time_predicates[{i}]"));
    }
    if let Some(i) = s.numeric_predicates.iter().position(|p| p == v) {
        o.push(format!("signals.numeric_predicates[{i}]"));
    }
    if s.base_iri.as_deref() == Some(v) {
        o.push("signals.base_iri".to_string());
    }
    if let Some(i) = s.annotation_predicates.iter().position(|p| p == v) {
        o.push(format!("signals.annotation_predicates[{i}]"));
    }
    if let Some(i) = s.quoting_predicates.iter().position(|p| p == v) {
        o.push(format!("signals.quoting_predicates[{i}]"));
    }
    if let Some((quoted, about)) = annotated_statement(card) {
        if v == quoted {
            o.push("signals.annotated_statement.0".to_string());
        }
        if v == about {
            o.push("signals.annotated_statement.1".to_string());
        }
    }
    o
}

/// The bindings a published body gave a pattern's placeholders.
type Binds = Vec<(String, String)>;

/// The **distinct** placeholders a body substitutes with a term the card
/// ranks. Distinct by name on purpose: the current `top-reach` writes
/// `{{OBJECT_PRED}}` twice — once to pick the seed, once to walk from it — and
/// a term conjoined with itself is the opposite of the two-maxima shape, it is
/// how the template guarantees the seed has an edge.
fn distinct_ranked<'a>(card: &DatasetCard, binds: &'a Binds) -> Vec<&'a str> {
    let mut names: Vec<&str> = binds
        .iter()
        .filter(|(_, v)| !origins(card, v).is_empty())
        .map(|(n, _)| n.as_str())
        .collect();
    names.sort_unstable();
    names.dedup();
    names
}

fn bound<'a>(binds: &'a Binds, name: &str) -> Option<&'a str> {
    binds
        .iter()
        .find(|(n, _)| n == name)
        .map(|(_, v)| v.as_str())
}

/// Match a published body against a template pattern, recovering the value each
/// `{{PLACEHOLDER}}` took. Every literal segment must appear, in order, and the
/// body must end exactly where the pattern does — a match is exact, so a
/// mismatched revision is reported as such instead of being misread.
fn match_pattern(pattern: &str, body: &str) -> Option<Binds> {
    let mut binds: Binds = Vec::new();
    let mut pat = pattern;
    let mut rest = body;
    loop {
        let Some(i) = pat.find("{{") else {
            return (pat == rest).then_some(binds);
        };
        let (lit, tail) = pat.split_at(i);
        rest = rest.strip_prefix(lit)?;
        let end = tail.find("}}")?;
        let name = &tail[2..end];
        pat = &tail[end + 2..];
        // The value runs up to the pattern's next literal segment.
        let next_lit = &pat[..pat.find("{{").unwrap_or(pat.len())];
        let cut = if next_lit.is_empty() {
            rest.len()
        } else {
            rest.find(next_lit)?
        };
        if cut == 0 {
            return None; // an empty substitution is not a substitution
        }
        binds.push((name.to_string(), rest[..cut].to_string()));
        rest = &rest[cut..];
    }
}

/// The `?s a {{CLASS}} … {{PRED}}` shape — a class and a predicate conjoined on
/// **one** subject. Recognized from the pattern text, not from the template id,
/// so a future template that writes the same shape is audited too.
fn class_pred_conjunction(pattern: &str) -> Option<(&str, &str)> {
    let after = pattern.split("?s a {{").nth(1)?;
    let class = after.split("}}").next()?;
    let tail = after.split_once("}}")?.1;
    for sep in ["; {{", "?s {{"] {
        if let Some(x) = tail.split(sep).nth(1) {
            return Some((class, x.split("}}").next()?));
        }
    }
    None
}

/// The `VALUES ?p { … }` list a body pins itself to, as bracketed IRIs. The
/// gate that admits the query counts predicates; the body only matches the ones
/// it names, and the two can disagree.
fn values_predicates(body: &str) -> Option<Vec<String>> {
    let inner = body.split("VALUES ?p {").nth(1)?.split('}').next()?;
    Some(
        inner
            .split_whitespace()
            .filter_map(|t| {
                let (p, local) = t.split_once(':')?;
                let ns = match p {
                    "owl" => "http://www.w3.org/2002/07/owl#",
                    "skos" => "http://www.w3.org/2004/02/skos/core#",
                    "rdfs" => "http://www.w3.org/2000/01/rdf-schema#",
                    _ => return None,
                };
                Some(format!("<{ns}{local}>"))
            })
            .collect(),
    )
}

/// The predicate IRIs a property path **must** traverse — the steps that are
/// not optional. `geo:hasGeometry?/geo:asWKT` requires only the second; the
/// fixed `geo:hasGeometry/geo:asWKT` the pre-#172 template wrote requires both,
/// which is why it could not match a file that has no `geo:hasGeometry`.
fn required_path_steps(path: &str) -> Vec<String> {
    path.split('/')
        .filter(|step| !step.ends_with('?') && !step.ends_with('*'))
        .filter_map(|step| match step.trim_end_matches('+') {
            "geo:asWKT" => Some(GEO_ASWKT.to_string()),
            "geo:hasGeometry" => Some(GEO_HASGEOMETRY.to_string()),
            _ => None,
        })
        .collect()
}

/// Audit every starter query a card already ships.
///
/// Two things happen per query, and they answer different questions. [`generate`]
/// is re-run over the same profile — what a re-card would ship — which says
/// whether the query is *stale*. The verdict says whether it *answers*, which is
/// the thing a reader of the published file experiences today.
pub fn audit(card: &DatasetCard) -> Vec<Finding> {
    let caps = Caps::from_card(card);
    let scope = GraphScope::of(card);
    let fresh = generate(card);
    card.queries
        .iter()
        .map(|q| {
            let revision = match fresh.iter().find(|r| r.id == q.id) {
                Some(r) if r.sparql == q.sparql => "current",
                Some(_) => "superseded",
                None => "dropped",
            };
            finding(card, &caps, scope, q, revision)
        })
        .collect()
}

/// Audit the **curated** `example_queries` a card carries — the half of a card a
/// publisher wrote, which [`audit`] (the generated half) never looks at.
///
/// A curated query makes no claim, so there is no template to hold it to; what
/// the card *can* still decide is narrower and stated as such:
///
/// * it does not parse — [`Verdict::Invalid`], certain;
/// * it reads only the default graph of a file whose default graph the card
///   records as empty — [`Verdict::Empty`], the same scope rule the starters
///   obey (#170);
/// * it names a predicate the card's **complete** predicate list does not
///   contain — [`Verdict::Suspect`], not `Empty`: the predicate may sit in an
///   `OPTIONAL`, `UNION` or `MINUS` branch, and the profile covers the default
///   graph only;
/// * anything else — [`Verdict::Undecidable`]; `card-audit --measure` runs it.
///
/// Findings use the ids of [`example_query_id`] and `revision: "curated"`, and
/// are reported apart from the generated queries' — they answer to a
/// different author.
pub fn audit_examples(card: &DatasetCard) -> Vec<Finding> {
    card.example_queries
        .iter()
        .enumerate()
        .map(|(i, sparql)| curated_finding(card, example_query_id(i), sparql))
        .collect()
}

fn curated_finding(card: &DatasetCard, id: String, sparql: &str) -> Finding {
    let mk = |verdict, why: String| Finding {
        id: id.clone(),
        verdict,
        why,
        revision: "curated",
        substitutions: Vec::new(),
        conjoined: false,
        observed: None,
    };
    let predicates = match crate::query_predicates(sparql) {
        Ok(p) => p,
        Err(e) => return mk(Verdict::Invalid, format!("does not parse: {e}")),
    };
    // Keyword tests on the text, as the starter audit's scope rule does: a
    // `GRAPH` or a dataset clause anywhere means the query does not read only
    // the default graph.
    let upper = strip_prefixes(sparql).to_ascii_uppercase();
    let scoped = upper.contains("GRAPH") || upper.contains("FROM");
    if !scoped && card.triple_count == 0 && card.named_graph_count > 0 {
        return mk(
            Verdict::Empty,
            format!(
                "it reads only the default graph, which the card records as empty \
                 ({} named graph(s) hold all {} statements)",
                card.named_graph_count, card.quad_count
            ),
        );
    }
    let missing: Vec<&String> = predicates
        .iter()
        .filter(|p| !card.predicates.iter().any(|(q, _)| q == *p))
        .collect();
    if !missing.is_empty() && !card.predicates.is_empty() {
        let names = missing
            .iter()
            .map(|s| s.as_str())
            .collect::<Vec<_>>()
            .join(" ");
        return if complete(card, &card.predicates) && card.named_graph_count == 0 {
            mk(
                Verdict::Suspect,
                format!(
                    "names {names}, which the card's complete predicate list does not contain \
                     — no row can match unless it sits in an OPTIONAL/UNION/MINUS branch"
                ),
            )
        } else {
            mk(
                Verdict::Undecidable,
                format!(
                    "names {names}, which the card's predicate list does not show — the list is \
                     capped, or the predicate may live in a named graph the profile does not cover"
                ),
            )
        };
    }
    mk(
        Verdict::Undecidable,
        "a curated query makes no claim the card can check; `card-audit --measure` runs it"
            .to_string(),
    )
}

fn finding(
    card: &DatasetCard,
    caps: &Caps,
    scope: GraphScope,
    q: &ExampleQuery,
    revision: &'static str,
) -> Finding {
    let body = strip_prefixes(&q.sparql);
    let body = body.trim();

    let mk = |verdict, why: String, revision, binds: &Binds| {
        let substitutions: Vec<Substitution> = binds
            .iter()
            .map(|(n, v)| Substitution {
                placeholder: n.clone(),
                value: v.clone(),
                origin: origins(card, v),
            })
            .collect();
        Finding {
            id: q.id.clone(),
            verdict,
            why,
            revision,
            conjoined: distinct_ranked(card, binds).len() > 1,
            substitutions,
            observed: None,
        }
    };

    let Some(t) = TEMPLATES.iter().find(|t| t.id == q.id) else {
        return mk(
            Verdict::Unrecognized,
            "no template of this id is in the library any more".to_string(),
            "retired",
            &Vec::new(),
        );
    };

    // Recover the substituted terms: match the body against the template's own
    // patterns (every scope variant, the fallback and the bounded form), then
    // against the bodies earlier revisions wrote. See `variant_of`.
    let Some(Variant {
        pattern,
        binds,
        nonempty,
        bounded,
    }) = variant_of(t, body)
    else {
        return mk(
            Verdict::Unrecognized,
            "the body matches no known revision of this template".to_string(),
            "unknown",
            &Vec::new(),
        );
    };

    // --- 1. Scope. A default-graph body on a file whose default graph the card
    //        itself records as empty cannot return a row (issue #170).
    if !body.contains("GRAPH") && card.triple_count == 0 && card.named_graph_count > 0 {
        return mk(
            Verdict::Empty,
            format!(
                "the body scans the default graph, which the card records as empty \
                 ({} named graph(s) hold all {} statements)",
                card.named_graph_count, card.quad_count
            ),
            revision,
            &binds,
        );
    }

    // --- 2. The template's own last gate, unchanged — and, where the table says
    //        the hook is an equivalence, its other direction.
    if scope == GraphScope::DefaultOnly {
        if let Some(hook) = t.provably_empty {
            if hook(card) {
                return mk(
                    Verdict::Empty,
                    "the card's own precompute for this query is empty (the generator \
                     refuses to emit it today)"
                        .to_string(),
                    revision,
                    &binds,
                );
            }
            if t.hook_is_exact && !bounded {
                return mk(
                    Verdict::Answers,
                    "the card precomputes this query's own result, and it is not empty".to_string(),
                    revision,
                    &binds,
                );
            }
        }
    }

    // --- 3. The co-occurrence rule, applied to the body that shipped.
    if let Some((cn, pn)) = class_pred_conjunction(pattern) {
        if let (Some(class), Some(pred)) = (bound(&binds, cn), bound(&binds, pn)) {
            let aggregate = matches!(nonempty, NonEmpty::Aggregate);
            if class_carries(card, class, pred) {
                return mk(
                    Verdict::Answers,
                    format!("class_links witnesses {class} carrying {pred}"),
                    revision,
                    &binds,
                );
            }
            return match refute_class_pred(card, class, pred) {
                Refuted::Proved => mk(
                    if aggregate {
                        Verdict::Vacuous
                    } else {
                        Verdict::Empty
                    },
                    format!(
                        "the class_links quotient accounts for every use of {pred} and \
                         none falls on {class}{}",
                        if aggregate {
                            " — the aggregate returns one row whose count is 0"
                        } else {
                            ""
                        }
                    ),
                    revision,
                    &binds,
                ),
                Refuted::AtMost { budget, instances } => mk(
                    Verdict::Suspect,
                    format!(
                        "no class_links row witnesses {class} carrying {pred}; the quotient \
                         is truncated, so at most {budget} of the class's {instances} \
                         instances could be joined"
                    ),
                    revision,
                    &binds,
                ),
                Refuted::Shadowed { described, twin } => mk(
                    Verdict::Suspect,
                    format!(
                        "the quotient accounts for every use of {pred} and none falls on \
                         {class}, but {} — the quotient files a multi-typed subject under \
                         one class only, so its silence is not evidence",
                        match (described, twin) {
                            (false, true) =>
                                "the class has no class_links row of its own AND another class \
                                 has exactly its instance count",
                            (false, false) => "the class has no class_links row of its own",
                            _ => "another class has exactly its instance count",
                        }
                    ),
                    revision,
                    &binds,
                ),
                Refuted::Unknown => mk(
                    Verdict::Undecidable,
                    format!("{pred} is not in the card's (capped) predicate list"),
                    revision,
                    &binds,
                ),
            };
        }
    }

    // --- 4. A property path can only match if the steps it insists on exist.
    if let Some(path) = bound(&binds, "WKT_PATH") {
        let missing: Vec<String> = required_path_steps(path)
            .into_iter()
            .filter(|iri| !card.predicates.iter().any(|(p, _)| p == iri))
            .collect();
        if !missing.is_empty() && complete(card, &card.predicates) {
            return mk(
                Verdict::Empty,
                format!(
                    "the path {path} requires {} , which the card's complete predicate \
                     list does not contain",
                    missing.join(", ")
                ),
                revision,
                &binds,
            );
        }
    }

    // --- 5. A pinned VALUES list must cover the gate that admitted the query.
    if let Some(listed) = values_predicates(body) {
        let present: Vec<&String> = card
            .signals
            .link_predicates
            .iter()
            .filter(|p| listed.contains(p))
            .collect();
        if present.is_empty() {
            return mk(
                Verdict::Empty,
                format!(
                    "the body pins VALUES ?p to {} , none of which this dataset uses \
                     (it links with {})",
                    listed.join(" "),
                    card.signals.link_predicates.join(" ")
                ),
                revision,
                &binds,
            );
        }
    }

    // --- 6. "Which predicates point OUT?" needs something outside the base IRI.
    if q.id == "lk-external" && !caps.external_iri {
        let why = "no IRI the card records lies outside the dataset's base IRI".to_string();
        return if complete(card, &card.in_hubs) && complete(card, &card.classes) {
            mk(
                Verdict::Empty,
                format!("{why}, and both lists are complete — the FILTER keeps nothing"),
                revision,
                &binds,
            )
        } else {
            mk(
                Verdict::Suspect,
                format!("{why}, but the lists are truncated so one could have fallen off"),
                revision,
                &binds,
            )
        };
    }

    // --- 6b. The RDF-star conjunction. `ANNOTATED_PRED` (inside the quoted
    //         triple) and `ANNOTATION_PRED` (outside it) are the second pair
    //         the card can witness, so step 7 below — which would see two
    //         ranked predicates and decline — must not reach them. What the
    //         published body actually bound is compared against the card's own
    //         witness: a re-derivation can move the pair, and a body carrying
    //         the old one is no longer proven.
    if let (Some(quoted), Some(about)) = (
        bound(&binds, "ANNOTATED_PRED"),
        bound(&binds, "ANNOTATION_PRED"),
    ) {
        return match annotated_statement(card) {
            Some((q, a)) if q == quoted && a == about => mk(
                Verdict::Answers,
                format!(
                    "signals.annotated_statement witnesses a {quoted} statement this graph \
                     both asserts and annotates with {about}"
                ),
                revision,
                &binds,
            ),
            Some((q, a)) => mk(
                Verdict::Suspect,
                format!(
                    "the body pins {quoted} / {about}, but the card's witnessed pair is \
                     {q} / {a} — nothing here proves these two meet on one statement"
                ),
                revision,
                &binds,
            ),
            None => mk(
                Verdict::Undecidable,
                "the card records no annotated-statement witness, so it cannot say whether \
                 the quoted predicate and the annotating one ever meet"
                    .to_string(),
                revision,
                &binds,
            ),
        };
    }

    // --- 7. Two independently-ranked terms conjoined, with nothing in the card
    //        able to relate them: the shape, without a decision.
    let ranked = distinct_ranked(card, &binds);
    if ranked.len() > 1 {
        return mk(
            Verdict::Undecidable,
            format!(
                "conjoins {} , drawn from different rankings — the card relates no \
                 specific subject to a specific predicate",
                ranked.join(" and ")
            ),
            revision,
            &binds,
        );
    }

    // --- 8. An un-grouped aggregate that joins two predicates on one subject
    //        always returns its row; whether the row says anything is another
    //        matter, and one no card can settle (`class_links` collapses every
    //        untyped subject into one bucket, so rows for the two predicates
    //        under it are not evidence that any single subject carries both).
    if matches!(nonempty, NonEmpty::Aggregate) && body.contains(" ; ") && !body.contains("GROUP BY")
    {
        return mk(
            Verdict::Undecidable,
            "an un-grouped aggregate always returns one row, but its body conjoins two \
             predicates the card only counted separately — the row may be vacuous"
                .to_string(),
            revision,
            &binds,
        );
    }

    // --- 9. Nothing above bit: the template's own claim stands.
    match nonempty {
        NonEmpty::Undecidable(reason) => {
            mk(Verdict::Undecidable, reason.to_string(), revision, &binds)
        }
        NonEmpty::AnyGraph | NonEmpty::Aggregate | NonEmpty::Witnessed => mk(
            Verdict::Answers,
            match nonempty {
                NonEmpty::AnyGraph => "any non-empty graph answers this",
                NonEmpty::Aggregate => "an un-grouped aggregate always returns one row",
                _ => "every substituted term came from a count the card records as > 0",
            }
            .to_string(),
            revision,
            &binds,
        ),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::card_derive::{derive_card, CardInput};
    use crate::{eval_query, ingest, summary_query_shape, QueryOutput, Rete};

    const TYPE: &str = "<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>";

    fn q(s: &str, p: &str, o: &str) -> (String, String, String, Option<String>) {
        (s.into(), p.into(), o.into(), None)
    }

    /// Ids whose template admits it cannot prove non-emptiness. The allow-list
    /// is **read off the table** rather than written out here, so a template
    /// cannot quietly join it: adding `NonEmpty::Undecidable` to one means
    /// writing down the reason, in the source, next to the body.
    fn may_be_empty(id: &str) -> bool {
        claim_of(id) == Claim::Undecidable
    }

    /// The property that would have caught the named-graph-only card bug — and
    /// the `lb-labels` one: every query the card ships **returns a non-empty
    /// result** when run against the very graph it was generated for.
    ///
    /// The only exemptions are the templates that declare themselves
    /// undecidable; everything else answering nothing is a generator bug, not a
    /// fact about the dataset.
    fn assert_every_query_returns_rows(card: &DatasetCard, rete: &Rete) {
        assert!(!card.queries.is_empty(), "card generated no queries at all");
        for eq in &card.queries {
            let allow_empty = may_be_empty(&eq.id);
            match eval_query(rete, &eq.sparql) {
                Ok(QueryOutput::Select(_, rows)) => assert!(
                    allow_empty || !rows.is_empty(),
                    "{}: returned zero rows:\n{}",
                    eq.id,
                    eq.sparql
                ),
                Ok(QueryOutput::Ask(b)) => assert!(allow_empty || b, "{}: ASK false", eq.id),
                Ok(QueryOutput::Construct(ts)) => {
                    assert!(
                        allow_empty || !ts.is_empty(),
                        "{}: constructed nothing",
                        eq.id
                    )
                }
                // No catch-all arm: `QueryOutput`'s `#[non_exhaustive]` does not
                // apply inside its own crate, so the three arms above are
                // exhaustive here — and a fourth result form should red this
                // test until someone decides what the query library does with it.
                Err(e) => panic!("{}: failed to run: {e:?}", eq.id),
            }
        }
    }

    /// Build the fixture and return `(card, image)` — the pair every
    /// returns-rows test needs.
    fn card_and_graph(
        quads: Vec<(String, String, String, Option<String>)>,
        term_count: u64,
        named_graphs: u64,
    ) -> (DatasetCard, Rete) {
        let card = derive_card(&quads, term_count, named_graphs, CardInput::default());
        let (bytes, _) =
            ingest::assemble_dataset_with_opts(quads, true, false, None, |_, _| Vec::new());
        (card, Rete::open(&bytes).unwrap())
    }

    fn sparql_of<'a>(card: &'a DatasetCard, id: &str) -> Option<&'a str> {
        card.queries
            .iter()
            .find(|q| q.id == id)
            .map(|q| q.sparql.as_str())
    }

    /// The single COUNT value of an aggregate query's one-row result.
    fn count_value(rete: &Rete, sparql: &str, var: &str) -> u64 {
        match eval_query(rete, sparql).unwrap() {
            QueryOutput::Select(_, rows) => {
                assert_eq!(rows.len(), 1, "expected one aggregate row");
                let lit = rows[0].get(var).expect("aggregate variable bound");
                lit.trim_start_matches('"')
                    .split('"')
                    .next()
                    .unwrap()
                    .parse()
                    .expect("count literal parses")
            }
            other => panic!("expected a SELECT result, got {other:?}"),
        }
    }

    /// A fixture exercising every signal so (almost) every template emits.
    fn rich_quads() -> Vec<(String, String, String, Option<String>)> {
        let label = "<http://www.w3.org/2000/01/rdf-schema#label>";
        let sameas = "<http://www.w3.org/2002/07/owl#sameAs>";
        let lat = "<http://www.w3.org/2003/01/geo/wgs84_pos#lat>";
        let long = "<http://www.w3.org/2003/01/geo/wgs84_pos#long>";
        let aswkt = "<http://www.opengis.net/ont/geosparql#asWKT>";
        let hasgeom = "<http://www.opengis.net/ont/geosparql#hasGeometry>";
        let gyear = "http://www.w3.org/2001/XMLSchema#gYear";
        let xint = "http://www.w3.org/2001/XMLSchema#integer";
        let wkt = "http://www.opengis.net/ont/geosparql#wktLiteral";
        let dbl = "http://www.w3.org/2001/XMLSchema#double";
        let mut v = Vec::new();
        for i in 0..6 {
            let s = format!("<http://ex/person/{i}>");
            v.push(q(&s, TYPE, "<http://ex/Person>"));
            v.push(q(&s, label, &format!("\"Person {i}\"@en")));
            v.push(q(&s, label, &format!("\"Personne {i}\"@fr")));
            v.push(q(
                &s,
                "<http://ex/birthYear>",
                &format!("\"{}\"^^<{gyear}>", 1800 + i),
            ));
            v.push(q(
                &s,
                "<http://ex/friendCount>",
                &format!("\"{}\"^^<{xint}>", i * 3),
            ));
            v.push(q(
                &s,
                "<http://ex/knows>",
                &format!("<http://ex/person/{}>", (i + 1) % 6),
            ));
            v.push(q(&s, "<http://ex/bornIn>", "<http://ex/place/0>"));
            if i % 2 == 0 {
                v.push(q(
                    &s,
                    sameas,
                    &format!("<http://www.wikidata.org/entity/Q{}>", 100 + i),
                ));
            }
        }
        v.push(q("<http://ex/place/0>", TYPE, "<http://ex/Place>"));
        v.push(q("<http://ex/place/0>", label, "\"Rome\"@en"));
        v.push(q("<http://ex/place/0>", lat, &format!("\"41.9\"^^<{dbl}>")));
        v.push(q(
            "<http://ex/place/0>",
            long,
            &format!("\"12.5\"^^<{dbl}>"),
        ));
        v.push(q(
            "<http://ex/place/0>",
            hasgeom,
            "<http://ex/place/0/geom>",
        ));
        v.push(q(
            "<http://ex/place/0/geom>",
            aswkt,
            &format!("\"POINT(12.5 41.9)\"^^<{wkt}>"),
        ));
        v
    }

    #[test]
    fn generated_queries_parse_run_and_are_tiered() {
        let quads = rich_quads();
        let card = derive_card(&quads, 50, 0, CardInput::default());
        assert!(
            card.queries.len() >= 12,
            "expected >= 12 starter queries, got {}",
            card.queries.len()
        );

        let (bytes, _) =
            ingest::assemble_dataset_with_opts(quads, true, false, None, |_, _| Vec::new());
        let rete = Rete::open(&bytes).unwrap();

        for eq in &card.queries {
            assert!(
                eq.sparql.starts_with("PREFIX"),
                "{}: no PREFIX block",
                eq.id
            );
            assert!(
                !eq.sparql.contains("{{"),
                "{}: unsubstituted placeholder",
                eq.id
            );
            assert!(!eq.dimension.is_empty(), "{}: missing dimension", eq.id);

            // Parses AND runs against the real engine (>= 0 rows, never an error).
            let result = eval_query(&rete, &eq.sparql);
            assert!(
                result.is_ok(),
                "{}: failed to run: {:?}",
                eq.id,
                result.err()
            );

            // Every Summary-tagged query is recognized by the index-free summary
            // classifier — the tier is truthful, not aspirational.
            if eq.tier == Tier::Summary {
                let shape = summary_query_shape(&eq.sparql);
                assert!(
                    matches!(shape, Ok(Some(_))),
                    "{}: tagged Summary but not summary-shaped: {:?}",
                    eq.id,
                    shape
                );
            }
        }

        // The default-only scope gets the same returns-rows contract the
        // named-only and mixed ones have had since #154 — the gap through which
        // `lb-labels`, `top-reach` and `sp-within` shipped broken on
        // default-graph files, which is the population most datasets are in.
        assert_every_query_returns_rows(&card, &rete);
    }

    /// Every statement in a named graph, the default graph empty — the shape
    /// (e.g. nkod.rete) whose cards used to ship six guaranteed-zero-rows
    /// queries. Includes an IRI that is referenced but never described, so
    /// `top-dangling` has rows to find.
    fn named_only_quads() -> Vec<(String, String, String, Option<String>)> {
        let mut v = Vec::new();
        for gi in 0..3 {
            let g = format!("<http://ex/graph/{gi}>");
            for i in 0..4 {
                let s = format!("<http://ex/item/{gi}-{i}>");
                v.push((
                    s.clone(),
                    TYPE.to_string(),
                    "<http://ex/Item>".to_string(),
                    Some(g.clone()),
                ));
                v.push((
                    s.clone(),
                    "<http://ex/rel>".to_string(),
                    format!("<http://ex/item/{gi}-{}>", (i + 1) % 4),
                    Some(g.clone()),
                ));
                v.push((
                    s,
                    "<http://ex/ref>".to_string(),
                    "<http://other/never-described>".to_string(),
                    Some(g.clone()),
                ));
            }
        }
        v
    }

    #[test]
    fn named_graph_only_queries_are_scoped_and_return_rows() {
        let quads = named_only_quads();
        let total = quads.len() as u64;
        let card = derive_card(&quads, 20, 3, CardInput::default());
        // The precondition of the bug: the card itself knows the default graph
        // is empty and the data lives in named graphs.
        assert_eq!(card.triple_count, 0);
        assert_eq!(card.named_graph_count, 3);

        // No emitted query may scan only the (empty) default graph.
        for eq in &card.queries {
            assert!(
                eq.sparql.contains("GRAPH"),
                "{}: default-graph-only query on a named-graph-only file:\n{}",
                eq.id,
                eq.sparql
            );
            // The pyramid summary covers the default graph only, so no
            // GRAPH-scoped query may claim the Summary tier.
            assert_ne!(eq.tier, Tier::Summary, "{}: untruthful Summary tier", eq.id);
        }

        let (bytes, _) =
            ingest::assemble_dataset_with_opts(quads, true, false, None, |_, _| Vec::new());
        let rete = Rete::open(&bytes).unwrap();
        assert_every_query_returns_rows(&card, &rete);

        // The headline count now reflects the data, not the empty default graph.
        let ov = card.queries.iter().find(|q| q.id == "ov-triples").unwrap();
        assert_eq!(count_value(&rete, &ov.sparql, "n"), total);
    }

    #[test]
    fn mixed_graph_queries_cover_both_sides_and_return_rows() {
        // Data in BOTH the default graph and a named graph.
        let mut quads = Vec::new();
        let label = "<http://www.w3.org/2000/01/rdf-schema#label>";
        for i in 0..4 {
            let s = format!("<http://ex/doc/{i}>");
            quads.push(q(&s, TYPE, "<http://ex/Doc>"));
            quads.push(q(&s, label, &format!("\"Doc {i}\"@en")));
            quads.push(q(
                &s,
                "<http://ex/rel>",
                &format!("<http://ex/doc/{}>", (i + 1) % 4),
            ));
            quads.push(q(&s, "<http://ex/rel>", "<http://other/never-described>"));
        }
        let default_count = quads.len() as u64;
        let g = "<http://ex/graph/annotations>".to_string();
        for i in 0..5 {
            quads.push((
                format!("<http://ex/note/{i}>"),
                "<http://ex/about>".to_string(),
                format!("<http://ex/doc/{}>", i % 4),
                Some(g.clone()),
            ));
        }
        let total = quads.len() as u64;

        let card = derive_card(&quads, 30, 1, CardInput::default());
        assert_eq!(card.triple_count, default_count);
        assert_eq!(card.quad_count, total);
        assert_eq!(card.named_graph_count, 1);

        let (bytes, _) =
            ingest::assemble_dataset_with_opts(quads, true, false, None, |_, _| Vec::new());
        let rete = Rete::open(&bytes).unwrap();
        assert_every_query_returns_rows(&card, &rete);

        // The overview count covers BOTH sides — neither half silently hidden.
        let ov = card.queries.iter().find(|q| q.id == "ov-triples").unwrap();
        assert_eq!(count_value(&rete, &ov.sparql, "n"), total);
        // And the named-graph family is present alongside the profile queries.
        let ids: Vec<&str> = card.queries.iter().map(|q| q.id.as_str()).collect();
        for id in ["ng-list", "ng-sizes", "ng-sample", "id-sample", "lb-labels"] {
            assert!(ids.contains(&id), "{id} missing from a mixed-graph card");
        }
    }

    #[test]
    fn default_graph_bodies_are_unchanged() {
        // A graph with no named graphs must get the classic bodies verbatim —
        // scope awareness may not perturb existing default-graph cards.
        let quads = rich_quads();
        let card = derive_card(&quads, 50, 0, CardInput::default());
        let ov = card.queries.iter().find(|q| q.id == "ov-triples").unwrap();
        assert!(ov
            .sparql
            .ends_with("SELECT (COUNT(*) AS ?n) WHERE { ?s ?p ?o }"));
        assert_eq!(ov.tier, Tier::Summary);
        for eq in &card.queries {
            assert!(
                !eq.sparql.contains("GRAPH ?g") && !eq.sparql.contains("UNION"),
                "{}: graph-scoped body leaked into a default-graph card",
                eq.id
            );
        }
    }

    /// The one-row smoke query returns EXACTLY one row in every graph scope —
    /// the unambiguous "did this file open and answer?" probe (a COUNT returns
    /// an honest 0 on a named-graph-only file and reads as failure).
    #[test]
    fn one_row_smoke_query_returns_exactly_one_row_in_every_scope() {
        type Quads = Vec<(String, String, String, Option<String>)>;
        let cases: Vec<(Quads, u64)> = vec![
            (rich_quads(), 0),       // default-only
            (named_only_quads(), 3), // named-graph-only
        ];
        for (quads, ng) in cases {
            let card = derive_card(&quads, 50, ng, CardInput::default());
            let smoke = card
                .queries
                .iter()
                .find(|q| q.id == "ov-one-row")
                .expect("ov-one-row always emits");
            let (bytes, _) =
                ingest::assemble_dataset_with_opts(quads, true, false, None, |_, _| Vec::new());
            let rete = Rete::open(&bytes).unwrap();
            match eval_query(&rete, &smoke.sparql).unwrap() {
                QueryOutput::Select(_, rows) => {
                    assert_eq!(rows.len(), 1, "ov-one-row must return exactly one row")
                }
                other => panic!("unexpected result form: {other:?}"),
            }
        }
    }

    #[test]
    fn families_are_gated_by_signal() {
        // A bare graph: no labels, no time, no geometry, no links, no named graphs.
        let quads = vec![
            q("<http://ex/a>", TYPE, "<http://ex/T>"),
            q("<http://ex/a>", "<http://ex/rel>", "<http://ex/b>"),
        ];
        let card = derive_card(&quads, 4, 0, CardInput::default());
        let ids: Vec<&str> = card.queries.iter().map(|q| q.id.as_str()).collect();

        // Signal-gated families are absent.
        for absent in [
            "sp-bbox",
            "sp-within",
            "ti-extent",
            "ti-histogram",
            "lb-labels",
            "ng-list",
            "ng-sample",
        ] {
            assert!(!ids.contains(&absent), "{absent} should be gated out");
        }
        // Unconditional overview queries are still present.
        for present in ["ov-triples", "ov-pred-list", "ov-pred-hist"] {
            assert!(ids.contains(&present), "{present} should always emit");
        }
        // Every object IRI is inside the dataset's own namespace, so "which
        // predicates link out?" has nothing to find — and is not emitted.
        assert!(
            !ids.contains(&"lk-external"),
            "lk-external has no external IRI"
        );
    }

    // ---------------------------------------------------------------------
    // The co-occurrence property: a body may conjoin only what the card proves
    // meets. Three fixtures, each reproducing the shape of a real dataset whose
    // published card ships a query that answers nothing.
    // ---------------------------------------------------------------------

    /// The **mtg** shape: the most populous class is NOT the one that carries
    /// the label predicate.
    ///
    /// `mtg:Ruling` has 76,990 instances and no `schema:name`; `mtg:Card` and
    /// its subclasses are fewer and carry all the names. A card generated from
    /// this graph must not join the top class to the label predicate, because
    /// the two never meet — that query returns zero rows on a plain
    /// default-graph file, and a reader concludes the file is broken.
    fn mtg_shaped_quads() -> Vec<(String, String, String, Option<String>)> {
        let name = "<http://schema.org/name>";
        let mut v = Vec::new();
        // 30 Rulings: the most populous class, no name anywhere on it.
        for i in 0..30 {
            let s = format!("<http://ex/ruling/{i}>");
            v.push(q(&s, TYPE, "<http://ex/Ruling>"));
            v.push(q(&s, "<http://ex/text>", &format!("\"Ruling text {i}\"")));
            v.push(q(
                &s,
                "<http://ex/about>",
                &format!("<http://ex/card/{}>", i % 5),
            ));
        }
        // 5 Cards: fewer instances, and the only things with a name.
        for i in 0..5 {
            let s = format!("<http://ex/card/{i}>");
            v.push(q(&s, TYPE, "<http://ex/Card>"));
            v.push(q(&s, name, &format!("\"Card {i}\"")));
            v.push(q(&s, "<http://ex/legalIn>", "<http://ex/format/standard>"));
        }
        v
    }

    #[test]
    fn top_class_without_the_label_predicate_still_answers() {
        let (card, rete) = card_and_graph(mtg_shaped_quads(), 60, 0);

        // The precondition of the bug, asserted so the fixture cannot drift
        // into the easy case: the top class is the one WITHOUT the label.
        assert_eq!(card.classes[0].0, "<http://ex/Ruling>");
        assert_eq!(
            card.signals.label_predicate.as_deref(),
            Some("<http://schema.org/name>")
        );
        assert!(
            !card
                .class_links
                .iter()
                .any(|l| l.s_class == "<http://ex/Ruling>"
                    && l.predicate == "<http://schema.org/name>"),
            "fixture precondition: the top class carries no label"
        );

        // The label query is still emitted — and it names the class that
        // actually has labels, not the biggest one.
        let lb = sparql_of(&card, "lb-labels").expect("lb-labels emitted");
        assert!(
            lb.contains("?s a <http://ex/Card> ; <http://schema.org/name> ?label"),
            "lb-labels must join the LABELLED class:\n{lb}"
        );
        assert!(
            !lb.contains("Ruling"),
            "the unlabelled top class leaked in:\n{lb}"
        );

        // Same class for the coverage query, so the two label queries are not
        // measuring different things (with TOP_CLASS this reported total/0).
        let cov = sparql_of(&card, "cmp-coverage").expect("cmp-coverage emitted");
        assert!(
            cov.contains("<http://ex/Card>"),
            "cmp-coverage on the wrong class"
        );

        // And the whole library answers.
        assert_every_query_returns_rows(&card, &rete);
    }

    /// The **hugging-face** shape: a label predicate exists, but no class the
    /// card can see carries it (there, `rdfs:label` sits only on the embedded
    /// ontology terms, whose `class_links` rows fall outside the top 100).
    /// The label query must degrade to the class-free form, not disappear.
    #[test]
    fn labels_off_every_known_class_fall_back_to_the_class_free_query() {
        let label = "<http://www.w3.org/2000/01/rdf-schema#label>";
        let mut quads = Vec::new();
        for i in 0..8 {
            let s = format!("<http://ex/model/{i}>");
            quads.push(q(&s, TYPE, "<http://ex/Model>"));
            quads.push(q(&s, "<http://ex/downloads>", &format!("\"{i}\"")));
        }
        // The only labels in the graph hang off UNTYPED subjects, so no
        // `class_links` row can witness a class that carries the predicate.
        for i in 0..3 {
            quads.push(q(
                &format!("<http://ex/term/{i}>"),
                label,
                &format!("\"Term {i}\"@en"),
            ));
        }
        let (card, rete) = card_and_graph(quads, 30, 0);

        assert_eq!(card.signals.label_predicate.as_deref(), Some(label));
        let lb = sparql_of(&card, "lb-labels").expect("lb-labels still emitted");
        assert!(
            lb.ends_with("SELECT ?s ?label WHERE { ?s <http://www.w3.org/2000/01/rdf-schema#label> ?label } LIMIT 50"),
            "expected the class-free fallback:\n{lb}"
        );
        // The fallback advertises the reduced gate it was emitted under.
        let req = &card
            .queries
            .iter()
            .find(|x| x.id == "lb-labels")
            .unwrap()
            .requires;
        assert_eq!(req, &["LABEL_PRED".to_string()]);
        // Coverage needs a labelled class and honestly has none, so it is gone
        // rather than reporting a percentage of the wrong class.
        assert!(sparql_of(&card, "cmp-coverage").is_none());
        assert_every_query_returns_rows(&card, &rete);
    }

    /// The **geoadmin** shape: `geo:asWKT` hangs straight off each feature and
    /// there is no `geo:hasGeometry` anywhere, so the fixed two-step path the
    /// template used to write could not match a single one of its 52,959
    /// geometries.
    #[test]
    fn geometry_hung_directly_off_the_feature_is_reachable() {
        let aswkt = "<http://www.opengis.net/ont/geosparql#asWKT>";
        let wkt = "http://www.opengis.net/ont/geosparql#wktLiteral";
        let mut quads = Vec::new();
        for i in 0..5 {
            let s = format!("<http://ex/district/{i}>");
            quads.push(q(&s, TYPE, "<http://ex/District>"));
            quads.push(q(&s, aswkt, &format!("\"POINT({} 4{i})\"^^<{wkt}>", i + 7)));
        }
        let (card, rete) = card_and_graph(quads, 20, 0);

        let sp = sparql_of(&card, "sp-within").expect("sp-within emitted");
        assert!(
            sp.contains("?s geo:asWKT ?w"),
            "expected the direct geometry path:\n{sp}"
        );
        assert!(
            !sp.contains("hasGeometry"),
            "a hasGeometry step the data does not have:\n{sp}"
        );
        match eval_query(&rete, sp).unwrap() {
            QueryOutput::Select(_, rows) => {
                assert_eq!(rows.len(), 5, "every feature is in the box")
            }
            other => panic!("unexpected result form: {other:?}"),
        }
        assert_every_query_returns_rows(&card, &rete);
    }

    /// Both geometry layouts in one graph: the optional step binds `?s` to the
    /// feature either way, so neither half is hidden.
    #[test]
    fn both_geometry_layouts_are_covered_by_one_path() {
        let (card, rete) = card_and_graph(rich_quads(), 50, 0);
        let sp = sparql_of(&card, "sp-within").expect("sp-within emitted");
        assert!(
            sp.contains("?s geo:hasGeometry?/geo:asWKT ?w"),
            "expected the optional-step path:\n{sp}"
        );
        match eval_query(&rete, sp).unwrap() {
            QueryOutput::Select(_, rows) => assert!(!rows.is_empty()),
            other => panic!("unexpected result form: {other:?}"),
        }
    }

    /// A graph of pure values — every object a literal, no `rdf:type` — has no
    /// group for the in-degree query and no IRI for the dangling-IRI one. The
    /// card knows (`in_hubs` is that precompute), so the generator refuses to
    /// emit either rather than shipping two queries that answer nothing.
    #[test]
    fn a_literal_only_graph_gets_no_object_queries() {
        let quads: Vec<_> = (0..6)
            .map(|i| {
                q(
                    &format!("<http://ex/row/{i}>"),
                    "<http://ex/value>",
                    &format!("\"v{i}\""),
                )
            })
            .collect();
        let (card, rete) = card_and_graph(quads, 12, 0);

        assert!(
            card.in_hubs.is_empty(),
            "fixture precondition: no IRI objects"
        );
        let ids: Vec<&str> = card.queries.iter().map(|x| x.id.as_str()).collect();
        for absent in ["top-in-hubs", "top-dangling"] {
            assert!(!ids.contains(&absent), "{absent} would return zero rows");
        }
        assert_every_query_returns_rows(&card, &rete);
    }

    // ---------------------------------------------------------------------
    // RDF-star: the `qt-*` family.
    // ---------------------------------------------------------------------

    const RECORDED_BY: &str = "<http://ex/recordedBy>";
    const CONFIDENCE: &str = "<http://ex/confidence>";
    const STATES: &str = "<http://ex/states>";
    const COUNT_OF: &str = "<http://ex/count>";

    /// A provenance graph: every occurrence is typed, most of those type
    /// assertions are themselves annotated with who recorded them, and two
    /// claims hold a statement as their *value* — the object position, which
    /// is a different capability from the subject one.
    ///
    /// Deliberately **partial**: `occ4`'s type assertion carries no annotation,
    /// so `qt-coverage` reports a real ratio instead of a vacuous 100 %.
    fn annotated_quads() -> Vec<(String, String, String, Option<String>)> {
        let mut v = Vec::new();
        for i in 0..4 {
            let s = format!("<http://ex/occ/{i}>");
            let species = if i < 2 {
                "<http://ex/Swallow>"
            } else {
                "<http://ex/Robin>"
            };
            v.push(q(&s, TYPE, species));
            v.push(q(&s, COUNT_OF, &format!("\"{}\"", i + 1)));
            // The star layer: a statement about the type assertion above.
            if i < 3 {
                let quoted = format!("<<{s} {TYPE} {species}>>");
                v.push(q(
                    &quoted,
                    RECORDED_BY,
                    if i == 0 {
                        "<http://ex/jsmith>"
                    } else {
                        "<http://ex/adoe>"
                    },
                ));
                if i == 0 {
                    v.push(q(&quoted, CONFIDENCE, "\"0.9\""));
                }
            }
            // …and the other position: a claim whose VALUE is a statement.
            if i < 2 {
                v.push(q(
                    &format!("<http://ex/claim/{i}>"),
                    STATES,
                    &format!("<<{s} {COUNT_OF} \"{}\">>", i + 1),
                ));
            }
        }
        v
    }

    /// The family emits, every query answers on the graph it came from, and
    /// the coverage aggregate reports the ratio the fixture really has.
    #[test]
    fn statement_queries_are_generated_and_return_rows() {
        let quads = annotated_quads();
        let (card, rete) = card_and_graph(quads, 40, 0);

        // The derive-time profile, which is what makes any of this possible:
        // the header's presence bit names no vocabulary.
        let s = &card.signals;
        assert_eq!(s.annotation_predicates, vec![RECORDED_BY, CONFIDENCE]);
        assert_eq!(s.quoting_predicates, vec![STATES]);
        assert_eq!(
            s.annotated_statement,
            Some((TYPE.to_string(), RECORDED_BY.to_string())),
            "the witness must be a statement the graph BOTH asserts and annotates"
        );

        let ids: Vec<&str> = card.queries.iter().map(|x| x.id.as_str()).collect();
        for want in [
            "qt-sample",
            "qt-about",
            "qt-qualifiers",
            "qt-coverage",
            "qt-quoted-object",
        ] {
            assert!(ids.contains(&want), "{want} should be emitted: {ids:?}");
        }
        for eq in card.queries.iter().filter(|x| x.id.starts_with("qt-")) {
            assert_eq!(eq.dimension, "statements");
            // The query surface is RDF-star (`<< s p o >>`). The ratified
            // RDF 1.2 spelling `<<( s p o )>>` is an EXPORT surface; a body in
            // it would not parse, which is the worst content a card can carry.
            assert!(
                !eq.sparql.contains("<<("),
                "{}: RDF 1.2 triple-term syntax in a QUERY",
                eq.id
            );
        }

        // The whole point: every one of them answers on this graph.
        assert_every_query_returns_rows(&card, &rete);

        // And the coverage aggregate counts what the fixture actually holds:
        // four type assertions, three of them annotated.
        let cov = sparql_of(&card, "qt-coverage").unwrap();
        assert_eq!(count_value(&rete, cov, "asserted"), 4);
        assert_eq!(count_value(&rete, cov, "qualified"), 3);
    }

    /// The overwhelmingly common case: no quoted triples, so no `qt-*` query,
    /// no empty section, and — because all three new signal fields serialize
    /// only when non-empty — a card byte-identical to one built before the
    /// family existed.
    #[test]
    fn a_graph_without_quoted_triples_gains_nothing() {
        let quads = rich_quads();
        let card = derive_card(&quads, 50, 0, CardInput::default());
        let s = &card.signals;
        assert!(s.annotation_predicates.is_empty());
        assert!(s.quoting_predicates.is_empty());
        assert!(s.annotated_statement.is_none());
        assert!(
            !card.queries.iter().any(|x| x.id.starts_with("qt-")),
            "a graph with no quoted triple must gain no statement query"
        );
        // The card's own bytes say nothing about a layer it does not have.
        let json = String::from_utf8(card.to_json_bytes()).unwrap();
        for key in [
            "annotation_predicates",
            "quoting_predicates",
            "annotated_statement",
        ] {
            assert!(!json.contains(key), "{key} reached a card that has none");
        }
    }

    /// Presence is not position. A graph that only ever holds a statement as a
    /// *value* has nothing for a subject-position body to match — the header's
    /// `FLAG_HAS_QUOTED_TRIPLES` cannot tell the two apart, and a query written
    /// for the wrong one is exactly the zero-rows failure this library exists
    /// to prevent.
    #[test]
    fn a_statement_held_only_as_a_value_gets_only_the_object_position_query() {
        let quads = vec![
            q("<http://ex/a>", TYPE, "<http://ex/T>"),
            q("<http://ex/a>", "<http://ex/p>", "<http://ex/b>"),
            q(
                "<http://ex/claim>",
                STATES,
                "<<<http://ex/a> <http://ex/p> <http://ex/b>>>",
            ),
        ];
        let (card, rete) = card_and_graph(quads, 12, 0);
        assert!(card.signals.annotation_predicates.is_empty());
        assert_eq!(card.signals.quoting_predicates, vec![STATES]);

        let ids: Vec<&str> = card.queries.iter().map(|x| x.id.as_str()).collect();
        assert!(ids.contains(&"qt-quoted-object"));
        for absent in ["qt-sample", "qt-about", "qt-qualifiers", "qt-coverage"] {
            assert!(
                !ids.contains(&absent),
                "{absent} has no subject-position statement to match"
            );
        }
        assert_every_query_returns_rows(&card, &rete);
    }

    /// A statement this graph annotates but never asserts cannot witness the
    /// coverage query: `?s p ?o` would match nothing and the aggregate would
    /// report `0 / 0`, which is the `mtg` "76990 / 0" failure one level up.
    /// The other four still emit — the quoted layer is real, it is only the
    /// join to the asserted one that is missing.
    #[test]
    fn an_annotation_of_an_unasserted_statement_witnesses_no_coverage() {
        let quads = vec![
            q("<http://ex/a>", TYPE, "<http://ex/T>"),
            q(
                "<<<http://ex/a> <http://ex/p> <http://ex/b>>>",
                RECORDED_BY,
                "<http://ex/jsmith>",
            ),
        ];
        let (card, rete) = card_and_graph(quads, 10, 0);
        assert_eq!(card.signals.annotation_predicates, vec![RECORDED_BY]);
        assert!(
            card.signals.annotated_statement.is_none(),
            "nothing asserts <http://ex/a> <http://ex/p> <http://ex/b>"
        );
        let ids: Vec<&str> = card.queries.iter().map(|x| x.id.as_str()).collect();
        assert!(
            !ids.contains(&"qt-coverage"),
            "no witness, no coverage query"
        );
        for want in ["qt-sample", "qt-about", "qt-qualifiers"] {
            assert!(ids.contains(&want), "{want} needs only the star layer");
        }
        assert_every_query_returns_rows(&card, &rete);
    }

    /// The audit reaches the RDF-star conjunction through the card's witness
    /// rather than through step 7, which would see two ranked predicates and
    /// decline — and it stops vouching for a published body whose pair the
    /// card no longer witnesses.
    #[test]
    fn the_audit_decides_the_star_conjunction_from_the_witness() {
        let mut card = derive_card(&annotated_quads(), 40, 0, CardInput::default());
        let findings = audit(&card);
        assert_eq!(verdict_of(&findings, "qt-coverage"), Verdict::Answers);

        // The same body on a card whose witness has moved: the pair is no
        // longer proven, and the audit says so instead of vouching for it.
        card.signals.annotated_statement = Some((COUNT_OF.to_string(), CONFIDENCE.to_string()));
        let findings = audit(&card);
        assert_eq!(verdict_of(&findings, "qt-coverage"), Verdict::Suspect);
    }

    /// The table-level audit: nothing in the library may conjoin two
    /// independently-chosen substitutions, and every placeholder must be
    /// declared. This is the check that makes the bug unrepresentable rather
    /// than merely fixed — it runs over every body of every template, in every
    /// graph scope, with no dataset involved.
    #[test]
    fn every_template_body_is_witnessed() {
        let mut problems = Vec::new();
        for t in TEMPLATES {
            for body in [Some(t.body), t.named_body, t.mixed_body]
                .into_iter()
                .flatten()
            {
                if let Err(e) = check_body(t.id, body, t.requires, t.nonempty) {
                    problems.push(e);
                }
            }
            if let Some(f) = &t.fallback {
                if let Err(e) = check_body(t.id, f.body, f.requires, f.nonempty) {
                    problems.push(e);
                }
                assert!(
                    f.requires.len() < t.requires.len(),
                    "{}: a fallback must need LESS than the template it stands in for",
                    t.id
                );
            }
            if let Some(b) = &t.bounded {
                for body in [Some(b.body), b.named_body].into_iter().flatten() {
                    if let Err(e) = check_body(t.id, body, b.requires, b.nonempty) {
                        problems.push(e);
                    }
                }
            }
        }
        assert!(problems.is_empty(), "{}", problems.join("\n"));
    }

    // ---------------------------------------------------------------------
    // B4: the cost gate. Every emitted starter is bounded — by the budget
    // when the card says the exact body is cheap, by its bounded form when
    // not, and by not being emitted when it has no honest bounded form.
    // ---------------------------------------------------------------------

    /// The ids whose exact question the card's own profile already answers,
    /// and which therefore ship nothing at all past the budget.
    const PROFILE_ANSWERS: &[&str] = &[
        "ov-triples",
        "ov-pred-list",
        "ov-pred-hist",
        "ty-class-hist",
        "ty-entities",
        "top-out-hubs",
        "top-in-hubs",
        "lt-datatypes",
        "lt-langs",
        "lt-numrange",
        "ti-extent",
        "ti-histogram",
        "sp-bbox",
        "ng-sizes",
        "qt-about",
        "qt-qualifiers",
        "top-class-graph",
    ];

    /// Generate under a budget of zero — every template whose body reads
    /// anything takes its bounded form or is dropped — and run every emitted
    /// query against the graph it was generated for.
    fn assert_bounded_library(quads: Vec<(String, String, String, Option<String>)>, ng: u64) {
        let card = derive_card(&quads, 60, ng, CardInput::default());
        let (bytes, _) =
            ingest::assemble_dataset_with_opts(quads, true, false, None, |_, _| Vec::new());
        let rete = Rete::open(&bytes).unwrap();
        let bounded = generate_with_budget(&card, 0);
        assert!(!bounded.is_empty(), "nothing survived a zero budget");
        for eq in &bounded {
            let t = TEMPLATES.iter().find(|t| t.id == eq.id).unwrap();
            // Either self-bounded, or the bounded form — never the exact body
            // of a template that reads something.
            if t.scan != Scan::Bounded {
                let b = t
                    .bounded
                    .as_ref()
                    .unwrap_or_else(|| panic!("{}: emitted past the budget", eq.id));
                assert!(
                    eq.sparql.ends_with(b.body)
                        || b.named_body.is_some_and(|nb| eq.sparql.ends_with(nb))
                        || {
                            // Substituted bodies cannot be compared verbatim; the
                            // variant matcher is the arbiter.
                            variant_of(t, strip_prefixes(&eq.sparql).trim())
                                .is_some_and(|v| v.bounded)
                        },
                    "{}: not the bounded form:\n{}",
                    eq.id,
                    eq.sparql
                );
                assert_eq!(
                    eq.title, b.title,
                    "{}: the title must say it is a sample",
                    eq.id
                );
            }
            assert!(
                !PROFILE_ANSWERS.contains(&eq.id.as_str()),
                "{}: a profile-answered question shipped past the budget",
                eq.id
            );
            let undecidable = claim_of_query(&eq.id, &eq.sparql) == Claim::Undecidable;
            match eval_query(&rete, &eq.sparql) {
                Ok(QueryOutput::Select(_, rows)) => assert!(
                    undecidable || !rows.is_empty(),
                    "{}: bounded form returned zero rows:\n{}",
                    eq.id,
                    eq.sparql
                ),
                Ok(QueryOutput::Ask(b)) => assert!(undecidable || b, "{}: ASK false", eq.id),
                Ok(QueryOutput::Construct(ts)) => assert!(undecidable || !ts.is_empty()),
                Err(e) => panic!("{}: failed to run: {e:?}\n{}", eq.id, eq.sparql),
            }
        }
        // And the audit reads every bounded body as a known form of its
        // template — never "unrecognized".
        let mut shipped = card.clone();
        shipped.queries = bounded;
        for f in audit(&shipped) {
            assert_ne!(f.verdict, Verdict::Unrecognized, "{}: {}", f.id, f.why);
        }
    }

    #[test]
    fn bounded_forms_parse_run_and_answer_in_every_scope() {
        assert_bounded_library(rich_quads(), 0);
        assert_bounded_library(named_only_quads(), 3);
        assert_bounded_library(mtg_shaped_quads(), 0);
        assert_bounded_library(annotated_quads(), 0);
        let mut mixed = rich_quads();
        for i in 0..5 {
            mixed.push((
                format!("<http://ex/note/{i}>"),
                "<http://ex/about>".to_string(),
                format!("<http://ex/person/{}>", i % 6),
                Some("<http://ex/graph/notes>".to_string()),
            ));
        }
        assert_bounded_library(mixed, 1);
    }

    /// The gate reads the card's counts, so a graph the size of an
    /// OpenCitations part gets bounded bodies whatever its fixture size. Here
    /// the rich fixture's card is inflated to 2.9 B statements: every emitted
    /// body must be bounded, the profile-answered questions must be gone, and
    /// the bounded forms must be the ones that ship.
    #[test]
    fn a_billion_statement_card_ships_only_bounded_starters() {
        let mut card = derive_card(&rich_quads(), 50, 0, CardInput::default());
        let scale = 50_000_000u64;
        card.triple_count *= scale;
        card.quad_count = card.triple_count;
        for (_, n) in card.predicates.iter_mut().chain(card.classes.iter_mut()) {
            *n *= scale;
        }
        for l in &mut card.class_links {
            l.count *= scale;
        }
        let queries = generate(&card);
        let ids: Vec<&str> = queries.iter().map(|q| q.id.as_str()).collect();
        for gone in PROFILE_ANSWERS {
            assert!(!ids.contains(gone), "{gone} shipped on a 2.9 B card");
        }
        for kept in [
            "ov-one-row",
            "ov-ask-pred",
            "id-sample",
            "lb-labels",
            "top-reach",
            "ty-class-shape",
            "top-dangling",
            "cmp-coverage",
            "lk-sameas",
            "lk-external",
            "sp-within",
        ] {
            assert!(
                ids.contains(&kept),
                "{kept} missing from the bounded set {ids:?}"
            );
        }
        let shape = queries.iter().find(|q| q.id == "ty-class-shape").unwrap();
        assert!(shape.sparql.contains("LIMIT 1000"), "{}", shape.sparql);
        assert!(shape.title.contains("1,000"), "{}", shape.title);
        // Within the budget the same card writes the exact bodies.
        let small = derive_card(&rich_quads(), 50, 0, CardInput::default());
        let exact = generate(&small);
        let shape = exact.iter().find(|q| q.id == "ty-class-shape").unwrap();
        assert!(!shape.sparql.contains("LIMIT 1000"), "{}", shape.sparql);
        // The audit agrees with the generator about the inflated card: what it
        // ships is current, and nothing is refuted.
        card.queries = queries;
        for f in audit(&card) {
            assert_eq!(f.revision, "current", "{}", f.id);
            assert!(
                matches!(f.verdict, Verdict::Answers | Verdict::Undecidable),
                "{}: {} — {}",
                f.id,
                f.verdict.as_str(),
                f.why
            );
        }
    }

    /// The bounded form's own claim is what `claim_of_query` reports — a
    /// sample of a graph may honestly hold no dangling IRI even where the
    /// whole graph does, and the measured-zero drop must not call that a
    /// generator defect.
    #[test]
    fn the_claim_follows_the_form_that_shipped() {
        let card = derive_card(&rich_quads(), 50, 0, CardInput::default());
        let exact = generate(&card);
        let shape = exact.iter().find(|q| q.id == "ty-class-shape").unwrap();
        assert_eq!(
            claim_of_query(&shape.id, &shape.sparql),
            Claim::CannotBeEmpty
        );
        let bounded = generate_with_budget(&card, 0);
        let external = bounded.iter().find(|q| q.id == "lk-external").unwrap();
        assert_eq!(claim_of("lk-external"), Claim::CannotBeEmpty);
        assert_eq!(
            claim_of_query(&external.id, &external.sparql),
            Claim::Undecidable,
            "the 1,000-statement sample may hold no external IRI"
        );
        // An unknown body falls back to the template's own claim.
        assert_eq!(
            claim_of_query("ty-class-shape", "SELECT ?x WHERE { ?x ?y ?z }"),
            Claim::CannotBeEmpty
        );
        assert_eq!(claim_of_query("not-a-template", "ASK {}"), Claim::Unknown);
    }

    /// The new `top-dangling` body returns the rows the old one did, and the
    /// old one — on published cards — is recognized and reported superseded.
    #[test]
    fn the_dangling_query_is_rewritten_without_changing_its_rows() {
        let (mut card, rete) = card_and_graph(named_only_quads_as_default(), 30, 0);
        let new = sparql_of(&card, "top-dangling").unwrap().to_string();
        let old = "SELECT ?o WHERE { ?s ?p ?o FILTER(isIRI(?o)) FILTER NOT EXISTS { ?o ?p2 ?o2 } } LIMIT 100";
        let rows = |q: &str| -> std::collections::BTreeSet<String> {
            match eval_query(&rete, q).unwrap() {
                QueryOutput::Select(_, rows) => rows
                    .iter()
                    .map(|r| r.get("o").cloned().unwrap_or_default())
                    .collect(),
                other => panic!("{other:?}"),
            }
        };
        assert_eq!(rows(&new), rows(&format!("{PREFIXES}\n{old}")));
        assert!(!rows(&new).is_empty());
        ship_instead(&mut card, "top-dangling", old);
        let f = audit(&card);
        let d = f.iter().find(|f| f.id == "top-dangling").unwrap();
        assert_eq!(d.revision, "superseded");
        assert_eq!(d.verdict, Verdict::Undecidable);
    }

    /// `named_only_quads`, moved into the default graph: a graph with one IRI
    /// every item references and nobody describes.
    fn named_only_quads_as_default() -> Vec<(String, String, String, Option<String>)> {
        named_only_quads()
            .into_iter()
            .map(|(s, p, o, _)| (s, p, o, None))
            .collect()
    }

    // ---------------------------------------------------------------------
    // D1: the curated `example_queries` are audited too, apart.
    // ---------------------------------------------------------------------

    #[test]
    fn curated_example_queries_are_audited_separately() {
        let mut card = derive_card(&rich_quads(), 50, 0, CardInput::default());
        card.example_queries = vec![
            // Parses, names only predicates the card knows: nothing to decide.
            "SELECT ?s WHERE { ?s <http://ex/knows> ?o } LIMIT 5".to_string(),
            // Does not parse.
            "SELECT ?s WHERE { ?s <http://ex/knows> ".to_string(),
            // A predicate the card's complete list does not contain.
            "SELECT ?s WHERE { ?s <http://ex/neverUsed> ?o }".to_string(),
        ];
        let findings = audit_examples(&card);
        assert_eq!(findings.len(), 3);
        assert_eq!(findings[0].id, "example-1");
        assert_eq!(findings[0].verdict, Verdict::Undecidable);
        assert_eq!(findings[0].revision, "curated");
        assert_eq!(findings[1].verdict, Verdict::Invalid);
        assert!(
            findings[1].why.contains("does not parse"),
            "{}",
            findings[1].why
        );
        assert_eq!(findings[2].verdict, Verdict::Suspect);
        assert!(findings[2].why.contains("neverUsed"), "{}", findings[2].why);
        // The generated half is untouched by the curated half.
        assert_eq!(audit(&card).len(), card.queries.len());

        // A truncated predicate list proves nothing absent: undecidable.
        card.predicates = (0..CARD_TOP_N)
            .map(|i| (format!("<http://ex/p{i}>"), 1))
            .collect();
        let f = audit_examples(&card);
        assert_eq!(f[2].verdict, Verdict::Undecidable, "{}", f[2].why);
    }

    #[test]
    fn a_curated_default_graph_query_on_a_named_only_file_is_empty() {
        let mut card = derive_card(&named_only_quads(), 20, 3, CardInput::default());
        card.example_queries = vec![
            "SELECT ?s WHERE { ?s ?p ?o } LIMIT 1".to_string(),
            "SELECT ?s WHERE { GRAPH ?g { ?s ?p ?o } } LIMIT 1".to_string(),
        ];
        let f = audit_examples(&card);
        assert_eq!(f[0].verdict, Verdict::Empty, "{}", f[0].why);
        assert_ne!(f[1].verdict, Verdict::Empty, "{}", f[1].why);
    }

    // ---------------------------------------------------------------------
    // The audit: reading a card that is already published.
    // ---------------------------------------------------------------------

    /// Replace one starter query's body with the one an older revision wrote —
    /// how a fixture stands in for a file that is already on the wire.
    fn ship_instead(card: &mut DatasetCard, id: &str, body: &str) {
        let q = card
            .queries
            .iter_mut()
            .find(|q| q.id == id)
            .unwrap_or_else(|| panic!("{id} is not in this card"));
        q.sparql = format!("{PREFIXES}\n{body}");
    }

    fn verdict_of(findings: &[Finding], id: &str) -> Verdict {
        findings
            .iter()
            .find(|f| f.id == id)
            .unwrap_or_else(|| panic!("{id} was not audited"))
            .verdict
    }

    fn rows_of(rete: &Rete, sparql: &str) -> usize {
        match eval_query(rete, sparql).unwrap() {
            QueryOutput::Select(_, rows) => rows.len(),
            QueryOutput::Ask(b) => usize::from(b),
            other => panic!("unexpected result form: {other:?}"),
        }
    }

    /// A card this generator just wrote must audit clean: nothing refuted,
    /// nothing suspected, nothing unrecognized, and every body current. If the
    /// audit and the generator ever disagree about a *fresh* card, one of them
    /// is wrong — and they are supposed to share the judgement.
    #[test]
    fn a_freshly_generated_card_audits_clean() {
        for (quads, ng) in [(rich_quads(), 0), (named_only_quads(), 3)] {
            let card = derive_card(&quads, 50, ng, CardInput::default());
            for f in audit(&card) {
                assert_eq!(
                    f.revision, "current",
                    "{}: the generator would not write this body",
                    f.id
                );
                assert!(
                    matches!(f.verdict, Verdict::Answers | Verdict::Undecidable),
                    "{}: {} — {}",
                    f.id,
                    f.verdict.as_str(),
                    f.why
                );
                // The only queries a fresh card may leave undecided are the
                // ones the table already says it cannot decide, plus `sp-bbox`:
                // its un-grouped aggregate always returns its row (so
                // `NonEmpty::Aggregate` is true about *rows*), and whether that
                // row is bound turns on two predicates meeting on one subject,
                // which is the one thing `class_links` cannot witness.
                if f.verdict == Verdict::Undecidable {
                    assert!(
                        may_be_empty(&f.id) || f.id == "sp-bbox",
                        "{}: undecidable but the table claims otherwise — {}",
                        f.id,
                        f.why
                    );
                }
            }
        }
    }

    /// The **mtg** card as published: the label query joins the most populous
    /// class to the most-used label predicate. The audit refutes it, and the
    /// engine agrees — the verdict is checked against the graph, not just
    /// against the card.
    #[test]
    fn the_audit_refutes_a_label_query_on_an_unlabelled_top_class() {
        let quads = mtg_shaped_quads();
        let (mut card, rete) = card_and_graph(quads, 60, 0);
        let top = card.classes[0].0.clone();
        ship_instead(
            &mut card,
            "lb-labels",
            &format!("SELECT ?s ?label WHERE {{ ?s a {top} ; <http://schema.org/name> ?label }} LIMIT 50"),
        );
        ship_instead(
            &mut card,
            "cmp-coverage",
            &format!(
                "SELECT (COUNT(?s) AS ?total) (COUNT(?l) AS ?have) WHERE {{ ?s a {top} \
                 OPTIONAL {{ ?s <http://schema.org/name> ?l }} }}"
            ),
        );
        let findings = audit(&card);
        assert_eq!(verdict_of(&findings, "lb-labels"), Verdict::Empty);
        // The coverage query is an un-grouped aggregate: it returns its row, and
        // the row says `have = 0`. A different failure, reported as one.
        assert_eq!(verdict_of(&findings, "cmp-coverage"), Verdict::Vacuous);
        assert_eq!(rows_of(&rete, sparql_of(&card, "lb-labels").unwrap()), 0);
        assert_eq!(rows_of(&rete, sparql_of(&card, "cmp-coverage").unwrap()), 1);
    }

    /// The **vidy** shape, and the one false positive this audit was caught
    /// making: every unit is typed *twice* — `schema:ArchiveComponent` and a
    /// native class — so the `class_links` quotient, which files each subject
    /// under its last type only, shows no label row for the top class even
    /// though the label query returns rows.
    ///
    /// The audit must NOT claim a refutation here. Both tells are present (the
    /// top class has no row of its own; another class has exactly its instance
    /// count), and a survey that called this "provably empty" would have sent
    /// someone to re-card a file that was fine.
    #[test]
    fn the_audit_will_not_refute_a_dually_typed_class() {
        let name = "<http://schema.org/name>";
        let component = "<http://ex/ArchiveComponent>";
        let unit = "<http://ex/Unit>";
        let mut quads = Vec::new();
        for i in 0..8 {
            let s = format!("<http://ex/unit/{i}>");
            // Both types, the native one last — so the quotient files every
            // statement under `Unit` and says nothing about `ArchiveComponent`.
            quads.push(q(&s, TYPE, component));
            quads.push(q(&s, TYPE, unit));
            quads.push(q(&s, name, &format!("\"Unit {i}\"")));
        }
        let (mut card, rete) = card_and_graph(quads, 30, 0);
        assert_eq!(
            card.classes[0].0, component,
            "fixture: the twin ranks first"
        );
        assert!(
            !card.class_links.iter().any(|l| l.s_class == component),
            "fixture: the quotient never mentions the top class"
        );
        ship_instead(
            &mut card,
            "lb-labels",
            &format!("SELECT ?s ?label WHERE {{ ?s a {component} ; {name} ?label }} LIMIT 50"),
        );
        assert_eq!(verdict_of(&audit(&card), "lb-labels"), Verdict::Suspect);
        assert_eq!(rows_of(&rete, sparql_of(&card, "lb-labels").unwrap()), 8);
    }

    /// The **geoadmin** card as published: a fixed two-step geometry path on a
    /// file that hangs `geo:asWKT` straight off the feature. Nothing to do with
    /// typing — the path names a predicate the card's complete list does not
    /// contain, so the refutation is exact.
    #[test]
    fn the_audit_refutes_a_path_through_a_predicate_that_is_not_there() {
        let aswkt = "<http://www.opengis.net/ont/geosparql#asWKT>";
        let wkt = "http://www.opengis.net/ont/geosparql#wktLiteral";
        let mut quads = Vec::new();
        for i in 0..5 {
            let s = format!("<http://ex/district/{i}>");
            quads.push(q(&s, TYPE, "<http://ex/District>"));
            quads.push(q(&s, aswkt, &format!("\"POINT({} 4{i})\"^^<{wkt}>", i + 7)));
        }
        let (mut card, rete) = card_and_graph(quads, 20, 0);
        ship_instead(
            &mut card,
            "sp-within",
            "SELECT ?s WHERE { ?s geo:hasGeometry/geo:asWKT ?w FILTER(geof:sfWithin(?w, \
             \"POLYGON((-180 -90, 180 -90, 180 90, -180 90, -180 -90))\"^^geo:wktLiteral)) } LIMIT 100",
        );
        assert_eq!(verdict_of(&audit(&card), "sp-within"), Verdict::Empty);
        assert_eq!(rows_of(&rete, sparql_of(&card, "sp-within").unwrap()), 0);
    }

    /// A `VALUES` list that does not cover the gate admitting the query: the
    /// dataset links only with `skos:closeMatch`, the shipped body names the
    /// other three. Refutable exactly — `signals.link_predicates` is computed
    /// from the full predicate counts, before any cap.
    #[test]
    fn the_audit_refutes_a_values_list_that_misses_the_only_link_predicate() {
        let close = "<http://www.w3.org/2004/02/skos/core#closeMatch>";
        let mut quads = vec![q("<http://ex/a>", TYPE, "<http://ex/T>")];
        for i in 0..4 {
            quads.push(q(
                &format!("<http://ex/a{i}>"),
                close,
                &format!("<http://other/x{i}>"),
            ));
        }
        let (mut card, rete) = card_and_graph(quads, 20, 0);
        assert_eq!(card.signals.link_predicates, vec![close.to_string()]);
        ship_instead(
            &mut card,
            "lk-sameas",
            "SELECT ?p (COUNT(*) AS ?n) WHERE { ?s ?p ?o VALUES ?p { owl:sameAs \
             skos:exactMatch rdfs:seeAlso } } GROUP BY ?p",
        );
        assert_eq!(verdict_of(&audit(&card), "lk-sameas"), Verdict::Empty);
        assert_eq!(rows_of(&rete, sparql_of(&card, "lk-sameas").unwrap()), 0);
    }

    /// The pre-#172 `top-reach` — a hub IRI and a top predicate, conjoined —
    /// is recognized (so it is not reported as an unreadable body) and honestly
    /// declared undecidable: nothing in a card ties a *subject* to a
    /// *predicate*. On the published catalog 6 of 26 sampled files answered
    /// nothing here, which is exactly what "undecidable" has to mean.
    #[test]
    fn the_audit_recognizes_the_legacy_reach_query_and_declines_to_decide() {
        let (mut card, _) = card_and_graph(rich_quads(), 50, 0);
        let hub = card.top_hubs[0].0.clone();
        let pred = card.predicates[0].0.clone();
        ship_instead(
            &mut card,
            "top-reach",
            &format!("SELECT ?y WHERE {{ {hub} {pred}+ ?y }} LIMIT 100"),
        );
        let f = audit(&card);
        let r = f.iter().find(|f| f.id == "top-reach").unwrap();
        assert_eq!(r.verdict, Verdict::Undecidable);
        assert_eq!(r.revision, "superseded");
        assert!(r.conjoined, "two independently-ranked terms in one body");
        assert_eq!(r.substitutions.len(), 2);
    }

    /// A body from no revision at all is reported as such rather than being
    /// force-fitted to the nearest pattern — a wrong binding would produce a
    /// confident wrong verdict, which is the failure mode a survey cannot have.
    #[test]
    fn an_unknown_body_is_not_force_fitted() {
        let (mut card, _) = card_and_graph(rich_quads(), 50, 0);
        ship_instead(
            &mut card,
            "lb-labels",
            "SELECT ?x WHERE { ?x ?y ?z } LIMIT 3",
        );
        assert_eq!(
            verdict_of(&audit(&card), "lb-labels"),
            Verdict::Unrecognized
        );
    }

    /// Ids are unique and every capability the table names is reachable — a
    /// `Cap` no template requires is dead weight that will drift out of date.
    #[test]
    fn the_table_is_well_formed() {
        let mut ids: Vec<&str> = TEMPLATES.iter().map(|t| t.id).collect();
        let n = ids.len();
        ids.sort_unstable();
        ids.dedup();
        assert_eq!(ids.len(), n, "duplicate template id");
        for &cap in ALL_CAPS {
            assert!(
                TEMPLATES.iter().any(|t| t.requires.contains(&cap)
                    || t.fallback
                        .as_ref()
                        .is_some_and(|f| f.requires.contains(&cap))),
                "{} is required by no template",
                cap.key()
            );
        }
        for t in TEMPLATES {
            assert!(
                !t.hook_is_exact || t.provably_empty.is_some(),
                "{}: hook_is_exact without a hook to be exact about",
                t.id
            );
        }
        // A bounded form must be bounded by its own text: every body reads a
        // LIMITed slice or asks a lookup-sized question, and carries the
        // placeholders it declares.
        for t in TEMPLATES {
            if let Some(b) = &t.bounded {
                assert!(
                    t.scan != Scan::Bounded,
                    "{}: a self-bounded template needs no bounded form",
                    t.id
                );
                for body in [Some(b.body), b.named_body].into_iter().flatten() {
                    assert!(
                        body.contains("LIMIT") || body.contains("FILTER EXISTS"),
                        "{}: bounded body without a LIMIT or an existence probe:\n{body}",
                        t.id
                    );
                }
            }
        }
        // Every legacy body names a template that still exists (otherwise the
        // audit could never reach it) and is genuinely different from the ones
        // that template writes now (otherwise it is dead weight).
        for l in LEGACY_BODIES {
            let t = TEMPLATES
                .iter()
                .find(|t| t.id == l.id)
                .unwrap_or_else(|| panic!("legacy body for unknown template {}", l.id));
            assert!(
                ![Some(t.body), t.named_body, t.mixed_body]
                    .into_iter()
                    .flatten()
                    .any(|b| b == l.body),
                "{}: legacy body is still a current one",
                l.id
            );
        }
    }
}