qua 0.71.0

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

use anyhow::Context;
use clap::Parser;
use quarb::{AstAdapter, NodeId, QueryResult, Value};
#[cfg(feature = "adapters")]
use quarb_athena::AthenaAdapter;
#[cfg(feature = "adapters")]
use quarb_atrep::AtrepAdapter;
#[cfg(feature = "adapters")]
use quarb_bigquery::BigqueryAdapter;
#[cfg(feature = "adapters")]
use quarb_compose::ComposeAdapter;
#[cfg(feature = "adapters")]
use quarb_csv::CsvAdapter;
#[cfg(feature = "adapters")]
use quarb_duckdb::DuckdbAdapter;
#[cfg(feature = "adapters")]
use quarb_html::HtmlAdapter;
#[cfg(feature = "adapters")]
use quarb_json::JsonAdapter;
#[cfg(feature = "kuzu")]
#[cfg(feature = "adapters")]
use quarb_kuzu::KuzuAdapter;
#[cfg(feature = "adapters")]
use quarb_mount::{Latent, Mount, MountAdapter};
#[cfg(feature = "adapters")]
use quarb_mysql::MysqlAdapter;
#[cfg(feature = "adapters")]
use quarb_open::*;
#[cfg(feature = "adapters")]
pub use quarb_open::{Mounted, OpenOpts, SourceCtx, open_target, split_database_url};
#[cfg(feature = "adapters")]
use quarb_oracle::OracleAdapter;
#[cfg(feature = "adapters")]
use quarb_postgres::PostgresAdapter;
#[cfg(feature = "adapters")]
use quarb_sqlite::SqliteAdapter;
#[cfg(feature = "adapters")]
use quarb_xml::XmlAdapter;
#[cfg(feature = "adapters")]
use std::io::IsTerminal;
use std::path::{Path, PathBuf};
#[cfg(feature = "adapters")]
use std::rc::Rc;

/// Query a filesystem tree, a JSON, XML, HTML, or CSV document.
#[derive(Parser, Default)]
#[command(
    version,
    about,
    after_help = "The manual: `man` as the first argument lists the commands, `man NAME` prints a \
                  command's page, `man '<=>'` a glyph's (a pipe, a sigil, an operator), `man syntax \
                  [KIND]` lists the glyphs; `--ru` for Russian."
)]
struct Cli {
    /// Quarb query, e.g. '//*.rs', '/users/*/name::', or '//a::href'.
    query: String,

    /// Directories (filesystem) and/or `.json`/`.xml`/`.html`/`.csv`
    /// files. One argument queries it directly; several are mounted
    /// as named children of one root (file stem = mount name), so a
    /// single query — including a `<=>` join — spans them all.
    /// `NAME=TARGET` picks the mount name explicitly (`ga=events.json`
    /// mounts as `/ga`) — the way to a clean name when the target is
    /// a URL with a query string. If omitted, reads one document
    /// from stdin.
    paths: Vec<PathBuf>,

    /// The mounts a `--model` file states, by the input each was
    /// injected as: the name as the statement gives it. A mount
    /// name is an identifier, which admits a dot (`mount
    /// library.json: …`); the command line's `NAME=TARGET` reading
    /// is narrower, so that `a=b.json` can be a file, and must not
    /// read a statement's name back.
    #[arg(skip)]
    stated: std::collections::HashMap<PathBuf, (String, PathBuf)>,

    /// The calculator's: one thread per line of the input, the line
    /// as its topic (`seq 5 | qc -l '$_ * 2'`); sugar for
    /// `$_ | lines |` at the head.
    #[arg(short = 'l', long = "lines", hide = true)]
    lines: bool,

    /// Mount the subtree at PATH as the tree (`?root=PATH` on the
    /// one source): paths print relative to it, `//` sweeps it, and
    /// what lies above or beside it is not mounted at all.
    #[arg(long, value_name = "PATH")]
    root: Option<String>,

    /// Include hidden entries (filesystem only).
    #[arg(long)]
    hidden: bool,

    /// Do not respect `.gitignore` / `.ignore` (filesystem only).
    #[arg(long = "no-ignore")]
    no_ignore: bool,

    /// Interpret the query as XPath 1.0 and translate it to Quarb
    /// before running (semantic notes go to stderr).
    #[arg(long)]
    xpath: bool,

    /// Interpret the query as a jq filter and translate it to Quarb
    /// before running (semantic notes go to stderr).
    #[arg(long, conflicts_with = "xpath")]
    jq: bool,

    /// Interpret the query as a SQL SELECT statement and translate
    /// it to Quarb before running (semantic notes go to stderr).
    #[arg(long, conflicts_with_all = ["xpath", "jq"])]
    sql: bool,

    /// With --jq, --xpath or --sql: translate a construct that has
    /// no exact Quarb counterpart to the nearest one, and warn of
    /// each place the answer can differ from the source language's
    /// (LENIENT_TRANSLATION). Without it such a construct is
    /// refused, and the refusal names this flag. The lenient forms
    /// today: in jq, sort_by, min_by, max_by, unique_by, and
    /// group_by(KEY) | map(length); in XPath, a relative path (read
    /// from the document root) and node() (the elements). A query
    /// that needs no leniency translates as it does without the
    /// flag.
    #[arg(long)]
    lenient: bool,

    /// Emit results as canonical kaiv: one typed leaf per value
    /// under /@results/N, with provenance recording the source
    /// document and each value's origin node.
    #[arg(long)]
    kaiv: bool,

    /// The notation of the document on standard input, which is
    /// read as JSON by default and never sniffed: one of json jsonl
    /// yaml toml xml html markdown text csv tsv fb2 conllu kaiv quarb,
    /// an atrep extension (atd atk usfm), or a source grammar's name
    /// (rust, python, …). The flags --yaml --toml --xml --html
    /// --markdown --text --fb2 name the common ones directly.
    #[arg(long = "format", value_name = "NOTATION")]
    stdin_format: Option<String>,
    #[arg(long = "yaml", conflicts_with = "stdin_format")]
    in_yaml: bool,
    #[arg(long = "toml", conflicts_with = "stdin_format")]
    in_toml: bool,
    #[arg(long = "xml", conflicts_with = "stdin_format")]
    in_xml: bool,
    #[arg(long = "html", conflicts_with = "stdin_format")]
    in_html: bool,
    #[arg(long = "markdown", conflicts_with = "stdin_format")]
    in_markdown: bool,
    #[arg(long = "text", conflicts_with = "stdin_format")]
    in_text: bool,
    #[arg(long = "fb2", conflicts_with = "stdin_format")]
    in_fb2: bool,

    /// With --kaiv: how many origins a value's provenance lists by
    /// name before the rest collapse into the elision marker
    /// (`;+N`). A sum over a thousand rows names 8 and says +992.
    #[arg(long, value_name = "N", default_value_t = 8, requires = "kaiv")]
    kaiv_origins: usize,

    /// Reproducible provenance: answer and export only the instants
    /// the data itself recorded, holding back a source's
    /// modification time and the moment of reading, so the same
    /// source gives the same output run after run.
    #[arg(long)]
    reproducible: bool,

    /// Print the results as one JSON document — an array of the
    /// values, records as objects. (The default prints the Quarb
    /// form: `%(k = v; …)` for a record, `@(a; b)` for a list.)
    #[arg(long, conflicts_with_all = ["jsonl", "kaiv"])]
    json: bool,

    /// Print the results as JSON Lines: one JSON document per line.
    #[arg(long, conflicts_with_all = ["json", "kaiv"])]
    jsonl: bool,

    /// Print the results as an aligned text table: each record a
    /// row, its fields the columns (the union of the records'
    /// fields, in first-seen order), scalars a `value` column;
    /// widths count grapheme clusters, so stressed words align.
    #[arg(long = "pretty", conflicts_with_all = ["json", "jsonl", "kaiv", "csv"])]
    table: bool,

    /// Retired: the aligned text table is `--pretty` (an alias
    /// through 0.37; refused with the pointer since).
    #[arg(long = "table", hide = true)]
    retired_table: bool,

    /// Print the results as CSV (RFC 4180), a header row first; the
    /// same columns as --pretty.
    #[arg(long, conflicts_with_all = ["json", "jsonl", "kaiv", "table"])]
    csv: bool,

    /// Load fragment definitions (`def &name(params): body;`) from a
    /// file before parsing the query; inline defs extend them.
    #[arg(long, value_name = "FILE")]
    defs: Option<PathBuf>,

    /// Expand the query's fragments and print the resulting
    /// canonical query text instead of running it (macroexpand).
    #[arg(long)]
    expand: bool,

    /// Expand each directly-invoked macro ONE step and print its
    /// generated text before re-expansion, one line per invocation
    /// (macroexpand-1); run the printed text again to take the
    /// next step, --expand for the fixed point.
    #[arg(long = "expand-1", conflicts_with = "expand")]
    expand_1: bool,

    /// Disable SQL pushdown for database inputs (always evaluate
    /// through the adapter's scan path).
    #[arg(long = "no-pushdown")]
    no_pushdown: bool,
    /// Mount a file whole instead of streaming it. A one-off query
    /// streams a CSV or TSV file (a row parsed when a cell of it is
    /// read), and a JSON, JSON lines or XML file of 128 MiB and more
    /// (an element parsed when a step reaches it); a query that
    /// walks the rows or the elements many times may prefer the file
    /// held.
    #[arg(long = "no-stream", conflicts_with = "stream")]
    no_stream: bool,
    /// Stream a JSON, JSON lines or XML file whatever its size (they
    /// stream from 128 MiB by themselves): the file is not held, an
    /// element is parsed when a step reaches it. It costs little
    /// memory, answers a count or a slice at once, and is slower
    /// than the whole read for a query that reads into the elements.
    #[arg(long = "stream")]
    stream: bool,

    /// The diagnostics shown on stderr beside a query's answer:
    /// error (the refusals and syntax errors alone), warning (the
    /// default), info (every note the run raised: what was pushed
    /// to a source, what was delegated, the locale in force), or
    /// debug (what the evaluation did on the way, round by round).
    /// The level changes what is shown, never what is raised. Beside
    /// the specification's codes the tool raises two of its own:
    /// UNRESOLVED (an external reference the run left unresolved)
    /// and READING (a reading a mount declined), both infos.
    #[arg(long, value_name = "LEVEL", default_value = "warning")]
    diagnostics: String,

    /// `--diagnostics=info`, shorter: the infos too (the pushdown's
    /// account, what was delegated, the locale in force).
    #[arg(long, conflicts_with_all = ["diagnostics", "debug"])]
    info: bool,

    /// `--diagnostics=debug`, shorter: everything the evaluation
    /// raised, round by round.
    #[arg(long, conflicts_with = "diagnostics")]
    debug: bool,

    /// Colour on stderr: the severity word of a diagnostic (error
    /// red, warning yellow, info green, debug blue) and the `Error` of
    /// a refusal. `auto` (the default) colours only when stderr is a
    /// terminal, NO_COLOR is unset and TERM is not dumb; `always`
    /// and `never` decide outright. The text itself never changes,
    /// so a captured stderr reads the same whatever the colour.
    #[arg(long, value_name = "WHEN", default_value = "auto")]
    color: ColorMode,

    /// Print the static plan (what the query will touch, step by
    /// step, with each adapter's estimate) as a kaiv document and
    /// stop, running nothing.
    #[arg(long)]
    plan: bool,

    /// Hold the run to a budget, refusing before running when the
    /// plan's estimate exceeds it: `nodes=N`, `bytes=N`,
    /// `requests=N`, comma-separated, and `strict` to refuse an
    /// unknown estimate too.
    #[arg(long, value_name = "BOUNDS")]
    budget: Option<String>,

    /// The output locale: how results are rendered (the decimal
    /// mark and grouping of numbers, the form of instants, csv's
    /// delimiter, sort's collation), never what they are. Layers,
    /// nearest wins: this flag, QUARB_LOCALE, ~/.quarb/config.toml
    /// ([output] locale = "…"), the system locale (LC_ALL, LANG),
    /// else the canonical form (C). A tag no table covers is
    /// reported and renders canonically.
    #[arg(long, value_name = "TAG")]
    locale: Option<String>,

    /// Group digits as the output locale does (1 234 567,5). Off by
    /// default: a locale sets the decimal mark, and a year or an id
    /// prints as written. Also QUARB_GROUPING=1, or `grouping =
    /// true` under [output] in the config file.
    #[arg(long)]
    grouping: bool,

    /// Hidden: read query lines on stdin and write each back as
    /// syntax-highlighted HTML (the playground's span classes) —
    /// the hook documentation builds use to color transcripts.
    #[arg(long = "highlight-html", hide = true)]
    highlight_html: bool,

    /// Save the result instead of printing it: `.json` writes a
    /// JSON array, any other extension a SQLite table (each record
    /// a row, its fields the columns) — both first-class inputs for
    /// later queries.
    #[arg(long, value_name = "FILE")]
    save: Option<PathBuf>,

    /// The table name for --save into SQLite (default: result).
    #[arg(long = "as", value_name = "NAME", default_value = "result")]
    save_as: String,

    /// Opt a directory mount into grafting (composition): a
    /// parseable leaf's — .json/.xml/.html/.csv/source — parsed
    /// tree becomes its children. Archives, buckets, and text
    /// columns graft by default.
    #[arg(long)]
    graft: bool,

    /// Disable grafting entirely: no boundary is crossed —
    /// archive members, bucket objects, and JSON text columns
    /// stay opaque leaves, so listings agree with find/tar and
    /// the server's own column types. Refused with the code:
    /// prefix, whose meaning is the grafted view.
    // A future parameterized form (--graft=MOUNT,
    // --no-graft=PATTERN) narrows these; the bare spellings keep
    // meaning all-mounts / all-boundaries. The conflict below
    // then relaxes to "both bare".
    #[arg(long = "no-graft", conflicts_with = "graft")]
    no_graft: bool,

    /// A declared-references document: '{"refs": {"field":
    /// "container", ...}}' — the edges the substrate's own catalog
    /// does not hold. On a SQLite database each declared property gains
    /// the full crosslink fabric ('-->', '->', '<-', '<--') into the
    /// target container (a table, or a view — e.g. a SELECT DISTINCT
    /// dimension view); a property may be scoped as 'table.column'. On
    /// Firebase, bare '-->' and '->' work for the declared properties.
    #[arg(long, value_name = "FILE")]
    refs: Option<PathBuf>,

    /// A model file declaring derived arbor structure over the
    /// source(s): 'node /ips/ip: query;' derives a container whose
    /// children play the role 'ip', 'ref /path/*::f --> C;' a scoped
    /// reference, 'rel A -> B[cond];' a relation no value carries,
    /// 'edge /path/*: ::a -- ::b;' pair edges, 'mount NAME: t;' a
    /// source the model opens itself. Every step is named for the role
    /// it lands on. The graph the data only implies, made navigable —
    /// over any adapter.
    #[arg(long, value_name = "FILE")]
    model: Option<PathBuf>,
    /// Sentence bonds: a .desm file (repeatable) — abbreviations a
    /// sentence may end in without ending, and /regex/ lines whose
    /// match straddles a UAX #29 break — loaded for the session, so
    /// the corpus: reading, `sentences` and `sc` agree on "Dr.
    /// Smith". `corpus:x?desm=FILE` adds one for a single mount
    #[arg(long, value_name = "FILE")]
    desm: Vec<PathBuf>,

    /// Override the quantifier bound N_max: the depth to which the
    /// open-ended path quantifiers (+, *, {m,}) expand, and the
    /// ceiling of any explicit {m,n}. Default: adapter-provided
    /// (typically 32).
    #[arg(long, value_name = "N")]
    quantifier_bound: Option<usize>,

    /// Override the frontier bound: the most expansion paths one
    /// round of a quantified walk may hold in flight (a walk that
    /// pushes or marks keeps one path per route). Default: 100000.
    #[arg(long, value_name = "N")]
    frontier_bound: Option<usize>,

    /// Override the graph bound: the most cost units a graph library
    /// command may compute over, a node or an edge of the induced
    /// subgraph each (their product for betweenness). Default:
    /// 10000000.
    #[arg(long, value_name = "N")]
    graph_bound: Option<usize>,

    /// Retired: the shell joins a query only as an environment
    /// mount, `sh=shell:` among the inputs, its programs the
    /// commands `sh:tr(a-z; A-Z)`; the switch refuses, naming it.
    #[arg(long, hide = true)]
    allow_shell: bool,

    /// Pin the invocation instant now() denotes (ISO-8601, e.g.
    /// '2026-07-12T09:00:00Z'). Default: the clock, read once at
    /// startup — evaluation itself never reads a clock, so a
    /// pinned run replays exactly.
    #[arg(long, value_name = "ISO")]
    now: Option<String>,

    /// Pin the seed of the session's random values (`rnd`, `sample`,
    /// `shuffle`): a whole number from 0. A run with a seed answers
    /// the same on every machine and in every release, so a pinned
    /// run replays exactly; a `session(--seed=n)` in the query moves
    /// it. Default: a seed drawn at startup, which the run names in
    /// an info (--info) so that it can be repeated.
    #[arg(long, value_name = "N")]
    seed: Option<u64>,

    /// Resident session: reuse (or start) a background qua that
    /// keeps the materialized inputs alive, so repeated queries
    /// skip the parse. The first query pays materialization; later
    /// ones answer from the standing arbor. Sessions are keyed by
    /// the canonical target set plus the semantics-affecting flags,
    /// and exit after --resident-ttl idle seconds. The session
    /// serves the inputs as they were when it started: edits to
    /// the files (or to --refs/--defs content) are not seen until
    /// the session expires or is killed. A git repository is the
    /// exception: the session looks at its refs before each query
    /// and answers the repository as it stands (a new commit, a
    /// moved branch, a new tag); what it has read of the commits
    /// themselves it keeps.
    #[arg(long)]
    resident: bool,

    /// Idle seconds before a resident session exits. Fixed when
    /// the session starts; later clients of the same session
    /// inherit it (as they do --diagnostics and the other flags the
    /// session was started with).
    #[arg(long, value_name = "SECS", default_value_t = 1800)]
    resident_ttl: u64,

    /// Internal: serve a resident session (spawned by --resident).
    #[arg(long, hide = true)]
    resident_serve: bool,

    /// Print the query with ANSI syntax highlighting and exit — the
    /// terminal counterpart of the JupyterLab highlighter, coloring
    /// paths, sigils, operators, strings, numbers, and stdlib
    /// keywords. Honors NO_COLOR; forces color even off a TTY (so a
    /// pipe into `less -R` works).
    #[arg(long)]
    highlight: bool,

    /// Cache parsed syntax trees for code inputs (.rs/.py/.js/.c…):
    /// the first query over a file parses and caches its AST; later
    /// queries load it and skip the parse. Content-addressed under
    /// ~/.quarb/cache (override with --cache-dir or $QUARB_CACHE_DIR;
    /// remove that directory to clear it). A stale or corrupt entry
    /// is silently ignored and reparsed, so the cache can never
    /// change a result.
    #[arg(long)]
    cache: bool,

    /// The AST cache directory (implies --cache). Default:
    /// $QUARB_CACHE_DIR, else ~/.quarb/cache.
    #[arg(long, value_name = "DIR")]
    cache_dir: Option<PathBuf>,
}

/// How a result line is written: the Quarb form by
/// default, JSON on request.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Output {
    Quarb,
    Json,
    Jsonl,
    Table,
    Csv,
}

/// Everything that shapes how a query's result comes out, decided
/// once from the command line and carried to the run chain — no
/// thread-local, so a resident session can build one per query (the
/// output command is each query's own; the instant too unless --now
/// pinned it) and nothing of one query leaks into the next.
#[derive(Clone)]
struct OutputCtx {
    /// The --json / --jsonl / --table / --csv choice.
    output: Output,
    /// --expand / --expand-1 with a target: print the expansion.
    expand: bool,
    expand_1: bool,
    /// --kaiv-origins: the bound on named origins per kaiv leaf.
    kaiv_origins: usize,
    /// --save: (file, table name).
    save: Option<(PathBuf, String)>,
    /// --quantifier-bound.
    quant_bound: Option<usize>,
    /// --frontier-bound.
    front_bound: Option<usize>,
    graph_bound: Option<usize>,
    allow_shell: bool,
    /// The session memory (`| ,name`, `$,name`, `%,`): for a one-shot
    /// run the run itself, for the REPL the whole session.
    session: quarb::SessionMemory,
    /// The environments mounted from the command line
    /// (`go=exec:~/go/bin`, `sh=shell:`, `py=python:./helpers.py`).
    environments: Vec<quarb::Environment>,
    /// The command libraries this build links (`morph:` under the
    /// `morph` feature), reached by their prefix with no mount, and
    /// the Python modules mounted as environments, bound as
    /// libraries under their aliases.
    libraries: Vec<std::sync::Arc<dyn quarb::CommandLibrary>>,
    /// --reproducible: provenance without the machine-dependent
    /// instant rungs.
    reproducible: bool,
    /// The invocation instant now() denotes: --now, or the clock
    /// read once at startup (per query in an unpinned resident
    /// session), so evaluation never reads a clock.
    now: (i64, u32),
    /// --plan: print the static plan and stop.
    plan: bool,
    /// The calculator's input: its pipe, read as one text, the topic
    /// the expression head's thread opens with (`None` at a terminal).
    /// The calculator profile: the run goes through the engine's
    /// calculator entry, no arbor.
    calc: bool,
    topic: Option<Value>,
    /// --budget, parsed.
    budget: Option<quarb::plan::Budget>,
    /// The --model file, parsed.
    #[cfg(feature = "adapters")]
    model: Option<quarb_model::Model>,
    /// The output locale in force, with the layer that set it.
    locale: Option<(quarb::locale::OutputLocale, &'static str)>,
    /// Resident-serve mode: the socket, the idle TTL, and whether
    /// --now pinned the instant.
    #[cfg(feature = "adapters")]
    resident: Option<(PathBuf, u64, bool)>,
    /// `@| encoding(LABEL)` taken off the end of the query.
    encoding: Option<(String, quarb::source::Escape)>,
    /// `| copy` taken off the end of the query (spec: The
    /// clipboard): the output goes to the clipboard instead of the
    /// screen, this its rendering's name for the diagnostic.
    copy: Option<&'static str>,
}

/// Split a scheme-prefixed query (`github:/torvalds/…`) into
/// its target scheme and the root-anchored query. Only schemes
/// whose bare form is a complete target qualify — schemes that
/// carry a payload (`git:PATH`, `mongodb://HOST/DB`) keep the
/// two-argument form, where the split would be ambiguous.
#[cfg(feature = "adapters")]
fn split_scheme_query(q: &str) -> Option<(&'static str, &str)> {
    for scheme in ["github:", "gitlab:", "k8s:", "kubernetes:"] {
        if let Some(rest) = q.strip_prefix(scheme)
            && rest.starts_with('/')
        {
            return Some((scheme, rest));
        }
    }
    None
}

#[cfg(feature = "adapters")]
impl From<&Cli> for OpenOpts {
    fn from(cli: &Cli) -> Self {
        OpenOpts {
            hidden: cli.hidden,
            no_ignore: cli.no_ignore,
            graft: cli.graft,
            no_graft: cli.no_graft,
            refs: cli.refs.clone(),
            allow_shell: cli.allow_shell,
            // the one-off query streams a CSV (ruling 2026-11-05);
            // a run that keeps the arbor — the kaiv emission, a save,
            // a resident server — mounts it whole
            stream_rows: !cli.no_stream
                && !cli.kaiv
                && cli.save.is_none()
                && !cli.resident
                && !cli.resident_serve,
            // a document of elements streams from a size, or where
            // `--stream` asks (the user's ruling, 2026-11-12); never
            // in a run that keeps the arbor
            stream_documents: if cli.no_stream
                || cli.kaiv
                || cli.save.is_some()
                || cli.resident
                || cli.resident_serve
            {
                None
            } else if cli.stream {
                Some(0)
            } else {
                Some(quarb_open::STREAM_DOCUMENTS_FROM)
            },
        }
    }
}

/// Whether a target is written with a reader prefix or an adapter
/// scheme (`text:…`, `imap://…`, `neo4j://…`) rather than as a
/// path; a one-letter prefix is a Windows drive, a path.
#[cfg(feature = "adapters")]
fn is_prefixed_target(s: &str) -> bool {
    s.split_once(':').is_some_and(|(pre, _)| {
        pre.len() > 1
            && pre
                .chars()
                .all(|c| c.is_ascii_alphanumeric() || "+.-".contains(c))
    })
}

/// The relational targets the single flow keeps typed, for pushdown.
#[cfg(feature = "adapters")]
fn is_relational_target(s: &str) -> bool {
    s.starts_with("mssql://")
        || s.starts_with("oracle://")
        || s.starts_with("bigquery://")
        || s.starts_with("athena:")
        || s.starts_with("mysql://")
        || is_pg_config(s)
}

/// The complete CLI entry point (the `qua` binary is a thin
/// shim over this; the `quarb-full` wheel ships it as
/// `qua-full`).
/// Which command runs: `qua`, with every source it can open, or
/// `qc`, the calculator — the same code, the adapters compiled out
/// and a query that would need one refused by name.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Profile {
    Qua,
    Calc,
}

/// `qua`'s entry point.
pub fn cli_main() -> anyhow::Result<()> {
    let r = cli_main_with(Profile::Qua);
    #[cfg(feature = "alloc-stats")]
    alloc_stats::report();
    report_top_error(r)
}

/// The refusal that ends a run, on stderr as the runtime would print
/// it (`Error: …`, the causes under it), the word painted when
/// colour is on; the exit status stays 1.
fn report_top_error(r: anyhow::Result<()>) -> anyhow::Result<()> {
    let Err(e) = r else {
        return Ok(());
    };
    let (pre, post) = paint(quarb::Severity::Error);
    match e.downcast_ref::<Told>() {
        // a refusal with a code is its diagnostic's own line
        Some(Told(line)) => {
            let rest = line.strip_prefix("error").unwrap_or(line);
            eprintln!("{pre}error{post}{rest}");
        }
        None => eprintln!("{pre}Error{post}: {e:?}"),
    }
    std::process::exit(1)
}

/// A refusal that ends the run and is told as a diagnostic's line,
/// code and site and the door to its remedy, in place of the bare
/// `Error: …`: a translator's refusal of a construct it has a word
/// for (`error SORT_NOT_TRANSLATED (jq): … Or pass --lenient: qua
/// man SORT_NOT_TRANSLATED`; ruling 2026-11-17).
#[derive(Debug)]
struct Told(String);

impl std::fmt::Display for Told {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.0)
    }
}

impl std::error::Error for Told {}

/// A translator's error as the run's refusal: its one line where it
/// has a word (`worded`: the code, the reason, whether the lenient
/// translator takes the construct), else the error under the
/// bridge's name.
fn translator_error<E>(
    bridge: &'static str,
    worded: Option<(&'static str, String, bool)>,
    lenient: bool,
    e: E,
) -> anyhow::Error
where
    E: std::error::Error + Send + Sync + 'static,
{
    let line = worded.map(|(code, reason, takes)| {
        quarb::diagnostic::translator_refusal(bridge, code, &reason, takes, lenient)
    });
    match line {
        Some(line) => anyhow::Error::new(Told(line)),
        None => anyhow::Error::new(e).context(match bridge {
            "xpath" => "translating XPath",
            "jq" => "translating jq",
            _ => "translating SQL",
        }),
    }
}

/// `qc`'s entry point: the calculator. The query runs as `qua` runs
/// it after the expression head `=`; the `=` is accepted and not
/// required, and anything that needs an input, a mount or a path
/// from a node is refused, pointing at `qua`.
pub fn calc_main() -> anyhow::Result<()> {
    let r = cli_main_with(Profile::Calc);
    #[cfg(feature = "alloc-stats")]
    alloc_stats::report();
    report_top_error(r)
}

/// `--color=auto|always|never`, qua's and quai's alike.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, clap::ValueEnum)]
pub enum ColorMode {
    #[default]
    Auto,
    Always,
    Never,
}

/// Colour on one output stream, decided once: the severity word of
/// a diagnostic (error bold red, warning yellow, info green, debug
/// blue) and the `error` of a refusal, and nothing else, so a
/// captured stream reads the same text whatever a terminal would
/// have shown. The tools share it: qua paints stderr, quai its
/// stdout (where its diagnostics go) and its stderr.
#[derive(Debug, Clone, Copy)]
pub struct Paint {
    on: bool,
}

impl Paint {
    /// The decision for a stream: `always` and `never` outright;
    /// `auto` paints only when the stream is a terminal, `NO_COLOR`
    /// is unset (no-color.org) and `TERM` is set and not `dumb`.
    pub fn decide(mode: ColorMode, stream_is_terminal: bool) -> Paint {
        let on = match mode {
            ColorMode::Always => true,
            ColorMode::Never => false,
            ColorMode::Auto => {
                stream_is_terminal
                    && std::env::var_os("NO_COLOR").is_none()
                    && std::env::var_os("TERM").is_some_and(|t| t != "dumb")
            }
        };
        Paint { on }
    }

    /// The escape sequences around a severity word, empty when
    /// colour is off.
    pub fn word(&self, severity: quarb::Severity) -> (&'static str, &'static str) {
        if !self.on {
            return ("", "");
        }
        let pre = match severity {
            quarb::Severity::Error => "\x1b[1;31m",
            quarb::Severity::Warning => "\x1b[33m",
            quarb::Severity::Info => "\x1b[32m",
            quarb::Severity::Debug => "\x1b[34m",
        };
        (pre, "\x1b[0m")
    }

    /// A diagnostic's line (`severity CODE (site): message`, and
    /// the tail of a code that has a remedy), the severity word
    /// alone painted.
    pub fn line(&self, d: &quarb::Diagnostic) -> String {
        let (pre, post) = self.word(d.severity);
        let line = d.line();
        // the line opens with the severity word
        let word = d.severity.word();
        format!("{pre}{word}{post}{}", &line[word.len()..])
    }

    /// The word `text` painted as an error (the `Error` of a
    /// refusal).
    pub fn error_word(&self, text: &str) -> String {
        let (pre, post) = self.word(quarb::Severity::Error);
        format!("{pre}{text}{post}")
    }
}

/// qua's stderr paint, decided once from `--color`; before the flag
/// is read (a usage error) the automatic rule holds.
static STDERR_PAINT: std::sync::OnceLock<Paint> = std::sync::OnceLock::new();

fn set_color(mode: ColorMode) {
    use std::io::IsTerminal;
    let _ = STDERR_PAINT.set(Paint::decide(mode, std::io::stderr().is_terminal()));
}

fn stderr_paint() -> Paint {
    use std::io::IsTerminal;
    *STDERR_PAINT.get_or_init(|| Paint::decide(ColorMode::Auto, std::io::stderr().is_terminal()))
}

fn paint(severity: quarb::Severity) -> (&'static str, &'static str) {
    stderr_paint().word(severity)
}

fn painted_line(d: &quarb::Diagnostic) -> String {
    stderr_paint().line(d)
}

/// The benchmark harness's allocation counter (feature
/// `alloc-stats`, never on in a shipped binary): a global allocator
/// that counts every allocation and reallocation, the bytes they
/// requested, and the peak heap in use, and reports the three on
/// stderr at exit. Relaxed atomics: the counts are totals, not an
/// ordering, and a thread's increments need no synchronization
/// with another's.
#[cfg(feature = "alloc-stats")]
mod alloc_stats {
    use std::alloc::{GlobalAlloc, Layout, System};
    use std::sync::atomic::{AtomicU64, Ordering::Relaxed};

    static COUNT: AtomicU64 = AtomicU64::new(0);
    static BYTES: AtomicU64 = AtomicU64::new(0);
    static LIVE: AtomicU64 = AtomicU64::new(0);
    static PEAK: AtomicU64 = AtomicU64::new(0);

    struct Counting;

    fn note(size: usize) {
        COUNT.fetch_add(1, Relaxed);
        BYTES.fetch_add(size as u64, Relaxed);
        let live = LIVE.fetch_add(size as u64, Relaxed) + size as u64;
        PEAK.fetch_max(live, Relaxed);
    }

    unsafe impl GlobalAlloc for Counting {
        unsafe fn alloc(&self, l: Layout) -> *mut u8 {
            note(l.size());
            unsafe { System.alloc(l) }
        }
        unsafe fn alloc_zeroed(&self, l: Layout) -> *mut u8 {
            note(l.size());
            unsafe { System.alloc_zeroed(l) }
        }
        unsafe fn dealloc(&self, p: *mut u8, l: Layout) {
            LIVE.fetch_sub(l.size() as u64, Relaxed);
            unsafe { System.dealloc(p, l) }
        }
        unsafe fn realloc(&self, p: *mut u8, l: Layout, new_size: usize) -> *mut u8 {
            LIVE.fetch_sub(l.size() as u64, Relaxed);
            note(new_size);
            unsafe { System.realloc(p, l, new_size) }
        }
    }

    #[global_allocator]
    static COUNTING: Counting = Counting;

    pub fn report() {
        eprintln!(
            "alloc-stats: allocations {} bytes {} peak-heap {}",
            COUNT.load(Relaxed),
            BYTES.load(Relaxed),
            PEAK.load(Relaxed)
        );
    }
}

fn cli_main_with(profile: Profile) -> anyhow::Result<()> {
    // Restore the default SIGPIPE disposition. Rust ignores
    // SIGPIPE at startup, which turns a closed downstream pipe
    // (`qua ... | head`) into a panic on the next write; a Unix
    // filter should instead die quietly by the signal.
    #[cfg(unix)]
    unsafe {
        libc::signal(libc::SIGPIPE, libc::SIG_DFL);
    }

    // A query engine never fetches over the network by surprise:
    // kaiv `.!units` / `.!types` registry imports resolve from the
    // frozen built-in set, local `.!registry` bases, or the warm
    // kaiv cache — not f.kaiv.io. `KAIV_OFFLINE=0` re-enables the
    // fetch explicitly (single-threaded here, so set_var is safe).
    if std::env::var_os("KAIV_OFFLINE").is_none() {
        unsafe {
            std::env::set_var("KAIV_OFFLINE", "1");
        }
    }

    // A refused query is a message, not a crash: under
    // `RUST_BACKTRACE=1` every error captured a stack and the
    // refusal printed it after its causes. The variable keeps its
    // meaning for a panic; the stack of an error is asked for by
    // its own name, `RUST_LIB_BACKTRACE=1` (single-threaded here,
    // and before the first error is made).
    if std::env::var_os("RUST_LIB_BACKTRACE").is_none() {
        unsafe {
            std::env::set_var("RUST_LIB_BACKTRACE", "0");
        }
    }

    // `qua man [--ru] [NAME | GLYPH | syntax]` and `qc man`: the command
    // inventory, before the query grammar sees the words (`man` is
    // reserved as a first argument); `--commands` lists the
    // registry as TSV for the documentation gate.
    let argv: Vec<String> = std::env::args().collect();
    match argv.get(1).map(String::as_str) {
        Some("man") => {
            let args: Vec<&str> = argv[2..].iter().map(String::as_str).collect();
            return match quarb::man::man(&args) {
                Ok(text) => {
                    println!("{text}");
                    Ok(())
                }
                Err(e) => Err(anyhow::anyhow!("{e}")),
            };
        }
        Some("--commands") => {
            print!("{}", quarb::man::registry_tsv());
            return Ok(());
        }
        _ => {}
    }
    let mut cli = match profile {
        Profile::Qua => Cli::parse(),
        // The calculator's help names it, and says what it is.
        Profile::Calc => {
            use clap::{CommandFactory, FromArgMatches};
            let cmd = Cli::command()
                .name("qc")
                .about("The Quarb calculator: qua after the expression head, with every adapter off")
                .override_usage("qc [OPTIONS] <EXPRESSION>...")
                // The calculator takes no input, so every positional
                // argument is expression text: the words are joined
                // with spaces, and `qc 3 + 5` needs no quotes. A
                // leading negative number is a value, not an option.
                .mut_arg("query", |a| {
                    a.value_name("EXPRESSION")
                        .allow_negative_numbers(true)
                        .help("The expression, e.g. '2 + 3 * 4' or '@(1; 2) ++ 3'; the head `=` is accepted and not required")
                })
                .mut_arg("paths", |a| {
                    a.value_name("WORD")
                        .allow_negative_numbers(true)
                        .help("The rest of the expression: the arguments are joined with spaces, so quotes are needed only around what the shell would take (| * ; ( ) $ \")")
                })
                .mut_arg("lines", |a| a.hide(false));
            Cli::from_arg_matches(&cmd.get_matches())?
        }
    };
    // Environment mounts (`ALIAS=SCHEME:TARGET` with an environment
    // scheme) are taken off the inputs here, from the command line
    // only: mounting one is the opt-in that lets `ALIAS:name(…)`
    // run code outside the query.
    if cli.retired_table {
        anyhow::bail!("'--table' is retired: the aligned text table is '--pretty'");
    }
    let (environments, mounted) = take_environments(&mut cli)?;
    let locale = set_output_locale(&cli)?;
    let mut piped = if profile == Profile::Calc {
        calc_check_options(&mut cli)?
    } else {
        None
    };
    let output = if cli.json {
        Output::Json
    } else if cli.jsonl {
        Output::Jsonl
    } else if cli.table {
        Output::Table
    } else if cli.csv {
        Output::Csv
    } else {
        Output::Quarb
    };

    // The highlight filter: no query, no target — a pure lexer
    // pass, line in, HTML line out.
    if cli.highlight_html {
        use std::io::BufRead;
        for line in std::io::stdin().lock().lines() {
            println!("{}", quarb::highlight::highlight_html(&line?));
        }
        return Ok(());
    }

    // A target may ride the query as a scheme prefix —
    // `qua 'github:/torvalds/linux::stars'` is
    // `qua '/torvalds/linux::stars' github:`. Recognized for
    // targets whose bare scheme is a complete target; the first
    // `/` begins the root-anchored query. The two-argument form
    // stays supported.
    #[cfg(feature = "adapters")]
    if cli.paths.is_empty()
        && let Some((scheme, query)) = split_scheme_query(&cli.query)
    {
        cli.paths.push(PathBuf::from(scheme));
        cli.query = query.to_string();
    }

    // `--lenient` is the translators' switch (the ruling of
    // 2026-11-17): alone it has nothing to be lenient about.
    if cli.lenient && !(cli.xpath || cli.jq || cli.sql) {
        anyhow::bail!(
            "--lenient goes with a translator (--jq, --xpath or --sql): it lets the \
             translation take the nearest Quarb construct where there is no exact one, \
             and warns of the difference"
        );
    }
    #[cfg(feature = "adapters")]
    if cli.xpath {
        let translation = if cli.lenient {
            quarb_xpath::translate_lenient(&cli.query)
        } else {
            quarb_xpath::translate(&cli.query)
        }
        .map_err(|e| {
            let worded = e.not_translated().map(|(c, r, t)| (c, r.to_string(), t));
            translator_error("xpath", worded, cli.lenient, e)
        })?;
        for warning in &translation.warnings {
            note_warning(LENIENT_TRANSLATION, "xpath", warning.clone());
        }
        for note in &translation.notes {
            eprintln!("note: {note}");
        }
        cli.query = translation.query;
    }
    #[cfg(feature = "adapters")]
    if cli.jq {
        let translation = if cli.lenient {
            quarb_jq::translate_lenient(&cli.query)
        } else {
            quarb_jq::translate(&cli.query)
        }
        .map_err(|e| {
            let worded = e.not_translated().map(|(c, r, t)| (c, r.to_string(), t));
            translator_error("jq", worded, cli.lenient, e)
        })?;
        // What the lenient translation gave up, one warning each.
        for warning in &translation.warnings {
            note_warning(LENIENT_TRANSLATION, "jq", warning.clone());
        }
        for note in &translation.notes {
            eprintln!("note: {note}");
        }
        cli.query = translation.query;
    }
    #[cfg(feature = "adapters")]
    if cli.sql {
        let translation = quarb_sql::translate(&cli.query).map_err(|e| {
            let worded = e.not_translated().map(|(c, r, t)| (c, r.to_string(), t));
            translator_error("sql", worded, cli.lenient, e)
        })?;
        for note in &translation.notes {
            eprintln!("note: {note}");
        }
        cli.query = translation.query;
    }

    set_color(cli.color);

    if cli.highlight {
        // Explicit --highlight forces color (the query is the
        // deliverable), but NO_COLOR still wins.
        if std::env::var_os("NO_COLOR").is_some() {
            println!("{}", cli.query);
        } else {
            println!("{}", quarb::highlight::highlight_ansi(&cli.query));
        }
        return Ok(());
    }

    // A --defs file holds definitions only; validate it as such,
    // then let its statements precede the query, where inline defs
    // (and duplicate detection) already work. Prepended stripped of
    // `#` comment lines — the query lexer has no comment syntax.
    if let Some(defs_path) = &cli.defs {
        let text = std::fs::read_to_string(defs_path)
            .with_context(|| format!("reading {}", defs_path.display()))?;
        // Strip a leading UTF-8 BOM, as the document readers do.
        let text = text.strip_prefix('\u{feff}').unwrap_or(&text).to_owned();
        quarb::parse_defs(&text)
            .with_context(|| format!("parsing definitions in {}", defs_path.display()))?;
        cli.query = format!("{}\n{}", quarb::strip_defs_comments(&text), cli.query);
    }
    // The calculator reads its query once the definitions are in
    // front of it, so a fragment a --defs file supplies is known.
    if profile == Profile::Calc {
        calc_check_query(&cli)?;
    }

    // --expand: print the fragment-expanded canonical query and
    // stop. Without an input, expansion is pure; with one, the
    // dispatch in `execute` opens it and `run` expands against it,
    // so data-aware macros (&name!) can read the data.
    if cli.expand {
        // (a model brings its own mounts and definitions: its
        // expansion waits until the model is read, below)
        if cli.paths.is_empty() && cli.model.is_none() {
            println!(
                "{}",
                quarb::expand(&cli.query, &quarb::Defs::default())
                    .context("expanding the query")?
            );
            return Ok(());
        }
    }
    // --expand-1: one ledger step, printed and stop (macroexpand-1).
    if cli.expand_1 {
        if cli.paths.is_empty() {
            for t in quarb::expand_first(&cli.query, &quarb::Defs::default())
                .context("expanding the query")?
            {
                println!("{t}");
            }
            return Ok(());
        }
    }

    if let Some(n) = cli.quantifier_bound {
        anyhow::ensure!(n >= 1, "--quantifier-bound must be at least 1");
    }
    if let Some(n) = cli.frontier_bound {
        anyhow::ensure!(n >= 1, "--frontier-bound must be at least 1");
    }
    if let Some(n) = cli.graph_bound {
        anyhow::ensure!(n >= 1, "--graph-bound must be at least 1");
    }
    // Bind the invocation instant: --now pins it; otherwise the
    // clock, read exactly once, here — never during evaluation.
    let now = match &cli.now {
        Some(text) => {
            let (secs, nanos, _) = quarb::temporal::parse_iso(text)
                .ok_or_else(|| anyhow::anyhow!("--now needs an ISO-8601 instant, got '{text}'"))?;
            (secs, nanos)
        }
        None => {
            let since = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap_or_default();
            (since.as_secs() as i64, since.subsec_nanos())
        }
    };
    // Adapters resolving a relative window (`since=30m`) read the
    // same instant, so a mount is as reproducible as the query.
    quarb::set_invocation_instant(now.0, now.1);

    // The session's sentence bonds, from every --desm file.
    #[cfg(feature = "adapters")]
    if !cli.desm.is_empty() {
        let mut bonds = syndesmos::Syndesmos::empty();
        for f in &cli.desm {
            bonds.extend(
                syndesmos::Syndesmos::load(f)
                    .map_err(|e| anyhow::anyhow!("reading {}: {e}", f.display()))?,
            );
        }
        quarb::set_sentence_bonds(Some(Rc::new(bonds)));
    }

    // A --model file declares derived arbor structure; parse it once
    // and `run` wraps every mounted source in the enrichment layer.
    #[cfg(feature = "adapters")]
    let mut parsed_model: Option<quarb_model::Model> = None;
    #[cfg(feature = "adapters")]
    if let Some(model_path) = &cli.model {
        let model = quarb_model::parse_model_file(model_path)
            .map_err(|e| anyhow::anyhow!("parsing model {}: {e}", model_path.display()))?;
        // A model's `mount` statements name sources it opens itself:
        // inject them as `NAME=TARGET` inputs, resolving relative
        // targets against the model file's directory. They lead, so
        // any positional CLI targets merge after (a collision under
        // the multi-mount root is refused there).
        let base_dir = model_path.parent();
        for m in &model.mounts {
            let target = quarb_model::resolve_mount_target(&m.target, base_dir);
            // An environment is mounted from the command line only:
            // a model file mounts sources, never code.
            if quarb::Environment::is_environment_target(&target) {
                anyhow::bail!(
                    "model {}: mount '{}' names an environment ({target}); environments \
                     are mounted from the command line only",
                    model_path.display(),
                    m.name
                );
            }
            let input = PathBuf::from(format!("{}={}", m.name, target));
            cli.stated
                .insert(input.clone(), (m.name.clone(), PathBuf::from(&target)));
            cli.paths.insert(0, input);
        }
        // A model's `def`/`macro` statements are its domain's
        // vocabulary: in scope for the query too, ahead of any
        // --defs file (prepended after it, so they read first).
        if !model.defs_text.trim().is_empty() {
            quarb::parse_defs(&model.defs_text)
                .with_context(|| format!("parsing definitions in {}", model_path.display()))?;
            cli.query = format!("{}\n{}", model.defs_text, cli.query);
        }
        parsed_model = Some(model);
        // --expand with a model that mounts nothing: the pure
        // expansion, now with the model's definitions in scope.
        if cli.expand && cli.paths.is_empty() {
            println!(
                "{}",
                quarb::expand(&cli.query, &quarb::Defs::default())
                    .context("expanding the query")?
            );
            return Ok(());
        }
    }

    // Enable the AST cache before dispatch, so both a normal run and
    // a resident daemon's per-query parses consult it.
    #[cfg(feature = "adapters")]
    if cli.cache || cli.cache_dir.is_some() {
        let dir = cli
            .cache_dir
            .clone()
            .unwrap_or_else(quarb_tree_sitter::Cache::default_dir);
        quarb_tree_sitter::set_cache(Some(quarb_tree_sitter::Cache::new(dir)));
    }

    if cli.resident || cli.resident_serve {
        anyhow::ensure!(
            !cli.kaiv && cli.save.is_none() && !cli.expand && !cli.expand_1,
            "--resident does not combine with --kaiv/--save/--expand"
        );
        anyhow::ensure!(
            !cli.paths.is_empty(),
            "--resident needs file/directory inputs (stdin has no session identity)"
        );
        #[cfg(not(unix))]
        anyhow::bail!("--resident needs Unix domain sockets (unavailable on this platform)");
    }
    #[cfg_attr(not(feature = "adapters"), allow(unused_mut))]
    let mut oc = OutputCtx {
        output,
        expand: cli.expand,
        expand_1: cli.expand_1,
        kaiv_origins: cli.kaiv_origins,
        save: cli.save.as_ref().map(|p| (p.clone(), cli.save_as.clone())),
        quant_bound: cli.quantifier_bound,
        front_bound: cli.frontier_bound,
        graph_bound: cli.graph_bound,
        allow_shell: cli.allow_shell,
        session: {
            // The switch seeds the session's level; `session(…)` in a
            // query may move it.
            let memory = quarb::session_memory();
            let level = if cli.debug {
                quarb::Severity::Debug
            } else if cli.info {
                quarb::Severity::Info
            } else {
                cli.diagnostics
                    .parse::<quarb::Severity>()
                    .map_err(|e| anyhow::anyhow!("--diagnostics: {e}"))?
            };
            memory.borrow_mut().diagnostics = level;
            // --seed pins the seed of the session's random values;
            // `session(--seed=n)` in a query may move it
            memory.borrow_mut().seed = cli.seed;
            // the debug licence: debug notes are raised only when
            // the level asks for them
            DEBUG_NOTES.with(|d| d.set(level == quarb::Severity::Debug));
            memory
        },
        environments: environments.clone(),
        libraries: {
            let mut libraries = linked_libraries();
            libraries.extend(mounted.iter().cloned());
            libraries
        },
        reproducible: cli.reproducible,
        now,
        plan: cli.plan,
        calc: profile == Profile::Calc,
        topic: None,
        budget: cli.budget.as_deref().map(parse_budget).transpose()?,
        #[cfg(feature = "adapters")]
        model: parsed_model,
        locale,
        #[cfg(feature = "adapters")]
        resident: None,
        encoding: None,
        copy: None,
    };
    // The calculator's input: a pipe is read whole, as one text, the
    // topic the expression head's thread opens with; nothing is
    // parsed (a document on a pipe is qua's). At a terminal the
    // topic stays null.
    if profile == Profile::Calc {
        if let Some(text) = piped.take() {
            oc.topic = Some(Value::Str(text));
        }
    } else if cli.lines {
        anyhow::bail!("--lines is the calculator's: pipe the text to qc");
    }
    #[cfg(all(unix, feature = "adapters"))]
    {
        if cli.resident && !cli.resident_serve {
            return resident_client(&cli, &oc);
        }
        if cli.resident_serve {
            let sock = resident_socket(&cli, &oc)?;
            RESIDENT_NOTE.with(|n| *n.borrow_mut() = Some(resident_note(&cli)));
            oc.resident = Some((sock, cli.resident_ttl, cli.now.is_some()));
        }
    }
    if profile == Profile::Calc {
        let r = calc_execute(&cli.query, cli.kaiv, &oc);
        oc.flush_notes();
        return r;
    }
    #[cfg(feature = "adapters")]
    {
        // a run the engine never saw (a plan answered by the source)
        // reports the notes the tool raised around it
        let r = execute(&cli, &cli.query, &oc);
        oc.flush_notes();
        return r;
    }
    #[cfg(not(feature = "adapters"))]
    unreachable!("the adapters are compiled out: this build is the calculator")
}

/// The calculator's checks on the command line: no input, no mount,
/// none of the options that open or translate one; the expression
/// head supplied where the query lacks it.
fn calc_check_options(cli: &mut Cli) -> anyhow::Result<Option<String>> {
    // Every positional argument is expression text: `qc 3 + 5` is
    // the expression `3 + 5`. The arguments stay in `paths` so that
    // a query which fails to parse can name an existing file among
    // them as the likely cause.
    if !cli.paths.is_empty() {
        let mut words = vec![cli.query.clone()];
        words.extend(cli.paths.iter().map(|p| p.to_string_lossy().into_owned()));
        cli.query = words.join(" ");
    }
    for (on, flag) in [
        (cli.model.is_some(), "--model"),
        (!cli.desm.is_empty(), "--desm"),
        (cli.resident || cli.resident_serve, "--resident"),
        (cli.cache || cli.cache_dir.is_some(), "--cache"),
        (cli.xpath, "--xpath"),
        (cli.jq, "--jq"),
        (cli.sql, "--sql"),
    ] {
        if on {
            anyhow::bail!(
                "qc is the calculator: {flag} opens or translates a source — run it with qua"
            );
        }
    }
    let q = cli.query.trim_start();
    let body = q.strip_prefix('=').unwrap_or(q).trim_start();
    // `-l`: one thread per line of the input — the head's text topic
    // split by `lines`, the query running over the lines as after
    // an iteration pipe. A body that opens with a pipe joins as it
    // stands; any other body is a command of its own.
    // A body that opens with a pipe stands for `$_ | …`: the topic
    // (the input) is what it pipes from.
    let opens_with_pipe = ["|", "@|", "__", "@__"].iter().any(|p| body.starts_with(p));
    // The piped text, read here so the query's shape is judged
    // against it: a query that opens with a pipe continues the piped
    // text (`echo a b c | qc '| words @| count'`); with nothing piped
    // there is nothing to continue, and the leading pipe is the
    // fragment qua refuses (draft 171). At a terminal the text is
    // none and the topic stays null. (`--expand` runs nothing: the
    // lens shows the sugar as it stands.)
    let piped = if std::io::IsTerminal::is_terminal(&std::io::stdin()) {
        None
    } else {
        let mut text = String::new();
        std::io::Read::read_to_string(&mut std::io::stdin().lock(), &mut text)
            .context("reading standard input")?;
        Some(text)
    };
    if opens_with_pipe
        && !cli.lines
        && !cli.expand
        && piped.as_deref().is_none_or(|t| t.trim().is_empty())
    {
        anyhow::bail!(
            "a leading pipe continues the piped text, and nothing is piped: a query without \
             input opens the root thread with '= .f(0) | …' or '^ | .f(0) | …' (a leading \
             pipe is a fragment)"
        );
    }
    cli.query = match (cli.lines, opens_with_pipe) {
        (true, true) => format!("= $_ | lines {body}"),
        (true, false) => format!("= $_ | lines | {body}"),
        (false, true) => format!("= $_ {body}"),
        // `^ | cmd` opens the root thread as in qua: no head before it
        (false, false) if body.starts_with('^') => body.to_string(),
        (false, false) => format!("= {body}"),
    };
    Ok(piped)
}

/// The calculator's check on the query, its definitions in front:
/// one that navigates, or whose operand reads a document, is
/// refused by name.
fn calc_check_query(cli: &Cli) -> anyhow::Result<()> {
    if !quarb::is_calculator(&cli.query) {
        // A query that fails to parse says so, and when one of the
        // arguments joined into it is a file on disk, the likely
        // cause is an input the calculator does not take; one that
        // parses but navigates is refused by what it needs.
        if let Err(e) = quarb::expand(&cli.query, &quarb::Defs::default()) {
            if let Some(p) = cli.paths.iter().find(|p| p.exists()) {
                anyhow::bail!(
                    "qc is the calculator and takes no input: '{}' names a file (an unquoted * or ? expands to the files of the directory: quote the expression) — a query over files runs with qua",
                    p.display()
                );
            }
            return Err(e.into());
        }
        anyhow::bail!(
            "qc is the calculator: this query navigates (a path from a node, or a mount) — run it with qua"
        );
    }
    if let Some(path) = quarb::calculator_reads(&cli.query) {
        anyhow::bail!(
            "qc is the calculator: '{path}' reads a document — run the query with qua over an input"
        );
    }
    Ok(())
}

/// A calculator query, run against the bare root: what `qua` runs
/// for an expression head without an input, and what `qc` runs for
/// everything — one path, so the two print the same bytes.
fn calc_execute(query: &str, kaiv: bool, oc: &OutputCtx) -> anyhow::Result<()> {
    // The bare root carries the composing layer too where the
    // readers are linked, so `= "…" | graft(json) | /a/*::` grafts a
    // literal or a program's output with no file behind it; the
    // calculator build, with no readers, keeps the bare root.
    #[cfg(feature = "adapters")]
    {
        let adapter = ComposeAdapter::new(quarb::adapter::Bare)
            .on_demand_only()
            .with_string_reader(quarb_open::string_reader(&SourceCtx::default()));
        return run_wrapped(
            query,
            &adapter,
            |n| adapter.locator(n, |_| String::new()),
            kaiv.then_some("stdin"),
            oc,
        );
    }
    #[cfg(not(feature = "adapters"))]
    {
        let adapter = quarb::adapter::Bare;
        run_wrapped(
            query,
            &adapter,
            |_| String::new(),
            kaiv.then_some("stdin"),
            oc,
        )
    }
}

// ---------------------------------------------------------------------------
// Resident sessions: a background qua keeps the materialized
// adapter alive; clients send queries over a Unix socket and read
// framed results. The protocol is deliberately tiny:
//   client → "Q <len>\n" + <len bytes of query text>
//   server → "R <len> <status>\n" + <len bytes>  (status 0 = ok)
// ---------------------------------------------------------------------------

/// The session socket: keyed by the canonical target set plus every
/// flag that changes query semantics, so different views of the
/// same tree get different sessions.
#[cfg(unix)]
#[cfg(feature = "adapters")]
fn resident_socket(cli: &Cli, oc: &OutputCtx) -> anyhow::Result<PathBuf> {
    use std::hash::{Hash, Hasher};
    let mut h = std::collections::hash_map::DefaultHasher::new();
    for p in &cli.paths {
        std::fs::canonicalize(p)
            .unwrap_or_else(|_| p.clone())
            .hash(&mut h);
    }
    (
        cli.graft,
        cli.no_graft,
        cli.hidden,
        cli.no_ignore,
        cli.allow_shell,
        cli.quantifier_bound,
        &cli.now,
        &cli.refs,
        &cli.defs,
        &cli.model,
        cli.no_pushdown,
        // A session renders under the locale it was started with.
        oc.locale.map(|(l, _)| l).map(|l| l.tag),
    )
        .hash(&mut h);
    // (a thirteenth element: tuples hash up to twelve)
    cli.frontier_bound.hash(&mut h);
    // The root the tree is opened at, the graph bound, and the
    // environments mounted. The key hashes `allow_shell` so that a
    // client is never answered by a session with more reach than it
    // asked for; the mounts that replaced the flag are taken out of
    // the paths before the paths are hashed, so a client that mounted
    // nothing reached a session started with `bin=exec:/bin` and ran
    // `bin:cat` in it, for the session's half hour. And a session
    // opened at `--root /a` answered a client that named no root.
    cli.root.hash(&mut h);
    cli.graph_bound.hash(&mut h);
    for e in &oc.environments {
        (&e.alias, std::mem::discriminant(&e.kind), &e.target).hash(&mut h);
    }
    // A session renders as it was started: its output form and its
    // grouping are part of its identity, so a --json session never
    // answers a plain client. A relative source (`t.txt`,
    // `text:t.txt`) names a different file from each directory.
    (
        cli.json,
        cli.jsonl,
        cli.csv,
        cli.table,
        cli.kaiv,
        cli.grouping,
    )
        .hash(&mut h);
    std::env::current_dir().ok().hash(&mut h);
    // The engine that answers. A session is a process of one build,
    // and its key named the inputs and the options only: a client of
    // another build over the same inputs connected to it and was
    // answered by that engine. After an upgrade a standing session
    // went on answering with the old engine for as long as it was
    // used, and a timing of a new build measured the old one.
    engine_build().hash(&mut h);
    let dir = resident_dir()?;
    Ok(dir.join(format!("quarb-{:016x}.sock", h.finish())))
}

/// The build of the engine this process is, as a session's key and
/// its note carry it: the version, and eight hex digits of the
/// binary's own identity (its path, its size and when it was
/// written), which tell two builds of one version apart.
#[cfg(unix)]
#[cfg(feature = "adapters")]
fn engine_build() -> String {
    engine_build_of(
        env!("CARGO_PKG_VERSION"),
        std::env::current_exe().ok().as_deref(),
    )
}

#[cfg(unix)]
#[cfg(feature = "adapters")]
fn engine_build_of(version: &str, exe: Option<&std::path::Path>) -> String {
    use std::hash::{Hash, Hasher};
    let mut h = std::collections::hash_map::DefaultHasher::new();
    version.hash(&mut h);
    if let Some(exe) = exe {
        exe.hash(&mut h);
        if let Ok(m) = std::fs::metadata(exe) {
            m.len().hash(&mut h);
            m.modified().ok().hash(&mut h);
        }
    }
    format!("{version} {:08x}", h.finish() as u32)
}

/// The directory holding session sockets. $XDG_RUNTIME_DIR is
/// per-user and 0700; without it, fall back to a per-uid 0700
/// subdirectory of the temp dir — never a world-writable directory
/// directly, where the predictable socket name could be squatted
/// by another local user. The fallback dir is verified to be ours
/// (owned by this uid, mode 0700, not a symlink): a pre-created
/// impostor directory would let its owner remove or replace live
/// sockets, so an unverifiable dir is a hard error rather than a
/// quiet risk.
#[cfg(unix)]
#[cfg(feature = "adapters")]
fn resident_dir() -> anyhow::Result<PathBuf> {
    use std::os::unix::fs::{MetadataExt as _, PermissionsExt as _};
    if let Some(d) = std::env::var_os("XDG_RUNTIME_DIR") {
        return Ok(PathBuf::from(d));
    }
    let uid = unsafe { libc::getuid() };
    let d = std::env::temp_dir().join(format!("quarb-{uid}"));
    let _ = std::fs::create_dir(&d);
    let _ = std::fs::set_permissions(&d, std::fs::Permissions::from_mode(0o700));
    let ok = std::fs::symlink_metadata(&d).is_ok_and(|m| {
        m.file_type().is_dir() && m.uid() == uid && m.permissions().mode() & 0o777 == 0o700
    });
    anyhow::ensure!(
        ok,
        "{} is not a private directory owned by this user \
         (another user may have created it); remove it or set \
         XDG_RUNTIME_DIR to use resident sessions",
        d.display()
    );
    Ok(d)
}

/// The inputs a session stands over, apart from how it reads them:
/// each target as the file system names it, or as written beside the
/// directory where it names no file (a source with a reading prefix,
/// a URL). Two sessions with this key in common hold the same inputs
/// twice.
#[cfg(unix)]
#[cfg(feature = "adapters")]
fn resident_inputs_key(cli: &Cli) -> u64 {
    use std::hash::{Hash, Hasher};
    let mut h = std::collections::hash_map::DefaultHasher::new();
    for p in &cli.paths {
        match std::fs::canonicalize(p) {
            Ok(real) => real.hash(&mut h),
            Err(_) => (std::env::current_dir().ok(), p).hash(&mut h),
        }
    }
    h.finish()
}

/// What a session says of itself beside its socket (the file
/// `quarb-KEY.session`): the key of its inputs, its process, the
/// directory it was started in, its arguments without the query and
/// the build of the engine it is.
/// A client about to start another session over the same inputs
/// reads it ([`warn_of_standing_sessions`]).
#[cfg(unix)]
#[cfg(feature = "adapters")]
fn resident_note(cli: &Cli) -> String {
    let quoted = |arg: &std::ffi::OsStr| -> String {
        let arg = arg.to_string_lossy();
        let plain = !arg.is_empty()
            && arg
                .chars()
                .all(|c| c.is_alphanumeric() || "-_./=:,+@%".contains(c));
        if plain {
            arg.into_owned()
        } else {
            format!("'{}'", arg.replace('\'', "'\\''"))
        }
    };
    // the arguments as the first client wrote them: the serve flag
    // and the query are no part of how the inputs are read
    let mut query_seen = false;
    let args: Vec<String> = std::env::args_os()
        .skip(1)
        .filter(|a| a != "--resident-serve")
        .filter(|a| {
            let is_query = !query_seen && a.to_string_lossy() == cli.query;
            query_seen |= is_query;
            !is_query
        })
        .map(|a| quoted(&a))
        .collect();
    format!(
        "inputs {:016x}\npid {}\ncwd {}\nargs {}\nengine {}\n",
        resident_inputs_key(cli),
        std::process::id(),
        std::env::current_dir()
            .map(|d| d.display().to_string())
            .unwrap_or_default(),
        args.join(" "),
        engine_build()
    )
}

#[cfg(unix)]
#[cfg(feature = "adapters")]
thread_local! {
    /// A serving session's note of itself, written beside its socket
    /// once the socket is bound and removed with it.
    static RESIDENT_NOTE: std::cell::RefCell<Option<String>> = const { std::cell::RefCell::new(None) };
}

/// Before a client starts a session: every other session that stands
/// over the same inputs is named on standard error (the user,
/// 2026-11-16). A session is keyed by its inputs AND by every option
/// that changes what a query answers, the output form and the
/// directory, so the same tree asked under another flag, or from
/// another directory, is materialized a second time beside the
/// first: two sessions over the Linux tree, 36 GB each, on a machine
/// of 62 GB. The second still starts: it may be what is meant.
#[cfg(unix)]
#[cfg(feature = "adapters")]
fn warn_of_standing_sessions(cli: &Cli, sock: &std::path::Path) {
    let Ok(dir) = resident_dir() else { return };
    let Ok(entries) = std::fs::read_dir(&dir) else {
        return;
    };
    let ours = format!("{:016x}", resident_inputs_key(cli));
    let own_note = sock.with_extension("session");
    for entry in entries.flatten() {
        let path = entry.path();
        let named = path
            .file_name()
            .and_then(|n| n.to_str())
            .is_some_and(|n| n.starts_with("quarb-") && n.ends_with(".session"));
        if !named || path == own_note {
            continue;
        }
        let Ok(note) = std::fs::read_to_string(&path) else {
            continue;
        };
        let field = |name: &str| -> &str {
            note.lines()
                .find_map(|l| l.strip_prefix(name)?.strip_prefix(' '))
                .unwrap_or("")
        };
        let Ok(pid) = field("pid").parse::<i32>() else {
            continue;
        };
        // a session that is gone left its note behind (killed, or
        // the machine went down): not standing, and the note goes
        let alive = unsafe { libc::kill(pid, 0) } == 0 && path.with_extension("sock").exists();
        if !alive {
            let _ = std::fs::remove_file(&path);
            continue;
        }
        if field("inputs") != ours {
            continue;
        }
        // A session of another build is never this client's: say
        // so, the reason it stands beside the new one (a session of
        // an engine before 0.67 wrote no build into its note).
        let ours_build = engine_build();
        let why = match field("engine") {
            theirs if theirs == ours_build => {
                "a session is reused under the same options and from the same directory".to_string()
            }
            "" => format!(
                "that session is an earlier build of the engine (this client is \
                 {ours_build}), and a session answers the clients of its own build"
            ),
            theirs => format!(
                "that session is another build of the engine ({theirs}; this client is \
                 {ours_build}), and a session answers the clients of its own build"
            ),
        };
        eprintln!(
            "resident session: another one already stands over the same inputs (pid {pid}, \
             started in {} as: qua {}). This run starts a second, which reads the inputs \
             again; {why}. To end the first: kill {pid}",
            field("cwd"),
            field("args")
        );
    }
}

/// Client side: connect to the session (starting it if needed),
/// send the query, stream the result.
#[cfg(unix)]
#[cfg(feature = "adapters")]
fn resident_client(cli: &Cli, oc: &OutputCtx) -> anyhow::Result<()> {
    use std::io::Write as _;
    let sock = resident_socket(cli, oc)?;
    let mut stream = match std::os::unix::net::UnixStream::connect(&sock) {
        Ok(s) => s,
        // No live session. The server owns stale-socket cleanup
        // (removing here would race a concurrent client into
        // orphaning a daemon that just bound).
        Err(_) => {
            warn_of_standing_sessions(cli, &sock);
            spawn_resident(&sock)?
        }
    };
    let q = cli.query.as_bytes();
    stream.write_all(format!("Q {}\n", q.len()).as_bytes())?;
    stream.write_all(q)?;
    stream.flush()?;
    let mut reader = std::io::BufReader::new(stream);
    let mut header = String::new();
    std::io::BufRead::read_line(&mut reader, &mut header)?;
    let mut parts = header.trim_end().split(' ');
    anyhow::ensure!(
        parts.next() == Some("R"),
        "bad session response: {header:?}"
    );
    let len: usize = parts
        .next()
        .and_then(|s| s.parse().ok())
        .context("bad session response length")?;
    let status: u8 = parts
        .next()
        .and_then(|s| s.parse().ok())
        .context("bad session response status")?;
    // The diagnostics, when the server sent any (a fourth field).
    let dlen: usize = parts.next().and_then(|s| s.parse().ok()).unwrap_or(0);
    let mut body = vec![0u8; len];
    std::io::Read::read_exact(&mut reader, &mut body)?;
    let mut diag = vec![0u8; dlen];
    if dlen > 0 {
        std::io::Read::read_exact(&mut reader, &mut diag)?;
    }
    if status == 0 {
        std::io::stdout().write_all(&body)?;
        if dlen > 0 {
            std::io::stderr().write_all(&diag)?;
        }
        Ok(())
    } else {
        anyhow::bail!("{}", String::from_utf8_lossy(&body));
    }
}

/// Start the session daemon (this binary, same arguments, plus the
/// internal serve flag), detach it from the terminal, and wait for
/// its socket — the wait covers materialization, which for a large
/// tree is exactly the cost the session exists to amortize.
#[cfg(unix)]
#[cfg(feature = "adapters")]
fn spawn_resident(sock: &std::path::Path) -> anyhow::Result<std::os::unix::net::UnixStream> {
    use std::os::unix::process::CommandExt as _;
    let log = sock.with_extension("log");
    let logfile =
        std::fs::File::create(&log).with_context(|| format!("creating {}", log.display()))?;
    let exe = std::env::current_exe().context("resolving qua binary")?;
    let mut cmd = std::process::Command::new(exe);
    // The flag goes first: after a `--` in the user's arguments it
    // would be a path, and the child would be a client spawning its
    // own child, without end. The marker is the second lock.
    if std::env::var_os("QUARB_RESIDENT_CHILD").is_some() {
        anyhow::bail!("a resident session does not spawn a session of its own");
    }
    cmd.arg("--resident-serve")
        .args(std::env::args_os().skip(1))
        .env("QUARB_RESIDENT_CHILD", "1")
        .stdin(std::process::Stdio::null())
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::from(logfile));
    // A session of its own: survives this client and its terminal.
    unsafe {
        cmd.pre_exec(|| {
            libc::setsid();
            Ok(())
        });
    }
    let mut child = cmd.spawn().context("starting resident session")?;
    eprintln!(
        "resident session starting (first query pays materialization; \
         log: {})",
        log.display()
    );
    let started = std::time::Instant::now();
    let mut last_note = 0u64;
    // The socket is looked for at short intervals first, doubling up
    // to 200 ms: a session over a small input stands within
    // milliseconds, and a flat 200 ms was most of its first answer.
    let mut nap = std::time::Duration::from_millis(2);
    loop {
        if let Ok(s) = std::os::unix::net::UnixStream::connect(sock) {
            return Ok(s);
        }
        if let Some(status) = child.try_wait()? {
            // A clean exit can mean our spawn lost a race and
            // deferred to an already-live session — connect to it.
            if let Ok(s) = std::os::unix::net::UnixStream::connect(sock) {
                return Ok(s);
            }
            let tail = std::fs::read_to_string(&log).unwrap_or_default();
            let tail = tail.lines().rev().take(5).collect::<Vec<_>>();
            anyhow::bail!(
                "resident session exited ({status}) before binding its socket:\n{}",
                tail.into_iter().rev().collect::<Vec<_>>().join("\n")
            );
        }
        let elapsed = started.elapsed().as_secs();
        if elapsed >= last_note + 15 {
            eprintln!("  … materializing ({elapsed}s)");
            last_note = elapsed;
        }
        std::thread::sleep(nap);
        nap = (nap * 2).min(std::time::Duration::from_millis(200));
    }
}

/// Wait until a client knocks at the session's socket, or until
/// `at_most` has passed (a second at the longest, so the idle time
/// is looked at again). The wait is the kernel's: a client is
/// accepted the moment it connects. (The loop napped 200 ms between
/// two looks at the socket, so a query that followed another waited
/// out the nap: every answer of a session took 0.2 s, whatever the
/// question, and a small input answered slower than with no session
/// at all.)
#[cfg(unix)]
#[cfg(feature = "adapters")]
fn wait_for_client(listener: &std::os::unix::net::UnixListener, at_most: std::time::Duration) {
    use std::os::fd::AsRawFd as _;
    let mut fd = libc::pollfd {
        fd: listener.as_raw_fd(),
        events: libc::POLLIN,
        revents: 0,
    };
    let ms = at_most.as_millis().clamp(1, 1000) as libc::c_int;
    // A signal that interrupts the wait, or an error, is the caller's
    // next look at the socket; an error that persists must not spin.
    if unsafe { libc::poll(&mut fd, 1, ms) } < 0
        && std::io::Error::last_os_error().kind() != std::io::ErrorKind::Interrupted
    {
        std::thread::sleep(std::time::Duration::from_millis(200));
    }
}

/// The largest query frame a session accepts. Query text is typed
/// by a person; the cap only exists so a garbled length header
/// cannot make the daemon allocate gigabytes.
#[cfg(unix)]
#[cfg(feature = "adapters")]
const RESIDENT_MAX_QUERY: usize = 1 << 20;

/// Server side: bind the socket and answer queries against the
/// standing adapter until the idle TTL expires. Queries run
/// serially; each failure answers that client and the session
/// lives on.
#[cfg(unix)]
#[cfg(feature = "adapters")]
fn resident_serve_loop<A: AstAdapter>(
    adapter: &A,
    render: impl Fn(NodeId) -> String,
    sock: &std::path::Path,
    ttl: u64,
    now_pinned: bool,
    oc: &OutputCtx,
) -> anyhow::Result<()> {
    use std::io::Write as _;
    // Clients can vanish mid-response (Ctrl-C, a closed pipe on
    // their stdout): the write then raises SIGPIPE, and the SIG_DFL
    // disposition cli_main restores (right for the one-shot filter)
    // would kill the whole session — and its materialization — with
    // it. Ignore it here; the write fails with EPIPE instead, which
    // the per-client `let _ =` absorbs.
    unsafe {
        libc::signal(libc::SIGPIPE, libc::SIG_IGN);
    }
    // Exclusive bind. When the path is taken, probe it: a live
    // daemon answering means another spawn won the race — defer to
    // it and exit, instead of unbinding it and idling as an
    // unreachable copy of the (possibly huge) materialization.
    // Only a dead socket (connect refused) is stale and removable.
    let listener = match std::os::unix::net::UnixListener::bind(sock) {
        Ok(l) => l,
        Err(e) if e.kind() == std::io::ErrorKind::AddrInUse => {
            if std::os::unix::net::UnixStream::connect(sock).is_ok() {
                eprintln!("resident session already live; deferring to it");
                return Ok(());
            }
            let _ = std::fs::remove_file(sock);
            std::os::unix::net::UnixListener::bind(sock)
                .with_context(|| format!("binding {}", sock.display()))?
        }
        Err(e) => return Err(e).with_context(|| format!("binding {}", sock.display())),
    };
    // Belt over the 0700 directory: the socket itself is private.
    let _ = std::fs::set_permissions(sock, {
        use std::os::unix::fs::PermissionsExt as _;
        std::fs::Permissions::from_mode(0o600)
    });
    // What this session is, for a client about to start another over
    // the same inputs.
    let note = sock.with_extension("session");
    if let Some(text) = RESIDENT_NOTE.with(|n| n.borrow_mut().take()) {
        let _ = std::fs::write(&note, text);
        let _ = std::fs::set_permissions(&note, {
            use std::os::unix::fs::PermissionsExt as _;
            std::fs::Permissions::from_mode(0o600)
        });
    }
    listener.set_nonblocking(true)?;
    let mut idle = std::time::Instant::now();
    loop {
        match listener.accept() {
            Ok((mut conn, _)) => {
                idle = std::time::Instant::now();
                conn.set_nonblocking(false)?;
                // A stalled client (stopped, wedged) must not hang
                // the serial loop past the TTL's reach.
                let _ = conn.set_read_timeout(Some(std::time::Duration::from_secs(30)));
                let _ = conn.set_write_timeout(Some(std::time::Duration::from_secs(30)));
                let mut reader = std::io::BufReader::new(conn.try_clone()?);
                let mut header = String::new();
                if std::io::BufRead::read_line(&mut reader, &mut header).is_err() {
                    continue;
                }
                let len: usize = match header
                    .trim_end()
                    .strip_prefix("Q ")
                    .and_then(|s| s.parse().ok())
                {
                    Some(n) if n <= RESIDENT_MAX_QUERY => n,
                    Some(_) => {
                        let msg = b"query exceeds the resident frame limit";
                        let _ = conn.write_all(format!("R {} 1\n", msg.len()).as_bytes());
                        let _ = conn.write_all(msg);
                        continue;
                    }
                    None => continue,
                };
                let mut qbytes = vec![0u8; len];
                if std::io::Read::read_exact(&mut reader, &mut qbytes).is_err() {
                    continue;
                }
                let query = String::from_utf8_lossy(&qbytes).into_owned();
                // The output command is each query's own: taken off
                // and reset here, never inherited from the last.
                let (query, copy) = take_copy(&query);
                let (query, encoding) = match take_output_encoding(&query) {
                    Ok(q) => q,
                    Err(e) => {
                        let body = format!("{e:#}").into_bytes();
                        let _ = conn.write_all(format!("R {} 1\n", body.len()).as_bytes());
                        let _ = conn.write_all(&body);
                        continue;
                    }
                };
                // A source that can move under the session looks
                // again before each query (a git repository at its
                // refs): the query answers it as it stands.
                adapter.refresh();
                // Each query is its own invocation instant unless
                // the session was pinned with --now.
                let mut now = oc.now;
                if !now_pinned {
                    let since = std::time::SystemTime::now()
                        .duration_since(std::time::UNIX_EPOCH)
                        .unwrap_or_default();
                    now = (since.as_secs() as i64, since.subsec_nanos());
                    quarb::set_invocation_instant(now.0, now.1);
                }
                let per_query = OutputCtx {
                    encoding,
                    copy,
                    now,
                    ..oc.clone()
                };
                DIAG_SINK.with(|s| *s.borrow_mut() = Some(Vec::new()));
                let (result, output) = with_stdout_capture(|| {
                    let r = run_wrapped(&query, adapter, &render, None, &per_query);
                    per_query.flush_notes();
                    r
                });
                let diag_lines = DIAG_SINK
                    .with(|s| s.borrow_mut().take())
                    .unwrap_or_default();
                let (status, body) = match result {
                    Ok(()) => (0u8, output),
                    Err(e) => (1u8, format!("{e:#}").into_bytes()),
                };
                // The diagnostics follow the body, their length a
                // fourth field of the header (absent = none).
                let diag: Vec<u8> = diag_lines
                    .iter()
                    .flat_map(|l| format!("{l}\n").into_bytes())
                    .collect();
                let _ = conn
                    .write_all(format!("R {} {} {}\n", body.len(), status, diag.len()).as_bytes());
                let _ = conn.write_all(&body);
                let _ = conn.write_all(&diag);
                let _ = conn.flush();
            }
            Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => {
                if idle.elapsed().as_secs() >= ttl {
                    break;
                }
                let left = std::time::Duration::from_secs(ttl).saturating_sub(idle.elapsed());
                wait_for_client(&listener, left);
            }
            Err(e) => {
                eprintln!("resident session accept error: {e}");
                std::thread::sleep(std::time::Duration::from_millis(200));
            }
        }
    }
    let _ = std::fs::remove_file(sock);
    let _ = std::fs::remove_file(&note);
    Ok(())
}

/// The codes the tool itself raises, named in the engine's list
/// with every other (`quarb::diagnostic`): the planner's account
/// (what was pushed to a source, what a source answered natively;
/// what stayed with the engine goes under the word of its reason,
/// `SORT_NOT_PUSHED` and its kin), the locale in force and a locale
/// tag without rules, an external reference the run left
/// unresolved, a reading a mount declined, a lenient translation,
/// and the debug codes of the plan a source was handed and the
/// mount a query ran over.
use quarb::diagnostic::{
    DELEGATED, LENIENT_TRANSLATION, LOCALE, LOCALE_UNKNOWN, MOUNT, PLAN, PUSHED, READING,
    UNRESOLVED,
};

thread_local! {
    /// The diagnostics the tool itself raises around a run — the
    /// planner's infos, the locale layer's — kept until the run's
    /// report drains them in front of the engine's own, or the
    /// flush after a run the engine never saw (a plan answered by
    /// the source).
    static NOTES: std::cell::RefCell<Vec<quarb::Diagnostic>> = const { std::cell::RefCell::new(Vec::new()) };
    /// Whether debug notes are raised at all: the level asked for
    /// them (spec: Diagnostics, the debug licence).
    static DEBUG_NOTES: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}

fn note(d: quarb::Diagnostic) {
    NOTES.with(|n| n.borrow_mut().push(d));
}

fn note_info(code: &str, site: impl Into<String>, message: impl Into<String>) {
    note(quarb::Diagnostic::info(code, site, message));
}

fn note_warning(code: &str, site: impl Into<String>, message: impl Into<String>) {
    note(quarb::Diagnostic::warning(code, site, message));
}

/// A debug note, its message built only when the level asks.
fn note_debug(code: &str, site: impl Into<String>, message: impl FnOnce() -> String) {
    if DEBUG_NOTES.with(|d| d.get()) {
        note(quarb::Diagnostic::new(
            quarb::Severity::Debug,
            code,
            site,
            message(),
        ));
    }
}

fn take_notes() -> Vec<quarb::Diagnostic> {
    NOTES.with(|n| std::mem::take(&mut *n.borrow_mut()))
}

thread_local! {
    /// The resident server's diagnostics sink: while set, a run's
    /// diagnostics collect here (as the lines a terminal would
    /// print) instead of going to the server's stderr, and ride the
    /// reply to the client, which prints them on its own stderr.
    static DIAG_SINK: std::cell::RefCell<Option<Vec<String>>> = const { std::cell::RefCell::new(None) };
}

/// Run `f` with stdout captured to a byte buffer (fd-level, so the
/// existing print-based output paths need no plumbing, and
/// non-UTF-8 output survives verbatim). Queries in a session run
/// serially, which keeps the fd dance safe.
#[cfg(unix)]
#[cfg(feature = "adapters")]
fn with_stdout_capture<R>(f: impl FnOnce() -> R) -> (R, Vec<u8>) {
    use std::io::{Read as _, Seek as _, Write as _};
    use std::os::fd::AsRawFd as _;
    let _ = std::io::stdout().flush();
    let mut tmp = match tempfile_in_temp() {
        Ok(t) => t,
        Err(_) => return (f(), Vec::new()),
    };
    let saved = unsafe { libc::dup(1) };
    if saved < 0 {
        return (f(), Vec::new());
    }
    unsafe { libc::dup2(tmp.as_raw_fd(), 1) };
    let r = f();
    let _ = std::io::stdout().flush();
    unsafe {
        libc::dup2(saved, 1);
        libc::close(saved);
    }
    let mut out = Vec::new();
    let _ = tmp.seek(std::io::SeekFrom::Start(0));
    let _ = tmp.read_to_end(&mut out);
    (r, out)
}

/// An anonymous scratch file for the capture (unlinked at once).
#[cfg(unix)]
#[cfg(feature = "adapters")]
fn tempfile_in_temp() -> std::io::Result<std::fs::File> {
    let path = std::env::temp_dir().join(format!(
        "quarb-capture-{}-{:x}",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.subsec_nanos())
            .unwrap_or(0)
    ));
    let f = std::fs::OpenOptions::new()
        .create_new(true)
        .read(true)
        .write(true)
        .open(&path)?;
    let _ = std::fs::remove_file(&path);
    Ok(f)
}

/// Run one query text against the CLI's inputs, printing results —
/// the whole adapter dispatch.
/// The plan against the inputs' catalogs, before any is opened:
/// printed under --plan (`true`: handled); refused under a --budget
/// it exceeds; else `false`, and the inputs open as usual (the run
/// checks the budget again on the opened adapters' own estimates).
/// `false` too when an input has no catalog — a database, a
/// service — since its plan is the opened adapter's to price.
#[cfg(feature = "adapters")]
impl Cli {
    /// An input's mount name and target, where it has a name: the
    /// name a model's statement gave it, as written, else the
    /// command line's `NAME=TARGET`.
    fn alias(&self, p: &Path) -> Option<(String, PathBuf)> {
        self.stated
            .get(p)
            .cloned()
            .or_else(|| quarb_open::split_alias(p))
    }
}

#[cfg(feature = "adapters")]
fn preflight(cli: &Cli, query: &str, oc: &OutputCtx) -> anyhow::Result<bool> {
    let split_alias = |p: &Path| cli.alias(p);
    let cap = oc.budget.as_ref().map_or(quarb::Cap::NONE, |b| b.cap());
    // A folder is priced as the run will walk it: the same hidden
    // and ignore rules, so the plan counts the files the mount
    // exposes and no others.
    let seen = quarb_fs::FsOptions {
        hidden: cli.hidden,
        respect_ignore: !cli.no_ignore,
    };
    let mut catalogs = Vec::new();
    for (i, p) in cli.paths.iter().enumerate() {
        let (name, target) = match split_alias(p) {
            Some(alias) => alias,
            None => (
                p.file_stem()
                    .map(|s| s.to_string_lossy().into_owned())
                    // a mount no name can be had for is named by its place
                    // among the inputs, from one (ruling 2026-11-14)
                    .unwrap_or_else(|| format!("doc{}", i + 1)),
                p.clone(),
            ),
        };
        let t = target.to_string_lossy().into_owned();
        if quarb_open::catalog_seen(&t, cap, seen).is_none() {
            return Ok(false);
        }
        let lookup: quarb::CatalogLookup =
            Box::new(move |ask| quarb_open::catalog_for_seen(&t, ask, seen));
        catalogs.push((name, target.display().to_string(), lookup));
    }
    if catalogs.is_empty() {
        return Ok(false);
    }
    let run = oc.run_opts();
    let defs = quarb::Defs::default();
    let plan = if catalogs.len() >= 2 || cli.paths.iter().any(|p| split_alias(p).is_some()) {
        let mut m = MountAdapter::new(Vec::new());
        for (name, target, lookup) in catalogs {
            m.declare(Latent {
                name,
                target: Some(target),
                opener: Box::new(|| Err("planned, not opened".into())),
                catalog: Some(lookup),
            })
            .map_err(|e| anyhow::anyhow!("mount: {e}"))?;
        }
        let q = quarb::Query::parse_with(query, &defs, &m, &run)?;
        match &oc.budget {
            Some(b) => q.plan_within(&m, b),
            None => q.plan(&m),
        }
    } else {
        let a = quarb::Unopened(catalogs.pop().expect("one input").2);
        let q = quarb::Query::parse_with(query, &defs, &a, &run)?;
        match &oc.budget {
            Some(b) => q.plan_within(&a, b),
            None => q.plan(&a),
        }
    };
    if oc.plan {
        print!("{}", plan.to_kaiv(query));
        return Ok(true);
    }
    // A definite excess refuses here; what the catalogs leave
    // unknown or unbounded is the opened adapters' to price, so a
    // strict budget names the bound the walk reached, as a lenient
    // one does.
    if let Some(budget) = &oc.budget
        && let Some(why) = budget.exceeded_before_opening(&plan)
    {
        return Err(quarb::QuarbError::refused(why).into());
    }
    Ok(false)
}

/// Take the environment mounts off the inputs: `go=exec:~/go/bin`,
/// `sh=shell:`, `py=python:./helpers.py`. A `shell:` mount opens the
/// shell gate (`--allow-shell`, retired, refuses naming it). Two
/// environments may not share an alias. A
/// `python:` mount imports its module here and binds it as a
/// command library under the alias, the second value.
/// The command libraries compiled into this binary, by feature.
pub fn linked_libraries() -> Vec<std::sync::Arc<dyn quarb::CommandLibrary>> {
    #[allow(unused_mut)]
    let mut libraries: Vec<std::sync::Arc<dyn quarb::CommandLibrary>> = Vec::new();
    #[cfg(feature = "morph")]
    libraries.push(std::sync::Arc::new(quarb_lib_morph::Morph));
    #[cfg(feature = "scipy")]
    libraries.push(std::sync::Arc::new(quarb_lib_scipy::Scipy));
    #[cfg(feature = "sklearn")]
    libraries.push(std::sync::Arc::new(quarb_lib_sklearn::Sklearn));
    #[cfg(feature = "numpy")]
    libraries.push(std::sync::Arc::new(quarb_lib_numpy::Numpy));
    #[cfg(feature = "pandas")]
    libraries.push(std::sync::Arc::new(quarb_lib_pandas::Pandas));
    libraries
}

type BoundModules = Vec<std::sync::Arc<dyn quarb::CommandLibrary>>;

/// The command libraries a session runs with: the linked ones, and
/// every `python:` mount bound as one under its alias (the module
/// imported now, so one that does not import refuses before any
/// query). An alias that is a linked library's prefix refuses. The
/// one binding qua and quai share.
pub fn session_libraries(
    environments: &[quarb::Environment],
) -> anyhow::Result<Vec<std::sync::Arc<dyn quarb::CommandLibrary>>> {
    let mut libraries = linked_libraries();
    for e in environments {
        if libraries.iter().any(|l| l.prefix() == e.alias) {
            anyhow::bail!(
                "'{}' is the prefix of a linked command library; an environment takes \
                 another alias",
                e.alias
            );
        }
        if e.kind == quarb::EnvKind::Python {
            libraries.push(python_environment(e)?);
        }
    }
    Ok(libraries)
}

fn take_environments(cli: &mut Cli) -> anyhow::Result<(Vec<quarb::Environment>, BoundModules)> {
    let mut environments: Vec<quarb::Environment> = Vec::new();
    let mut kept = Vec::new();
    for p in std::mem::take(&mut cli.paths) {
        match quarb::Environment::parse_mount(&p.to_string_lossy()) {
            None => kept.push(p),
            Some(Ok(e)) => {
                if environments.iter().any(|x| x.alias == e.alias) {
                    anyhow::bail!(
                        "two environments mounted as '{}'; give each its own alias",
                        e.alias
                    );
                }
                environments.push(e);
            }
            Some(Err(e)) => anyhow::bail!("{e}"),
        }
    }
    // The python: mounts bound as libraries, beside the linked ones.
    let mounted: BoundModules = session_libraries(&environments)?
        .into_iter()
        .filter(|l| environments.iter().any(|e| e.alias == l.prefix()))
        .collect();
    cli.paths = kept;
    if cli.allow_shell {
        anyhow::bail!(
            "--allow-shell is retired: mount the shell, sh=shell:, and write sh:tr(a-z; A-Z)"
        );
    }
    // The shell gate (a corpus mount's `annotate=`) is the mount.
    if environments.iter().any(|e| e.kind == quarb::EnvKind::Shell) {
        cli.allow_shell = true;
    }
    Ok((environments, mounted))
}

/// A `python:` mount bound as a command library: the module
/// imported now, so a module that does not import refuses at the
/// mount, before any query.
#[cfg(feature = "python")]
fn python_environment(
    e: &quarb::Environment,
) -> anyhow::Result<std::sync::Arc<dyn quarb::CommandLibrary>> {
    let module = quarb_pyvalue::ModuleEnvironment::mount(&e.alias, &e.target)
        .map_err(|m| anyhow::anyhow!("{m}"))?;
    Ok(std::sync::Arc::new(module))
}

#[cfg(not(feature = "python"))]
fn python_environment(
    e: &quarb::Environment,
) -> anyhow::Result<std::sync::Arc<dyn quarb::CommandLibrary>> {
    anyhow::bail!(
        "'{}=python:{}': this build is without the python feature; build qua or quai with \
         `--features python` to mount a Python module",
        e.alias,
        e.target
    )
}

#[cfg(feature = "adapters")]
fn execute(cli: &Cli, query: &str, oc: &OutputCtx) -> anyhow::Result<()> {
    let split_alias = |p: &Path| cli.alias(p);
    // The offline switch (`QUARB_OFFLINE`), before anything is
    // opened or priced: the opener holds every mount to it, and the
    // doors this function opens itself (the relational stores, for
    // pushdown; the web level) are held to it here.
    for p in &cli.paths {
        if let Some(s) = p.to_str() {
            quarb_open::offline::gate(s)?;
        }
        if let Some((_, target)) = split_alias(p)
            && let Some(s) = target.to_str()
        {
            quarb_open::offline::gate(s)?;
        }
    }
    // The source boundary of this invocation's one target.
    let ctx = &SourceCtx::default();
    // `--expand` shows the query whole; otherwise the output command
    // comes off the end here, for the sink to apply.
    let (query, copy, encoding) = if cli.expand || cli.expand_1 {
        (query.to_string(), None, None)
    } else {
        let (query, copy) = take_copy(query);
        let (query, encoding) = take_output_encoding(&query)?;
        (query, copy, encoding)
    };
    let query = &query;
    let oc = &OutputCtx {
        encoding,
        copy,
        ..oc.clone()
    };
    // A refs document only means something to an adapter that
    // consumes it; passing one alongside targets that all ignore it
    // deserves a loud note, not silence.
    if cli.refs.is_some() {
        let consumes = |p: &PathBuf| {
            let target = split_alias(p).map(|(_, t)| t).unwrap_or_else(|| p.clone());
            is_sqlite(&target)
                || target
                    .to_str()
                    .is_some_and(|s| s.starts_with("firebase://"))
        };
        if !cli.paths.iter().any(consumes) {
            eprintln!(
                "qua: --refs: no target consumes a declared-references document \
                 (SQLite databases and firebase:// do); ignoring it"
            );
        }
    }
    // --plan and --budget price the inputs before paying to open
    // them, when each has a catalog (a file, an archive, a
    // directory). Anything else is priced once open, by its own
    // adapter.
    if (oc.plan || oc.budget.is_some()) && preflight(cli, query, oc)? {
        return Ok(());
    }
    // `--root PATH` is the sugar for one source (spec: Mounts, the
    // root option); several carry `?root=PATH` each.
    if cli.root.is_some() && cli.paths.len() != 1 {
        anyhow::bail!(
            "--root takes one mounted source; with several, write ?root=PATH on each target"
        );
    }
    // Several inputs are mounted as named children of one root; a
    // single `NAME=TARGET` input mounts too, so its name is real.
    if cli.paths.len() >= 2 || cli.paths.iter().any(|p| split_alias(p).is_some()) {
        let mut mounts: Vec<Mount> = Vec::new();
        let mut renders: Vec<Box<dyn Fn(NodeId) -> String>> = Vec::new();
        for (i, p) in cli.paths.iter().enumerate() {
            let (name, target) = match split_alias(p) {
                Some(alias) => alias,
                None => (
                    p.file_stem()
                        .map(|s| s.to_string_lossy().into_owned())
                        // a mount no name can be had for is named by its place
                        // among the inputs, from one (ruling 2026-11-14)
                        .unwrap_or_else(|| format!("doc{}", i + 1)),
                    p.clone(),
                ),
            };
            // Mounts are addressed by name, so two inputs sharing one
            // would silently union under it with no way to target
            // either — refuse rather than merge distinct sources.
            if mounts.iter().any(|m| m.name == name) {
                anyhow::bail!(
                    "input '{}' mounts as '{name}', colliding with an earlier input of the \
                     same name; give one an explicit alias (NAME=TARGET)",
                    p.display()
                );
            }
            let Mounted {
                adapter, render, ..
            } = open_mount(&target, &OpenOpts::from(cli))?;
            mounts.push(Mount {
                name,
                target: Some(target.display().to_string()),
                adapter,
            });
            renders.push(render);
        }
        let sources = cli
            .paths
            .iter()
            .map(|p| p.display().to_string())
            .collect::<Vec<_>>()
            .join(", ");
        let adapter = MountAdapter::try_new(mounts).map_err(|e| anyhow::anyhow!("mount: {e}"))?;
        return run(
            query,
            &adapter,
            |n| match adapter.decode(n) {
                None => "/".to_string(),
                Some((m, inner)) => {
                    format!("/{}{}", adapter.mount_name(m), renders[m](inner))
                }
            },
            cli.kaiv.then_some(sources.as_str()),
            ctx,
            oc,
        );
    }
    // `--root PATH`, or `?root=PATH` on the one source: the subtree
    // mounted as the tree, through the mount path whatever the
    // source's kind (spec: Mounts, the root option). `?autounits` and
    // `?autounit=` take the same door (the convention wraps a mount).
    if let Some(p) = cli.paths.first()
        && let Some(target) = rooted_target(p, cli.root.as_deref()).or_else(|| units_target(p))
    {
        let src = target.display().to_string();
        let m = open_mount(&target, &OpenOpts::from(cli))?;
        return run(
            query,
            &m.adapter,
            |n| (m.render)(n),
            cli.kaiv.then_some(src.as_str()),
            ctx,
            oc,
        );
    }
    let path = match cli.paths.first() {
        Some(p) => Some(take_encoding_option(p, ctx)?),
        None => None,
    };

    // A reader prefix or an adapter scheme that is not one of the
    // relational doors below opens through quarb-open, as every
    // front-end does; the relational doors stay typed for pushdown.
    if let Some(s) = path.as_ref().and_then(|p| p.to_str())
        && is_prefixed_target(s)
        && !is_relational_target(s)
        && !s.starts_with("web:")
    {
        let src = s.to_string();
        let m = open_mount(cli.paths.first().expect("a target"), &OpenOpts::from(cli))?;
        return run(
            query,
            &m.adapter,
            |n| (m.render)(n),
            cli.kaiv.then_some(src.as_str()),
            ctx,
            oc,
        );
    }

    // The web level: a site — a directory of built pages or an
    // archive of them — as `/sites/<host>/pages/…`, each page
    // grafted at the text level on entry.
    if let Some(p) = &path
        && let Some(rest) = p.to_str().and_then(|s| s.strip_prefix("web:"))
        && !rest.is_empty()
    {
        let src = rest.to_string();
        return match web_level(rest, ctx)? {
            WebSite::Memory(adapter) => run(
                query,
                &adapter,
                |n| adapter.locator(n),
                cli.kaiv.then_some(src.as_str()),
                ctx,
                oc,
            ),
            WebSite::Sqlite(store) => run_web_store(cli, query, store, &src, ctx, oc),
            WebSite::Postgres(store) => run_web_store(cli, query, store, &src, ctx, oc),
        };
    }
    // Kùzu: kuzu:PATH (opt-in: built with --features kuzu).
    #[cfg(feature = "kuzu")]
    // A SQL Server database: mssql://USER:PASS@HOST[:PORT]/DB.
    if let Some(s) = path.as_ref().and_then(|p| p.to_str())
        && s.starts_with("mssql://")
    {
        if let Some(plan) = pushdown_plan(cli, query, Some(quarb_sql::Dialect::Mssql), Door::PLAIN)
        {
            crosslinks_named(ctx, "the database", || {
                let mut a = MssqlAdapter::connect(s).context("connecting to SQL Server")?;
                Ok(a.hold_crosslinks(&ctx.crosslinks()))
            })?;
            match quarb_mssql::raw_query(
                s,
                &plan.sql,
                plan.order_table.as_deref(),
                plan.join_left
                    .as_ref()
                    .map(|(t, c)| (t.as_str(), c.as_slice())),
            ) {
                Ok((cols, rows)) => {
                    print_raw(&cols, rows, plan.record, plan.properties, oc)?;
                    return Ok(());
                }
                Err(e) => {
                    note_info(
                        quarb::diagnostic::STATEMENT_NOT_PUSHED,
                        "query",
                        format!(
                            "the plan was not executed ({e}); scanning — the plan: {}",
                            plan.sql
                        ),
                    );
                }
            }
        }
        let adapter = match partial_plan_with(cli, query, Some(quarb_sql::Dialect::Mssql), true)
            .filter(|pl| !columns_compared_unchecked("prefilter", &pl.column_types))
        {
            Some(pl) => {
                let a = MssqlAdapter::connect_filtered(s, &pl.table, &pl.where_sql)
                    .context("connecting to SQL Server")?;
                match a.prefetch(&pl.table) {
                    Ok(()) => a,
                    Err(e) => {
                        note_info(
                            quarb::diagnostic::STATEMENT_NOT_PUSHED,
                            "prefilter",
                            format!("the prefilter was rejected ({e}); scanning"),
                        );
                        MssqlAdapter::connect(s).context("connecting to SQL Server")?
                    }
                }
            }
            None => MssqlAdapter::connect(s).context("connecting to SQL Server")?,
        };
        // the mount's `crosslinks=`, written in the URL's query
        // string: the references of these labels held in memory
        let mut adapter = adapter;
        adapter
            .hold_crosslinks(&ctx.crosslinks())
            .map_err(|e| anyhow::anyhow!("the database: {e}"))?;
        return run_relational(
            adapter,
            cli.no_graft,
            query,
            |a, n| a.locator(n),
            cli.kaiv.then_some(s),
            ctx,
            oc,
        );
    }

    // An Oracle database: oracle://USER:PASS@HOST[:PORT]/SERVICE.
    if let Some(s) = path.as_ref().and_then(|p| p.to_str())
        && s.starts_with("oracle://")
    {
        if let Some(plan) = pushdown_plan(cli, query, Some(quarb_sql::Dialect::Oracle), Door::PLAIN)
        {
            crosslinks_named(ctx, "the database", || {
                let mut a = OracleAdapter::connect(s).context("connecting to Oracle")?;
                Ok(a.hold_crosslinks(&ctx.crosslinks()))
            })?;
            match quarb_oracle::raw_query(
                s,
                &plan.sql,
                plan.order_table.as_deref(),
                plan.join_left
                    .as_ref()
                    .map(|(t, c)| (t.as_str(), c.as_slice())),
            ) {
                Ok((cols, rows)) => {
                    print_raw(&cols, rows, plan.record, plan.properties, oc)?;
                    return Ok(());
                }
                Err(e) => {
                    note_info(
                        quarb::diagnostic::STATEMENT_NOT_PUSHED,
                        "query",
                        format!(
                            "the plan was not executed ({e}); scanning — the plan: {}",
                            plan.sql
                        ),
                    );
                }
            }
        }
        let adapter = match partial_plan_with(cli, query, Some(quarb_sql::Dialect::Oracle), true)
            .filter(|pl| !columns_compared_unchecked("prefilter", &pl.column_types))
        {
            Some(pl) => {
                let a = OracleAdapter::connect_filtered(s, &pl.table, &pl.where_sql)
                    .context("connecting to Oracle")?;
                match a.prefetch(&pl.table) {
                    Ok(()) => a,
                    Err(e) => {
                        note_info(
                            quarb::diagnostic::STATEMENT_NOT_PUSHED,
                            "prefilter",
                            format!("the prefilter was rejected ({e}); scanning"),
                        );
                        OracleAdapter::connect(s).context("connecting to Oracle")?
                    }
                }
            }
            None => OracleAdapter::connect(s).context("connecting to Oracle")?,
        };
        // the mount's `crosslinks=`, written in the URL's query
        // string: the references of these labels held in memory
        let mut adapter = adapter;
        adapter
            .hold_crosslinks(&ctx.crosslinks())
            .map_err(|e| anyhow::anyhow!("the database: {e}"))?;
        return run_relational(
            adapter,
            cli.no_graft,
            query,
            |a, n| a.locator(n),
            cli.kaiv.then_some(s),
            ctx,
            oc,
        );
    }

    // A BigQuery target connects and introspects the dataset.
    if let Some(s) = path.as_ref().and_then(|p| p.to_str())
        && s.starts_with("bigquery://")
    {
        if let Some(plan) = pushdown_plan(cli, query, None, Door::PLAIN) {
            crosslinks_named(ctx, "the database", || {
                let mut a = BigqueryAdapter::connect(s).context("connecting to BigQuery")?;
                Ok(a.hold_crosslinks(&ctx.crosslinks()))
            })?;
            match quarb_bigquery::raw_query(
                s,
                &plan.sql,
                plan.order_table.as_deref(),
                plan.join_left
                    .as_ref()
                    .map(|(t, c)| (t.as_str(), c.as_slice())),
            ) {
                Ok((cols, rows)) => {
                    print_raw(&cols, rows, plan.record, plan.properties, oc)?;
                    return Ok(());
                }
                Err(e) => {
                    // The plan can fail catalog-side checks (e.g. the
                    // witness-JOIN uniqueness obligation): fall back to
                    // the scan, but never silently under --diagnostics=info.
                    note_info(
                        quarb::diagnostic::STATEMENT_NOT_PUSHED,
                        "query",
                        format!(
                            "the plan was not executed ({e}); scanning — the plan: {}",
                            plan.sql
                        ),
                    );
                }
            }
        }
        let adapter = match partial_plan(cli, query, None) {
            Some(pl) => {
                let a = BigqueryAdapter::connect_filtered(s, &pl.table, &pl.where_sql)
                    .context("connecting to BigQuery")?;
                match a.prefetch(&pl.table) {
                    Ok(()) => a,
                    Err(e) => {
                        note_info(
                            quarb::diagnostic::STATEMENT_NOT_PUSHED,
                            "prefilter",
                            format!("the prefilter was rejected ({e}); scanning"),
                        );
                        BigqueryAdapter::connect(s).context("connecting to BigQuery")?
                    }
                }
            }
            None => BigqueryAdapter::connect(s).context("connecting to BigQuery")?,
        };
        // the mount's `crosslinks=`, written in the URL's query
        // string: the references of these labels held in memory
        let mut adapter = adapter;
        adapter
            .hold_crosslinks(&ctx.crosslinks())
            .map_err(|e| anyhow::anyhow!("the database: {e}"))?;
        return run_relational(
            adapter,
            cli.no_graft,
            query,
            |a, n| a.locator(n),
            cli.kaiv.then_some(s),
            ctx,
            oc,
        );
    }

    // Athena: the S3 datalake's query layer. Billed by bytes
    // scanned, so the same ladder as BigQuery: full pushdown,
    // else a filtered fetch, else the lazy scan.
    if let Some(s) = path.as_ref().and_then(|p| p.to_str())
        && s.starts_with("athena:")
    {
        if let Some(plan) = pushdown_plan(cli, query, None, Door::PLAIN) {
            crosslinks_named(ctx, "the database", || {
                let mut a = AthenaAdapter::connect(s).context("connecting to Athena")?;
                Ok(a.hold_crosslinks(&ctx.crosslinks()))
            })?;
            match quarb_athena::raw_query(
                s,
                &plan.sql,
                plan.order_table.as_deref(),
                plan.join_left
                    .as_ref()
                    .map(|(t, c)| (t.as_str(), c.as_slice())),
            ) {
                Ok((cols, rows)) => {
                    print_raw(&cols, rows, plan.record, plan.properties, oc)?;
                    return Ok(());
                }
                Err(e) => {
                    note_info(
                        quarb::diagnostic::STATEMENT_NOT_PUSHED,
                        "query",
                        format!(
                            "the plan was not executed ({e}); scanning — the plan: {}",
                            plan.sql
                        ),
                    );
                }
            }
        }
        let adapter = match partial_plan(cli, query, None) {
            Some(pl) => {
                let a = AthenaAdapter::connect_filtered(s, &pl.table, &pl.where_sql)
                    .context("connecting to Athena")?;
                match a.prefetch(&pl.table) {
                    Ok(()) => a,
                    Err(e) => {
                        note_info(
                            quarb::diagnostic::STATEMENT_NOT_PUSHED,
                            "prefilter",
                            format!("the prefilter was rejected ({e}); scanning"),
                        );
                        AthenaAdapter::connect(s).context("connecting to Athena")?
                    }
                }
            }
            None => AthenaAdapter::connect(s).context("connecting to Athena")?,
        };
        // the mount's `crosslinks=`, written in the URL's query
        // string: the references of these labels held in memory
        let mut adapter = adapter;
        adapter
            .hold_crosslinks(&ctx.crosslinks())
            .map_err(|e| anyhow::anyhow!("the database: {e}"))?;
        return run_relational(
            adapter,
            cli.no_graft,
            query,
            |a, n| a.locator(n),
            cli.kaiv.then_some(s),
            ctx,
            oc,
        );
    }

    // A MySQL/MariaDB URL connects and introspects the database.
    if let Some(s) = path.as_ref().and_then(|p| p.to_str())
        && s.starts_with("mysql://")
    {
        if let Some(plan) =
            pushdown_plan(cli, query, Some(quarb_sql::Dialect::MySql), Door::CHECKED).filter(
                |plan| {
                    column_types_hold(
                        cli,
                        "query",
                        &plan.column_types,
                        plan.keyed_by.as_ref(),
                        || {
                            let tables: Vec<&str> =
                                plan.tables.iter().map(String::as_str).collect();
                            Ok(quarb_mysql::column_catalog(s, &tables)?)
                        },
                    )
                },
            )
        {
            crosslinks_named(ctx, "the database", || {
                let mut a = MysqlAdapter::connect(s).context("connecting to MySQL")?;
                Ok(a.hold_crosslinks(&ctx.crosslinks()))
            })?;
            match quarb_mysql::raw_query(
                s,
                &plan.sql,
                &plan_order(&plan),
                plan.join_left
                    .as_ref()
                    .map(|(t, c)| (t.as_str(), c.as_slice())),
            ) {
                Ok((cols, rows)) => {
                    print_raw(&cols, rows, plan.record, plan.properties, oc)?;
                    return Ok(());
                }
                Err(e) => {
                    // The plan can fail catalog-side checks (e.g. the
                    // witness-JOIN uniqueness obligation): fall back to
                    // the scan, but never silently under --diagnostics=info.
                    note_info(
                        quarb::diagnostic::STATEMENT_NOT_PUSHED,
                        "query",
                        format!(
                            "the plan was not executed ({e}); scanning — the plan: {}",
                            plan.sql
                        ),
                    );
                }
            }
        }
        let adapter = match partial_plan_with(cli, query, Some(quarb_sql::Dialect::MySql), true)
            .filter(|pl| {
                column_types_hold(cli, "prefilter", &pl.column_types, None, || {
                    Ok(quarb_mysql::column_catalog(s, &[pl.table.as_str()])?)
                })
            }) {
            Some(pl) => {
                let a = MysqlAdapter::connect_filtered(s, &pl.table, &pl.where_sql)
                    .context("connecting to MySQL")?;
                match a.prefetch(&pl.table) {
                    Ok(()) => a,
                    Err(e) => {
                        note_info(
                            quarb::diagnostic::STATEMENT_NOT_PUSHED,
                            "prefilter",
                            format!("the prefilter was rejected ({e}); scanning"),
                        );
                        MysqlAdapter::connect(s).context("connecting to MySQL")?
                    }
                }
            }
            None => MysqlAdapter::connect(s).context("connecting to MySQL")?,
        };
        // the mount's `crosslinks=`, written in the URL's query
        // string: the references of these labels held in memory
        let mut adapter = adapter;
        adapter
            .hold_crosslinks(&ctx.crosslinks())
            .map_err(|e| anyhow::anyhow!("the database: {e}"))?;
        return run_relational(
            adapter,
            cli.no_graft,
            query,
            |a, n| a.locator(n),
            cli.kaiv.then_some(s),
            ctx,
            oc,
        );
    }

    // A PostgreSQL connection string connects and materializes the
    // public schema (postgres:// / postgresql:// URL, or the
    // keyword form starting with host=).
    if let Some(s) = path.as_ref().and_then(|p| p.to_str())
        && is_pg_config(s)
    {
        if let Some(plan) = pushdown_plan(
            cli,
            query,
            Some(quarb_sql::Dialect::Postgres),
            Door::CHECKED,
        )
        .filter(|plan| {
            column_types_hold(
                cli,
                "query",
                &plan.column_types,
                plan.keyed_by.as_ref(),
                || {
                    let tables: Vec<&str> = plan.tables.iter().map(String::as_str).collect();
                    Ok(quarb_postgres::column_catalog(s, &tables)?)
                },
            )
        }) {
            crosslinks_named(ctx, "the database", || {
                let mut a = PostgresAdapter::connect(s).context("connecting to PostgreSQL")?;
                Ok(a.hold_crosslinks(&ctx.crosslinks()))
            })?;
            let sql =
                with_ordered_sums(&plan, |sums| quarb_postgres::float_sum_forms(s, sums).ok());
            match quarb_postgres::raw_query(
                s,
                &sql,
                &plan_order(&plan),
                plan.join_left
                    .as_ref()
                    .map(|(t, c)| (t.as_str(), c.as_slice())),
            ) {
                Ok((cols, rows)) => {
                    print_raw(&cols, rows, plan.record, plan.properties, oc)?;
                    return Ok(());
                }
                Err(e) => {
                    // The plan can fail catalog-side checks (e.g. the
                    // witness-JOIN uniqueness obligation): fall back to
                    // the scan, but never silently under --diagnostics=info.
                    note_info(
                        quarb::diagnostic::STATEMENT_NOT_PUSHED,
                        "query",
                        format!(
                            "the plan was not executed ({e}); scanning — the plan: {}",
                            plan.sql
                        ),
                    );
                }
            }
        }
        let adapter = match partial_plan_with(cli, query, Some(quarb_sql::Dialect::Postgres), true)
            .filter(|pl| {
                column_types_hold(cli, "prefilter", &pl.column_types, None, || {
                    Ok(quarb_postgres::column_catalog(s, &[pl.table.as_str()])?)
                })
            }) {
            Some(pl) => {
                let a = PostgresAdapter::connect_filtered(s, &pl.table, &pl.where_sql)
                    .context("connecting to PostgreSQL")?;
                match a.prefetch(&pl.table) {
                    Ok(()) => a,
                    Err(e) => {
                        note_info(
                            quarb::diagnostic::STATEMENT_NOT_PUSHED,
                            "prefilter",
                            format!("the prefilter was rejected ({e}); scanning"),
                        );
                        PostgresAdapter::connect(s).context("connecting to PostgreSQL")?
                    }
                }
            }
            None => PostgresAdapter::connect(s).context("connecting to PostgreSQL")?,
        };
        // the mount's `crosslinks=`, written in the URL's query
        // string: the references of these labels held in memory
        let mut adapter = adapter;
        adapter
            .hold_crosslinks(&ctx.crosslinks())
            .map_err(|e| anyhow::anyhow!("the database: {e}"))?;
        return run_relational(
            adapter,
            cli.no_graft,
            query,
            |a, n| a.locator(n),
            cli.kaiv.then_some(s),
            ctx,
            oc,
        );
    }

    // DuckDB databases, by extension.
    if let Some(p) = &path
        && p.extension()
            .and_then(|e| e.to_str())
            .is_some_and(|e| e.eq_ignore_ascii_case("duckdb") || e.eq_ignore_ascii_case("ddb"))
    {
        if let Some(plan) = pushdown_plan(cli, query, None, Door::CHECKED).filter(|plan| {
            column_types_hold(
                cli,
                "query",
                &plan.column_types,
                plan.keyed_by.as_ref(),
                || {
                    let tables: Vec<&str> = plan.tables.iter().map(String::as_str).collect();
                    Ok(quarb_duckdb::column_catalog(p, &tables)?)
                },
            )
        }) {
            crosslinks_named(ctx, &p.display().to_string(), || {
                let mut a = DuckdbAdapter::open(p).context("opening DuckDB database")?;
                Ok(a.hold_crosslinks(&ctx.crosslinks()))
            })?;
            let sql = with_ordered_sums(&plan, |sums| quarb_duckdb::float_sum_forms(p, sums).ok());
            match quarb_duckdb::raw_query(
                p,
                &sql,
                &plan_order(&plan),
                plan.join_left
                    .as_ref()
                    .map(|(t, c)| (t.as_str(), c.as_slice())),
            ) {
                Ok((cols, rows)) => {
                    print_raw(&cols, rows, plan.record, plan.properties, oc)?;
                    return Ok(());
                }
                Err(e) => {
                    // The plan can fail catalog-side checks (e.g. the
                    // witness-JOIN uniqueness obligation): fall back to
                    // the scan, but never silently under --diagnostics=info.
                    note_info(
                        quarb::diagnostic::STATEMENT_NOT_PUSHED,
                        "query",
                        format!(
                            "the plan was not executed ({e}); scanning — the plan: {}",
                            plan.sql
                        ),
                    );
                }
            }
        }
        // The leading conditions the database can take go ahead of
        // the scan, as on the other doors (0.71: this door opened
        // the file whole). No dialect: the conditions are the
        // portable ones, and a regex narrows by `strpos`.
        let adapter = match partial_plan_with(cli, query, None, true).filter(|pl| {
            column_types_hold(cli, "prefilter", &pl.column_types, None, || {
                Ok(quarb_duckdb::column_catalog(p, &[pl.table.as_str()])?)
            })
        }) {
            Some(pl) => {
                let a = DuckdbAdapter::open_filtered(p, &pl.table, &pl.where_sql)
                    .context("opening DuckDB database")?;
                match a.prefetch(&pl.table) {
                    Ok(()) => a,
                    Err(e) => {
                        note_info(
                            quarb::diagnostic::STATEMENT_NOT_PUSHED,
                            "prefilter",
                            format!("the prefilter was rejected ({e}); scanning"),
                        );
                        DuckdbAdapter::open(p).context("opening DuckDB database")?
                    }
                }
            }
            None => DuckdbAdapter::open(p).context("opening DuckDB database")?,
        };
        let mut adapter = adapter;
        adapter
            .hold_crosslinks(&ctx.crosslinks())
            .map_err(|e| anyhow::anyhow!("{}: {e}", p.display()))?;
        let src = p.display().to_string();
        return run_relational(
            adapter,
            cli.no_graft,
            query,
            |a, n| a.locator(n),
            cli.kaiv.then_some(src.as_str()),
            ctx,
            oc,
        );
    }

    // SQLite databases are binary: dispatch before the text read
    // (by extension, or the 16-byte magic).
    if let Some(p) = &path
        && is_sqlite(p)
    {
        if let Some(plan) =
            pushdown_plan(cli, query, Some(quarb_sql::Dialect::Sqlite), Door::CHECKED).filter(
                |plan| {
                    column_types_hold(
                        cli,
                        "query",
                        &plan.column_types,
                        plan.keyed_by.as_ref(),
                        || {
                            let tables: Vec<&str> =
                                plan.tables.iter().map(String::as_str).collect();
                            Ok(quarb_sqlite::column_catalog(p, &tables)?)
                        },
                    )
                },
            )
        {
            crosslinks_named(ctx, &p.display().to_string(), || {
                let mut a = SqliteAdapter::open_with_refs(p, &relational_refs(&cli.refs)?)
                    .context("opening SQLite database")?;
                Ok(a.hold_crosslinks(&ctx.crosslinks()))
            })?;
            match quarb_sqlite::raw_query(
                p,
                &plan.sql,
                &plan_order(&plan),
                plan.join_left
                    .as_ref()
                    .map(|(t, c)| (t.as_str(), c.as_slice())),
            ) {
                Ok((cols, rows)) => {
                    print_raw(&cols, rows, plan.record, plan.properties, oc)?;
                    return Ok(());
                }
                Err(e) => {
                    // The plan can fail catalog-side checks (e.g. the
                    // witness-JOIN uniqueness obligation): fall back to
                    // the scan, but never silently under --diagnostics=info.
                    note_info(
                        quarb::diagnostic::STATEMENT_NOT_PUSHED,
                        "query",
                        format!(
                            "the plan was not executed ({e}); scanning — the plan: {}",
                            plan.sql
                        ),
                    );
                }
            }
        }
        let refs = relational_refs(&cli.refs)?;
        let adapter = match partial_plan_with(cli, query, Some(quarb_sql::Dialect::Sqlite), true)
            .filter(|pl| {
                column_types_hold(cli, "prefilter", &pl.column_types, None, || {
                    Ok(quarb_sqlite::column_catalog(p, &[pl.table.as_str()])?)
                })
            }) {
            Some(pl) => {
                let a = SqliteAdapter::open_filtered_with_refs(p, &pl.table, &pl.where_sql, &refs)
                    .context("opening SQLite database")?;
                match a.prefetch(&pl.table) {
                    Ok(()) => a,
                    Err(e) => {
                        note_info(
                            quarb::diagnostic::STATEMENT_NOT_PUSHED,
                            "prefilter",
                            format!("the prefilter was rejected ({e}); scanning"),
                        );
                        SqliteAdapter::open_with_refs(p, &refs)
                            .context("opening SQLite database")?
                    }
                }
            }
            None => SqliteAdapter::open_with_refs(p, &refs).context("opening SQLite database")?,
        };
        let mut adapter = adapter;
        adapter
            .hold_crosslinks(&ctx.crosslinks())
            .map_err(|e| anyhow::anyhow!("{}: {e}", p.display()))?;
        let src = p.display().to_string();
        return run_relational(
            adapter,
            cli.no_graft,
            query,
            |a, n| a.locator(n),
            cli.kaiv.then_some(src.as_str()),
            ctx,
            oc,
        );
    }

    // Everything else — a directory, a document by extension or
    // content, an archive, a workbook, source code, a kaiv file —
    // opens through quarb-open, the same door every front-end
    // mounts through.
    if let Some(p) = &path {
        let src = p.display().to_string();
        let m = open_mount(cli.paths.first().expect("a target"), &OpenOpts::from(cli))?;
        return run(
            query,
            &m.adapter,
            |n| (m.render)(n),
            cli.kaiv.then_some(src.as_str()),
            ctx,
            oc,
        );
    }

    // No target: the document comes down the pipe (or, with none,
    // an expression head runs as a calculator).
    let text = match &path {
        Some(_) => unreachable!("a target opened above"),
        // No target and no pipe: an expression-headed query runs as
        // a calculator against a bare root; anything that navigates
        // is refused loudly (silent emptiness would read as data).
        None if std::io::stdin().is_terminal() => {
            if !quarb::is_calculator(&cli.query) {
                // A query that fails to parse should say so — not
                // masquerade as a missing target.
                quarb::expand(&cli.query, &quarb::Defs::default())?;
                anyhow::bail!(
                    "no input: give a directory, a file, or pipe a document to \
                     stdin — an expression head '= expr' runs without one; a \
                     --model file opens its own sources with `mount NAME: target;`"
                );
            }
            // The calculator: the bare root, the path `qc` runs.
            return calc_execute(query, cli.kaiv, oc);
        }
        None => read_prose(Path::new("-"), ctx)?,
    };
    // Strip a leading UTF-8 BOM (RFC 8259 permits ignoring it): it
    // otherwise breaks JSON parsing, since U+FEFF is not whitespace
    // so `trim_start` leaves it in place.
    let text = match text.strip_prefix('\u{feff}') {
        Some(rest) => rest.to_owned(),
        None => text,
    };
    let kaiv = cli.kaiv.then_some("stdin");
    // An empty pipe is no input: an expression head runs as the
    // calculator against the bare root, anything that navigates is
    // refused as with no input at all.
    if text.trim().is_empty() {
        if quarb::is_calculator(&cli.query) {
            return calc_execute(query, cli.kaiv, oc);
        }
        quarb::expand(&cli.query, &quarb::Defs::default())?;
        anyhow::bail!(
            "no input: standard input is empty — give a directory, a file, or pipe a document; \
             an expression head '= expr' runs without one"
        );
    }
    // Standard input is read as JSON by default and never sniffed
    // (spec: Grafting; the qua chapter): a notation flag names
    // anything else.
    let notation = stdin_notation(cli)?;
    stdin_dispatch(&notation, &text, query, kaiv, ctx, oc)
}

/// The notation the flags name for standard input: `--format NAME`
/// or one of the direct flags, JSON without any; two at once are
/// refused.
fn stdin_notation(cli: &Cli) -> anyhow::Result<String> {
    let direct: Vec<&str> = [
        (cli.in_yaml, "yaml"),
        (cli.in_toml, "toml"),
        (cli.in_xml, "xml"),
        (cli.in_html, "html"),
        (cli.in_markdown, "markdown"),
        (cli.in_text, "text"),
        (cli.in_fb2, "fb2"),
    ]
    .into_iter()
    .filter(|(on, _)| *on)
    .map(|(_, n)| n)
    .collect();
    anyhow::ensure!(
        direct.len() <= 1,
        "standard input has one notation: --{} and --{} name two",
        direct[0],
        direct[1]
    );
    Ok(match (&cli.stdin_format, direct.first()) {
        // the extension synonyms read as their notation (the
        // calculator profile has no compose crate to ask)
        (Some(f), _) => match f.trim().to_ascii_lowercase().as_str() {
            "yml" => "yaml".to_string(),
            "md" => "markdown".to_string(),
            "ndjson" => "jsonl".to_string(),
            "txt" | "plain" => "text".to_string(),
            "htm" => "html".to_string(),
            other => other.to_string(),
        },
        (None, Some(n)) => n.to_string(),
        (None, None) => "json".to_string(),
    })
}

/// Run `query` over standard input read as `notation`.
#[cfg(feature = "adapters")]
fn stdin_dispatch(
    notation: &str,
    text: &str,
    query: &str,
    kaiv: Option<&str>,
    ctx: &SourceCtx,
    oc: &OutputCtx,
) -> anyhow::Result<()> {
    match notation {
        "json" => {
            let adapter = JsonAdapter::parse(text).with_context(|| {
                "parsing standard input as JSON (its default notation; --format NAME or \
                 --yaml, --xml, --html, --text … name another)"
            })?;
            run(query, &adapter, |n| adapter.pointer(n), kaiv, ctx, oc)
        }
        "jsonl" => {
            let adapter = JsonAdapter::parse_lines(text).context("parsing JSON Lines")?;
            run(query, &adapter, |n| adapter.pointer(n), kaiv, ctx, oc)
        }
        "yaml" => {
            let adapter = quarb_yaml::parse(text).context("parsing YAML")?;
            run(query, &adapter, |n| adapter.pointer(n), kaiv, ctx, oc)
        }
        "toml" => {
            let adapter = quarb_toml::parse(text).context("parsing TOML")?;
            run(query, &adapter, |n| adapter.pointer(n), kaiv, ctx, oc)
        }
        "xml" => {
            let adapter = XmlAdapter::parse(text).context("parsing XML")?;
            run(query, &adapter, |n| adapter.locator(n), kaiv, ctx, oc)
        }
        "html" => {
            let adapter = HtmlAdapter::parse(text);
            run(query, &adapter, |n| adapter.locator(n), kaiv, ctx, oc)
        }
        "markdown" => {
            let adapter = quarb_markdown::parse(text);
            run(query, &adapter, |n| adapter.locator(n), kaiv, ctx, oc)
        }
        "text" => {
            let adapter = quarb_text::TextModel::parse_plain(text);
            run(query, &adapter, |n| adapter.locator(n), kaiv, ctx, oc)
        }
        "csv" | "tsv" => {
            let delim = if notation == "csv" { b',' } else { b'\t' };
            let adapter =
                CsvAdapter::parse_declared(text, delim, ctx.csv()).context("parsing CSV")?;
            run(query, &adapter, |n| adapter.locator(n), kaiv, ctx, oc)
        }
        "fb2" => {
            let adapter = quarb_text_koine::parse_xml_as(text, "fb2")
                .map_err(|e| anyhow::anyhow!("reading FictionBook: {e}"))?;
            run(query, &adapter, |n| adapter.locator(n), kaiv, ctx, oc)
        }
        "conllu" | "conllup" => {
            let adapter = quarb_text::TextModel::parse_conllu_text(text)
                .map_err(|e| anyhow::anyhow!("reading CoNLL-U: {e}"))?;
            run(query, &adapter, |n| adapter.locator(n), kaiv, ctx, oc)
        }
        "quarb" => {
            let adapter = quarb::reflect::QueryArbor::parse(text).context("parsing Quarb query")?;
            run(query, &adapter, |n| adapter.locator(n), kaiv, ctx, oc)
        }
        "kaiv" | "daiv" | "raiv" => {
            let adapter = parse_kaiv_ext(notation, text, None)?;
            run(query, &adapter, |n| adapter.locator(n), kaiv, ctx, oc)
        }
        "atd" | "atk" | "usfm" | "sfm" | "atrep" => {
            let adapter =
                AtrepAdapter::parse_str(text, Path::new(".")).context("parsing atrep document")?;
            run(query, &adapter, |n| adapter.locator(n), kaiv, ctx, oc)
        }
        ext if quarb_tree_sitter::supported(ext) => {
            let adapter = quarb_tree_sitter::TreeSitterAdapter::parse(text, ext)
                .map_err(|e| anyhow::anyhow!("parsing {ext} source: {e}"))?;
            run(query, &adapter, |n| adapter.locator(n), kaiv, ctx, oc)
        }
        other => anyhow::bail!(
            "--format {other}: no such notation; standard input reads as one of {}, conllu, \
             kaiv, quarb, an atrep extension (atd atk usfm) or a source grammar's name",
            quarb_compose::NOTATIONS.join(", ")
        ),
    }
}

/// Whether pushdown applies: enabled, not emitting kaiv (which
/// needs node provenance), not in --expand mode, not saving, and
/// not resident. A resident daemon must reach the serve loop with
/// the unfiltered adapter: a first-query full pushdown would answer
/// and exit before binding the socket, and a partial pushdown would
/// bake its WHERE into the standing arbor every later query reuses.
#[cfg(feature = "adapters")]
fn pushdown_applies(cli: &Cli) -> bool {
    // A planned or budgeted run goes through the engine, whose run
    // prices the query against the store's estimator and prints or
    // refuses before anything is read; a pushdown would execute the
    // SQL outright and drop both flags.
    // A model enriches the arbor (derived containers, references,
    // edges, weights) and is checked at load; the SQL plan sees the
    // bare source, so a modelled run goes through the engine.
    pushdown_off(cli).is_none()
}

/// What keeps the run from pushing anything to its source, as the
/// user wrote it: the option a refusal names (`OPTION_NOT_PUSHED`).
/// `None` where pushdown applies.
fn pushdown_off(cli: &Cli) -> Option<&'static str> {
    if cli.no_pushdown {
        Some("--no-pushdown")
    } else if cli.model.is_some() {
        Some("--model")
    } else if cli.plan {
        Some("--plan")
    } else if cli.budget.is_some() {
        Some("--budget")
    } else if cli.kaiv {
        Some("--kaiv")
    } else if cli.expand || cli.expand_1 {
        Some("--expand")
    } else if cli.save.is_some() {
        Some("--save")
    } else if cli.resident || cli.resident_serve {
        Some("--resident")
    } else {
        None
    }
}

/// The partial-pushdown plan (a WHERE for one table's fetch), with
/// --diagnostics=info commentary. Tried only after full pushdown refused.
#[cfg(feature = "adapters")]
fn partial_plan(
    cli: &Cli,
    query: &str,
    dialect: Option<quarb_sql::Dialect>,
) -> Option<quarb_sql::Partial> {
    // (BigQuery's and Athena's doors: no catalog is asked, so a
    // partial plan that compares two columns is not used)
    partial_plan_with(cli, query, dialect, false)
        .filter(|pl| !columns_compared_unchecked("prefilter", &pl.column_types))
}

/// Whether a plan's column-type assumptions hold in the driver's
/// catalog. SQLite and MySQL coerce a mixed comparison by rules of
/// their own, Quarb compares by value: a plan that compares a
/// column with a number is the scan's only on a numeric column,
/// and one that compares it with text only on a column that is
/// not. A catalog that cannot be read answers no, and the query
/// scans.
#[cfg(feature = "adapters")]
fn column_types_hold(
    _cli: &Cli,
    site: &str,
    types: &quarb_sql::ColumnTypes,
    keyed_by: Option<&(quarb_sql::Refusal, String)>,
    catalog: impl FnOnce() -> anyhow::Result<Vec<quarb_sql::ColumnFact>>,
) -> bool {
    if types.is_empty() {
        return true;
    }
    let unmet = match catalog() {
        Ok(c) => types.unmet(&c),
        Err(_) => types
            .numeric
            .iter()
            .chain(&types.text)
            .chain(&types.json)
            .cloned()
            .collect(),
    };
    if !unmet.is_empty() {
        // a prefilter the types decline is not used: the note that
        // told of it is taken back, so the account says one thing
        if site == "prefilter" {
            NOTES.with(|n| {
                let mut n = n.borrow_mut();
                if n.last()
                    .is_some_and(|d| d.code == PUSHED && d.site == "prefilter")
                {
                    n.pop();
                }
            });
        }
        // A sort, a fold or a distinct count by a column that is not
        // numeric is told under its own word: the database would run
        // it, by its collation or its own grouping of the texts.
        match keyed_by.filter(|(_, column)| unmet.contains(column)) {
            Some((word, column)) => {
                let reason = match word {
                    quarb_sql::Refusal::Sort => "ORDER BY collations differ per engine".to_string(),
                    quarb_sql::Refusal::Fold => format!(
                        "a fold by {column}, which is no numeric column: two texts that read \
                         as one number are one key to the engine and two to GROUP BY"
                    ),
                    _ => format!(
                        "a count of the distinct values of {column}, which is no numeric \
                         column: two texts that read as one number are one value to the \
                         engine and two to DISTINCT"
                    ),
                };
                if let Some(code) = word.code() {
                    note_info(code, site, format!("{reason}; scanning"));
                }
            }
            None => {
                // named by what the query holds: a column no
                // computation and no reducer assumed was compared
                let among = |list: &[String]| unmet.iter().any(|c| list.contains(c));
                let (computed, reduced) = (among(&types.computed), among(&types.reduced));
                let compared = unmet
                    .iter()
                    .any(|c| !types.computed.contains(c) && !types.reduced.contains(c));
                let mut words: Vec<&str> = Vec::new();
                if compared || !(computed || reduced) {
                    words.push("comparison");
                }
                if computed {
                    words.push("computation");
                }
                if reduced {
                    words.push("reducer");
                }
                let constructs = match words.as_slice() {
                    [a] => a.to_string(),
                    [a, b] => format!("{a} or {b}"),
                    _ => "comparison, computation or reducer".to_string(),
                };
                note_info(
                    quarb::diagnostic::TYPE_NOT_PUSHED,
                    site,
                    format!(
                        "the {constructs} on {} would follow the column's type where the \
                         scan follows the value; scanning",
                        unmet.join(", ")
                    ),
                )
            }
        }
    }
    unmet.is_empty()
}

/// A mount's `crosslinks=` names references by their labels, and a
/// label no reference carries is refused where the adapter holds
/// them. A query pushed whole opens no adapter, so its labels were
/// not looked at and a misspelled one passed in silence
/// (`shop.db?crosslinks=ordr` with a count answered the count).
/// Where the option is given and a whole plan is about to answer,
/// the labels are held against the catalog first: `hold` opens the
/// source and holds them, and its refusal ends the run as the
/// scan's would.
#[cfg(feature = "adapters")]
fn crosslinks_named(
    ctx: &SourceCtx,
    shown: &str,
    hold: impl FnOnce() -> anyhow::Result<Result<(), String>>,
) -> anyhow::Result<()> {
    if ctx.crosslinks().is_empty() {
        return Ok(());
    }
    hold()?.map_err(|e| anyhow::anyhow!("{shown}: {e}"))
}

/// Whether a plan compares two columns for a source whose catalog is
/// not asked, and so cannot be used; told once, under
/// TYPE_NOT_PUSHED. The engine compares two values by what they
/// read as and SQL by their types, which agree where both columns
/// are numeric: a typed database runs two text columns against each
/// other without complaint, so nothing but the catalog can say.
#[cfg(feature = "adapters")]
fn columns_compared_unchecked(site: &str, types: &quarb_sql::ColumnTypes) -> bool {
    if !types.columns_compared {
        return false;
    }
    if site == "prefilter" {
        NOTES.with(|n| {
            let mut n = n.borrow_mut();
            if n.last()
                .is_some_and(|d| d.code == PUSHED && d.site == "prefilter")
            {
                n.pop();
            }
        });
    }
    note_info(
        quarb::diagnostic::TYPE_NOT_PUSHED,
        site,
        "a comparison of two columns is pushed where both are numeric, and this source's \
         column types are not checked before a plan runs (SQLite's, MySQL's, PostgreSQL's \
         and DuckDB's are); scanning"
            .to_string(),
    );
    true
}

/// [`partial_plan`]; `keyed_hops` for an adapter that reads steps by
/// key, where crosslinks and resolutions keep the prefilter.
#[cfg(feature = "adapters")]
fn partial_plan_with(
    cli: &Cli,
    query: &str,
    dialect: Option<quarb_sql::Dialect>,
    keyed_hops: bool,
) -> Option<quarb_sql::Partial> {
    if !pushdown_applies(cli) {
        return None;
    }
    let plan = if keyed_hops {
        quarb_sql::partial_pushdown_keyed(query, dialect)
    } else {
        quarb_sql::partial_pushdown_explained(query, dialect)
    };
    match plan {
        Ok(p) => {
            note_info(
                PUSHED,
                "prefilter",
                format!(
                    "partial pushdown: WHERE {} on {}; the rest scans the filtered set",
                    p.where_sql, p.table
                ),
            );
            Some(p)
        }
        Err(e) => {
            note_not_pushed("prefilter", &e);
            None
        }
    }
}

/// The planner's account of a part it did not hand to the source:
/// the reason under its word's code (`SORT_NOT_PUSHED`; ruling
/// 2026-11-17, one word per reason). Three refusals tell nothing: a
/// partial plan with no leading condition (nothing was there to
/// push), a partial plan refused for the reason the whole plan was
/// just told under, and a query the planner could not parse (it
/// reads with the engine's own parser, and the engine's error says
/// it once).
#[cfg(feature = "adapters")]
fn note_not_pushed(site: &str, e: &quarb_sql::SqlError) {
    match e.not_pushed() {
        Some((word, reason)) => {
            if let Some(code) = word.code() {
                let message = format!("{reason}; scanning");
                // the partial plan refused for the whole plan's own
                // reason says nothing new
                let said = NOTES.with(|n| {
                    n.borrow()
                        .last()
                        .is_some_and(|d| d.code == code && d.message == message)
                });
                if !said {
                    note_info(code, site, message);
                }
            }
        }
        None if matches!(e, quarb_sql::SqlError::Syntax(_)) => {}
        None => note_info(
            quarb::diagnostic::OPERATOR_NOT_PUSHED,
            site,
            format!("{e}; scanning"),
        ),
    }
}

/// Whether the target's grafts read JSON under the property reading
/// (`?graft=json2` on the first target, a path as written taken as
/// is, as `take_encoding_option` takes it).
#[cfg(feature = "adapters")]
fn target_grafts_json2(cli: &Cli) -> bool {
    let Some(p) = cli.paths.first() else {
        return false;
    };
    if p.exists() {
        return false;
    }
    p.to_str()
        .and_then(|s| s.rsplit_once('?'))
        .is_some_and(|(_, query)| {
            query
                .split('&')
                .filter_map(|pair| pair.strip_prefix("graft="))
                .any(|label| quarb_compose::DataGraft::parse(label).is_ok_and(|g| g.json))
        })
}

/// What a database's door does with a plan beyond running its
/// statement.
#[cfg(feature = "adapters")]
#[derive(Clone, Copy)]
struct Door {
    /// The driver composes the plan's whole order (a join's second
    /// key, a sort, a reverse, a fold's groups, a LIMIT).
    orders: bool,
    /// The plan's column types are held against the catalog before
    /// it runs.
    catalog: bool,
}

#[cfg(feature = "adapters")]
impl Door {
    /// SQLite, MySQL, PostgreSQL and DuckDB: the order composed,
    /// and every assumption a plan makes of a column's type held
    /// against the catalog before it runs ([`column_types_hold`]).
    const CHECKED: Door = Door {
        orders: true,
        catalog: true,
    };
    /// The other drivers: the FROM table's key alone.
    const PLAIN: Door = Door {
        orders: false,
        catalog: false,
    };
}

/// The order a plan owes, as its driver takes it.
/// A plan's statement with its float sums in the source's ordered
/// form (`quarb_sql::FloatSum`): the door's driver says the form
/// for each sum, from its catalog, or nothing for a sum that stays
/// as written. A catalog that cannot be asked leaves the plan as it
/// is.
#[cfg(feature = "adapters")]
fn with_ordered_sums(
    plan: &quarb_sql::Pushdown,
    forms: impl FnOnce(&[quarb_relational::FloatSum<'_>]) -> Option<Vec<Option<String>>>,
) -> String {
    if plan.sums.is_empty() {
        return plan.sql.clone();
    }
    let asked: Vec<quarb_relational::FloatSum<'_>> = plan
        .sums
        .iter()
        .map(|s| quarb_relational::FloatSum {
            mean: s.mean,
            table: &s.table,
            column: &s.column,
            column_sql: &s.column_sql,
        })
        .collect();
    let Some(forms) = forms(&asked) else {
        return plan.sql.clone();
    };
    let mut sql = plan.sql.clone();
    for (s, form) in plan.sums.iter().zip(forms) {
        if let Some(form) = form {
            sql = sql.replace(&s.text, &form);
        }
    }
    sql
}

#[cfg(feature = "adapters")]
fn plan_order(plan: &quarb_sql::Pushdown) -> quarb_relational::PlanOrder<'_> {
    quarb_relational::PlanOrder {
        table: plan.order_table.as_deref(),
        then: plan.order_then.as_deref(),
        then_as: plan.order_then_as.as_deref(),
        first: plan.order_first.as_deref(),
        desc: plan.order_desc,
        groups: plan.order_groups,
        limit: plan.limit,
    }
}

/// The pushdown plan for a database input, with --diagnostics=info
/// commentary on stderr either way.
#[cfg(feature = "adapters")]
fn pushdown_plan(
    cli: &Cli,
    query: &str,
    dialect: Option<quarb_sql::Dialect>,
    door: Door,
) -> Option<quarb_sql::Pushdown> {
    if let Some(option) = pushdown_off(cli) {
        note_info(
            quarb::diagnostic::OPTION_NOT_PUSHED,
            "query",
            format!("nothing is pushed under {option}; scanning"),
        );
        return None;
    }
    match quarb_sql::pushdown_explained(query, dialect) {
        Ok(plan) => {
            // The plan as exported; what actually ran is reported
            // after execution (print_raw: the driver resolves the
            // ORDER BY key from the catalog), and the plan itself
            // is named where it does not run — the refusal branches.
            note_debug(PLAN, "query", || format!("pushdown plan: {}", plan.sql));
            // A plan that reads a JSON value as a child node of its
            // column (`/col/key::`) answers by the default reading's
            // spelling; under `?graft=json2` the scan lists no scalar
            // as a child and answers nothing there, so the plan is
            // not the scan's. (A prefilter is checked again by the
            // scan and stays.)
            if plan.column_types.json_children && target_grafts_json2(cli) {
                note_info(
                    quarb::diagnostic::GRAFT_NOT_PUSHED,
                    "query",
                    format!(
                        "the plan reads a JSON value as a child node of its column, and under \
                         ?graft=json2 a scalar is a property: write /col::key; scanning — the \
                         plan: {}",
                        plan.sql
                    ),
                );
                return None;
            }
            // A plan owes its rows in the scan's order. Beyond the
            // FROM table's key, which every driver appends, that is
            // the driver's to compose (`quarb_relational::
            // order_clause`): an every-witness JOIN's second key, a
            // sort's own terms, the keys turned for a reverse, the
            // least key of each group of a fold, a LIMIT after them.
            // A driver that appends the one key alone scans.
            if !door.orders {
                let owed = if plan.order_then.is_some() {
                    Some((
                        quarb::diagnostic::JOIN_NOT_PUSHED,
                        "an every-witness JOIN ('<=>*')",
                    ))
                } else if plan.order_first.is_some() || plan.order_desc {
                    Some((quarb::diagnostic::SORT_NOT_PUSHED, "a sort or a reverse"))
                } else if plan.order_groups {
                    Some((quarb::diagnostic::FOLD_NOT_PUSHED, "a fold"))
                } else if plan.limit.is_some() {
                    Some((quarb::diagnostic::TAKE_NOT_PUSHED, "a positional selection"))
                } else {
                    None
                };
                if let Some((code, what)) = owed {
                    note_info(
                        code,
                        "query",
                        format!(
                            "{what} is pushed where the driver keeps the plan's order \
                             (SQLite, DuckDB, PostgreSQL, MySQL), and this one does not; \
                             scanning — the plan: {}",
                            plan.sql
                        ),
                    );
                    return None;
                }
            }
            // A sort, a fold or a distinct count reads a numeric
            // column, and over a text one the database would run the
            // plan and answer another order or other groups: the
            // catalog must confirm the type first, and a source whose
            // catalog is not asked scans.
            if !door.catalog && columns_compared_unchecked("query", &plan.column_types) {
                return None;
            }
            if plan.keyed_by.is_some() && !door.catalog {
                note_info(
                    quarb::diagnostic::TYPE_NOT_PUSHED,
                    "query",
                    format!(
                        "a sort, a fold or a distinct count by {} is pushed where the column \
                         is numeric, and this source's column types are not checked before a \
                         plan runs (SQLite's, MySQL's, PostgreSQL's and DuckDB's are); \
                         scanning — the plan: {}",
                        plan.keyed_by
                            .as_ref()
                            .map_or("a column", |(_, c)| c.as_str()),
                        plan.sql
                    ),
                );
                return None;
            }
            Some(plan)
        }
        Err(e) => {
            note_not_pushed("query", &e);
            None
        }
    }
}

/// Print a pushed-down result the way the engine would: the bare
/// value of a one-column projection, a record where the query built
/// records (`record`: `| %(::title)` is a record of one field, which
/// was printed as the bare value) or the row has several columns;
/// under `properties` (`| %`) a row's record holds its cells that
/// are not NULL, as the node's own record does.
/// Buffered: one flush at the end, not a syscall per line.
#[cfg(feature = "adapters")]
fn print_raw(
    cols: &[String],
    rows: Vec<Vec<Value>>,
    record: bool,
    properties: bool,
    oc: &OutputCtx,
) -> anyhow::Result<()> {
    // Under --diagnostics=info: the statement the driver executed, verbatim,
    // ORDER BY and all. Recorded at execution because the key is
    // a per-adapter catalog lookup.
    if let Some(sql) = quarb_relational::take_executed() {
        note_info(PUSHED, "query", format!("pushdown: {sql}"));
    }
    // The same printer as the scan path, so --json / --jsonl /
    // --table / --csv hold whether or not the plan was pushed down.
    let values: Vec<Value> = rows
        .into_iter()
        .flat_map(|row| {
            if cols.len() <= 1 && !record {
                row
            } else {
                // `| %` is the record of a row's properties, and a
                // NULL cell is no property of its row
                vec![Value::Record(
                    cols.iter()
                        .cloned()
                        .zip(row)
                        .filter(|(_, v)| !(properties && matches!(v, Value::Null)))
                        .collect(),
                )]
            }
        })
        .collect();
    let mut out = OutSink::new(oc.encoding.clone(), oc.copy);
    emit_values(&mut out, values, oc.output, oc)?;
    out.finish()
}

/// Where a result goes: standard output, buffered — or, under
/// `@| encoding(LABEL)`, a buffer encoded as one text when the
/// query is done, so the bytes land as the encoding has them and
/// a character the encoding cannot represent refuses the whole
/// output (nothing half-written).
struct OutSink {
    buf: Vec<u8>,
    encoding: Option<(String, quarb::source::Escape)>,
    /// `| copy`: the buffer goes to the clipboard, not the screen,
    /// and one diagnostic line says so (spec: The clipboard).
    copy: Option<&'static str>,
}

impl OutSink {
    fn new(encoding: OutputEncoding, copy: Option<&'static str>) -> Self {
        OutSink {
            buf: Vec::new(),
            encoding,
            copy,
        }
    }

    fn finish(self) -> anyhow::Result<()> {
        use std::io::Write as _;
        if let Some(rendering) = self.copy {
            // the encoding is the screen's boundary; the clipboard
            // takes text
            let text = String::from_utf8(self.buf).context("the output is not UTF-8")?;
            return copy_to_clipboard(&text, rendering);
        }
        let stdout = std::io::stdout();
        let mut out = stdout.lock();
        match self.encoding {
            Some((label, escape)) => {
                let text = String::from_utf8(self.buf).context("the output is not UTF-8")?;
                let bytes = quarb::source::encode_with(&text, &label, escape)
                    .map_err(|e| anyhow::anyhow!("encoding({label}): {e}"))?;
                out.write_all(&bytes)?;
            }
            None => out.write_all(&self.buf)?,
        }
        out.flush()?;
        Ok(())
    }
}

/// Past this many bytes the terminal's clipboard (OSC 52) is no
/// longer the way: emulators and tmux cap the sequence, so a local
/// tool is preferred and the diagnostic becomes a warning pointing
/// at the redirection, the terminal user's tool.
const COPY_THRESHOLD: usize = 100_000;

/// `| copy` (spec: Output Commands, "The clipboard"): the rendered
/// output to the clipboard instead of the screen. The terminal's
/// own clipboard through OSC 52 (right through SSH and tmux) up to
/// the threshold, a local tool past it or where there is no
/// terminal (`wl-copy`, `xclip`, `xsel`, `pbcopy`, `clip.exe`), the
/// terminal's again when no tool exists; and always one diagnostic
/// in the output's place, shown at every level since it stands for
/// the output: an info `copied 1.2 MB as JSON`, a warning past the
/// threshold naming the redirection.
fn copy_to_clipboard(text: &str, rendering: &str) -> anyhow::Result<()> {
    let size = text.len();
    let tty = std::io::IsTerminal::is_terminal(&std::io::stderr());
    let small = size <= COPY_THRESHOLD;
    let route = if small && tty {
        osc52(text).map(|_| "the terminal's clipboard")
    } else {
        match clipboard_tool(text) {
            Ok(tool) => Ok(tool),
            Err(tool_error) if tty => osc52(text)
                .map(|_| "the terminal's clipboard (no clipboard tool; the terminal may cap a text this large)")
                .map_err(|e| anyhow::anyhow!("{tool_error}; {e}")),
            Err(e) => Err(e),
        }
    };
    let route = route.with_context(|| {
        format!(
            "copy: the output ({}) reached no clipboard; redirect it instead: qua … > file",
            human_size(size)
        )
    })?;
    let (severity, hint) = if small {
        (quarb::Severity::Info, String::new())
    } else {
        (
            quarb::Severity::Warning,
            "; in a terminal prefer the redirection, qua … > file".to_string(),
        )
    };
    let d = quarb::Diagnostic::new(
        severity,
        quarb::diagnostic::COPIED,
        "copy",
        format!(
            "copied {} as {rendering} to {route}{hint}",
            human_size(size)
        ),
    );
    // the output's stand-in: shown whatever the diagnostics level,
    // through the resident server's sink when one is set
    let sunk = DIAG_SINK.with(|s| {
        if let Some(v) = s.borrow_mut().as_mut() {
            v.push(d.to_string());
            true
        } else {
            false
        }
    });
    if !sunk {
        eprintln!("{}", painted_line(&d));
    }
    Ok(())
}

/// A byte count as people read it.
fn human_size(n: usize) -> String {
    if n < 1000 {
        format!("{n} B")
    } else if n < 1_000_000 {
        format!("{:.1} kB", n as f64 / 1000.0)
    } else {
        format!("{:.1} MB", n as f64 / 1_000_000.0)
    }
}

/// OSC 52: the text, base64, to the terminal's clipboard selection
/// (`c`), written to the controlling terminal so a redirected stdout
/// never carries it.
fn osc52(text: &str) -> anyhow::Result<()> {
    use std::io::Write as _;
    let payload = quarb::base64(text.as_bytes());
    let seq = format!("\x1b]52;c;{payload}\x07");
    let mut tty = std::fs::OpenOptions::new()
        .write(true)
        .open("/dev/tty")
        .context("no controlling terminal for OSC 52")?;
    tty.write_all(seq.as_bytes())?;
    tty.flush()?;
    Ok(())
}

/// The first clipboard tool that takes the text on its stdin:
/// `wl-copy` under Wayland, `xclip -selection clipboard` or `xsel
/// --clipboard --input` under X11, `pbcopy` on macOS, `clip.exe`
/// under WSL. The system clipboard every application pastes from,
/// never the X11 primary selection.
fn clipboard_tool(text: &str) -> anyhow::Result<&'static str> {
    use std::io::Write as _;
    use std::process::{Command, Stdio};
    let mut candidates: Vec<(&'static str, &'static [&'static str])> = Vec::new();
    if std::env::var_os("WAYLAND_DISPLAY").is_some() {
        candidates.push(("wl-copy", &[]));
    }
    candidates.push(("xclip", &["-selection", "clipboard"]));
    candidates.push(("xsel", &["--clipboard", "--input"]));
    candidates.push(("pbcopy", &[]));
    candidates.push(("clip.exe", &[]));
    candidates.push(("wl-copy", &[]));
    for (tool, args) in candidates {
        let Ok(mut child) = Command::new(tool)
            .args(args)
            .stdin(Stdio::piped())
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .spawn()
        else {
            continue;
        };
        // A tool that exits before it has read everything (no display,
        // a wrapper that fails) closes the pipe. Under the default
        // SIGPIPE disposition `cli_main` restores, that write killed
        // qua: exit 141, no message, the next tool never tried. The
        // signal is ignored for the write, which then fails with EPIPE.
        #[cfg(unix)]
        let previous = unsafe { libc::signal(libc::SIGPIPE, libc::SIG_IGN) };
        let wrote = match child.stdin.take() {
            Some(mut stdin) => stdin.write_all(text.as_bytes()).is_ok(),
            None => true,
        };
        #[cfg(unix)]
        unsafe {
            libc::signal(libc::SIGPIPE, previous);
        }
        let finished = child.wait().map(|st| st.success()).unwrap_or(false);
        if wrote && finished {
            return Ok(tool);
        }
    }
    Err(anyhow::anyhow!(
        "no clipboard tool found (wl-copy, xclip, xsel, pbcopy, clip.exe)"
    ))
}

/// Take `| copy` off the end of a query (spec: The clipboard): the
/// output boundary is the tool's, so the host that prints applies
/// it; the engine's [`quarb::take_copy`] knows the spelling and the
/// rendering's name.
fn take_copy(query: &str) -> (String, Option<&'static str>) {
    match quarb::take_copy(query) {
        Some((rest, rendering)) => (rest, Some(rendering)),
        None => (query.to_string(), None),
    }
}

impl std::io::Write for OutSink {
    fn write(&mut self, data: &[u8]) -> std::io::Result<usize> {
        self.buf.extend_from_slice(data);
        Ok(data.len())
    }
    fn flush(&mut self) -> std::io::Result<()> {
        Ok(())
    }
}

/// Take `@| encoding(LABEL)` off the end of a query: the output
/// boundary is the tool's, not the engine's (it has no byte
/// value). The command anywhere else reaches the executor and is
/// refused there. The command before it decides what a character
/// the encoding lacks becomes: after `@| json` / `@| jsonl` the
/// format's `\u` escape; after anything else the output is
/// refused at the first such character.
type OutputEncoding = Option<(String, quarb::source::Escape)>;

#[cfg(feature = "adapters")]
fn take_output_encoding(query: &str) -> anyhow::Result<(String, OutputEncoding)> {
    let trimmed = query.trim_end();
    let Some(head) = trimmed.strip_suffix(')') else {
        return Ok((query.to_string(), None));
    };
    let Some(open) = head.rfind('(') else {
        return Ok((query.to_string(), None));
    };
    let (before, label) = head.split_at(open);
    let before = before.trim_end();
    let Some(rest) = before.strip_suffix("encoding") else {
        return Ok((query.to_string(), None));
    };
    let rest = rest.trim_end();
    let Some(rest) = rest.strip_suffix("@|") else {
        return Ok((query.to_string(), None));
    };
    let label = label[1..].trim().trim_matches('"');
    quarb::source::encoding_for_label(label).ok_or_else(|| {
        anyhow::anyhow!(
            "encoding: unknown label {label:?} (labels are the Encoding Standard's: utf-8, \
             windows-1251, koi8-r, iso-8859-2, …)"
        )
    })?;
    let rest = rest.trim_end();
    let escape = match rest.rsplit("@|").next().map(str::trim) {
        Some(command)
            if command == "json" || command == "jsonl" || command.starts_with("json(") =>
        {
            quarb::source::Escape::Json
        }
        _ => quarb::source::Escape::Refuse,
    };
    Ok((rest.to_string(), Some((label.to_string(), escape))))
}

/// The web level (`web:`): a directory of built pages or an
/// archive of them (`.tar`, `.tgz`, `.zip`) as one site. Pages
/// join against `?base=<url>`, else the base read off a page's
/// canonical URL.
/// Run a query over an index-backed site store: the planner first
/// — a count outright, a candidate set the engine re-verifies, or
/// nothing (the scan) — with the pushdown account among the infos on stderr.
#[cfg(feature = "adapters")]
fn run_web_store<S: quarb_web::db::SqlStore + 'static>(
    cli: &Cli,
    query: &str,
    store: S,
    src: &str,
    ctx: &SourceCtx,
    oc: &OutputCtx,
) -> anyhow::Result<()> {
    use quarb_web::plan::{Plan, Rung};
    let model = oc.model.is_some();
    let plan = match pushdown_off(cli) {
        None => quarb_web::plan::plan(query, store.dialect(), model),
        Some(option) => Plan {
            rung: Rung::Scan,
            code: Some(quarb::diagnostic::OPTION_NOT_PUSHED),
            where_sql: String::new(),
            params: Vec::new(),
            reason: format!("nothing is pushed under {option}"),
            unverified: Vec::new(),
            limit: None,
        },
    };
    // A scan is told under the word of what stopped the push; one
    // with nothing refused (no predicate to push, a query that does
    // not parse: the engine's error says that) tells nothing.
    match (plan.rung == Rung::Scan, plan.code) {
        (true, Some(code)) => note_info(code, "web", format!("{}; scanning", plan.reason)),
        (true, None) => {}
        (false, _) => note_info(
            PUSHED,
            "web",
            format!("web: {} — {}", web_rung_name(&plan.rung), plan.reason),
        ),
    }
    if plan.rung != Rung::Scan {
        note_info(PUSHED, "web", format!("web: WHERE {}", plan.where_sql));
        note_debug(PLAN, "web", || {
            format!(
                "web: plan {}",
                store
                    .estimate_where(&plan.where_sql, &plan.params)
                    .map_or_else(|| "unknown".to_string(), |e| e.to_string())
            )
        });
    }
    match plan.rung {
        Rung::Full => {
            let n = store.count_where(&plan.where_sql, &plan.params);
            note_info(DELEGATED, "web", "web: the count answered by the store");
            println!("{n}");
            Ok(())
        }
        Rung::Prefilter => {
            let keys = match &plan.limit {
                Some(l) => store.keys_where_top(
                    &plan.where_sql,
                    &plan.params,
                    &l.column,
                    l.descending,
                    l.n,
                ),
                None => store.keys_where(&plan.where_sql, &plan.params),
            };
            note_info(
                DELEGATED,
                "web",
                format!("web: {} candidate(s)", keys.len()),
            );
            let adapter = quarb_web::WebAdapter::new(store).with_scope(keys);
            run(
                query,
                &adapter,
                |n| adapter.locator(n),
                cli.kaiv.then_some(src),
                ctx,
                oc,
            )
        }
        Rung::Scan => {
            let adapter = quarb_web::WebAdapter::new(store);
            run(
                query,
                &adapter,
                |n| adapter.locator(n),
                cli.kaiv.then_some(src),
                ctx,
                oc,
            )
        }
    }
}

/// The target as written when it carries the unit-suffix options
/// (`?autounits`, `?autounit=_km`), which open through the mount
/// path; None otherwise.
fn units_target(p: &Path) -> Option<PathBuf> {
    let s = p.to_str()?;
    if p.exists() {
        return None;
    }
    let (_, query) = s.rsplit_once('?')?;
    query
        .split('&')
        .any(|pair| {
            pair == "autounits"
                || pair == "autounit"
                || pair.starts_with("autounit=")
                || pair.starts_with("autounits=")
                || pair == "slugs"
                || pair.starts_with("slugs=")
                || pair.starts_with("units=")
                || pair == "sci"
                || pair.starts_with("sci=")
        })
        .then(|| p.to_path_buf())
}

/// The target with its root: `--root PATH` appended as `?root=PATH`,
/// or the target as written when it carries the option itself; None
/// when neither.
fn rooted_target(p: &Path, flag: Option<&str>) -> Option<PathBuf> {
    let s = p.to_str()?;
    if let Some(root) = flag {
        let sep = if s.contains('?') { '&' } else { '?' };
        return Some(PathBuf::from(format!("{s}{sep}root={root}")));
    }
    if p.exists() {
        return None;
    }
    let (_, query) = s.rsplit_once('?')?;
    query
        .split('&')
        .any(|pair| pair.starts_with("root="))
        .then(|| p.to_path_buf())
}

#[cfg(feature = "adapters")]
fn web_rung_name(r: &quarb_web::plan::Rung) -> &'static str {
    match r {
        quarb_web::plan::Rung::Full => "full",
        quarb_web::plan::Rung::Prefilter => "prefilter",
        quarb_web::plan::Rung::Scan => "scan",
    }
}

/// Run a relational query with JSON-column grafting: the adapter
/// is wrapped in `ComposeAdapter`, so a text column whose value
/// parses as JSON grafts an inner arbor navigable in place
/// (`/orders/*/data/user/age`). `outer_loc` is the wrapped
/// adapter's own locator, threaded through the bang-locator.
/// Under --no-graft the wrap is skipped: a text column stays the
/// server's own scalar.
#[cfg(feature = "adapters")]
fn run_relational<A: AstAdapter>(
    inner: A,
    no_graft: bool,
    query: &str,
    outer_loc: impl Fn(&A, NodeId) -> String,
    kaiv_source: Option<&str>,
    ctx: &SourceCtx,
    oc: &OutputCtx,
) -> anyhow::Result<()> {
    if no_graft {
        return run(
            query,
            &inner,
            |n| outer_loc(&inner, n),
            kaiv_source,
            ctx,
            oc,
        );
    }
    let adapter = ComposeAdapter::new(inner)
        .with_decoding(current_decoding(ctx)?)
        .with_csv_options(ctx.csv())
        .with_data_graft(ctx.data_graft())
        .with_string_reader(quarb_open::string_reader(ctx));
    run(
        query,
        &adapter,
        |n| adapter.locator(n, |o| outer_loc(adapter.outer(), o)),
        kaiv_source,
        ctx,
        oc,
    )
}

/// Run `query` against `adapter`, printing node locations (via
/// `render`) or projected values, one per line.
#[cfg(feature = "adapters")]
fn run<A: AstAdapter>(
    query: &str,
    adapter: &A,
    render: impl Fn(NodeId) -> String,
    kaiv_source: Option<&str>,
    ctx: &SourceCtx,
    oc: &OutputCtx,
) -> anyhow::Result<()> {
    // The source boundary's record (the single-input flow read one
    // source) answers `:::encoding` / `:::replaced` on the root.
    if let Some((encoding, replaced)) = ctx.take_record() {
        let sourced = quarb::source::Sourced {
            inner: quarb_model::Borrowed(adapter),
            encoding,
            replaced,
        };
        return run_modelled(query, &sourced, render, kaiv_source, oc);
    }
    run_modelled(query, adapter, render, kaiv_source, oc)
}

#[cfg(feature = "adapters")]
fn run_modelled<A: AstAdapter>(
    query: &str,
    adapter: &A,
    render: impl Fn(NodeId) -> String,
    kaiv_source: Option<&str>,
    oc: &OutputCtx,
) -> anyhow::Result<()> {
    // A --model file enriches every source with derived structure,
    // and its derived nodes render through the composed locator.
    if let Some(model) = oc.model.clone() {
        let documents = model.nodes.iter().any(|n| n.trait_name == "document");
        let enriched = quarb_model::ModelAdapter::new(quarb_model::Borrowed(adapter), model);
        enriched
            .check()
            .map_err(|e| anyhow::anyhow!("reading the model: {e}"))?;
        let base_render = &render;
        if documents {
            // a node constructor whose role wears the trait
            // `document` declares a corpus (spec: The Corpus
            // Reading): each member's text is read as prose, its
            // other keys declared, and the member serves the corpus
            // commands like a mounted document
            let reader: quarb_compose::DocumentNodes<
                quarb_model::ModelAdapter<quarb_model::Borrowed<'_>>,
            > = std::rc::Rc::new(|m, n| {
                let (text, declared) = m.document_member(n)?;
                let path = m.locator(n, |_| String::new());
                let doc = quarb_open::document_of(&text, &path, &declared);
                let ctx = SourceCtx::default();
                Some(
                    quarb_open::finish_corpus(
                        doc,
                        None,
                        None,
                        None,
                        &[],
                        None,
                        None,
                        None,
                        None,
                        false,
                        "corpus",
                        &ctx,
                    )
                    .unwrap_or_else(|_| quarb_open::document_of(&text, &path, &declared)),
                )
            });
            let composed = ComposeAdapter::new(enriched)
                .with_document_graft(quarb_compose::DocumentGraft::Text)
                .with_document_nodes(reader)
                .with_string_reader(quarb_open::string_reader(&SourceCtx::default()));
            let model_render =
                |n: NodeId| composed.locator(n, |o| composed.outer().locator(o, base_render));
            return run_dispatch(query, &composed, model_render, kaiv_source, oc);
        }
        let model_render = |n: NodeId| enriched.locator(n, base_render);
        return run_dispatch(query, &enriched, model_render, kaiv_source, oc);
    }
    run_dispatch(query, adapter, render, kaiv_source, oc)
}

/// The resident check and wrap chain, shared by the plain and
/// model-enriched paths.
#[cfg(feature = "adapters")]
fn run_dispatch<A: AstAdapter>(
    query: &str,
    adapter: &A,
    render: impl Fn(NodeId) -> String,
    kaiv_source: Option<&str>,
    oc: &OutputCtx,
) -> anyhow::Result<()> {
    // Every adapter dispatch funnels through here — which makes it
    // the one place a resident session takes over: the adapter is
    // built and materialized, so instead of answering once and
    // exiting, serve queries against it until the TTL.
    #[cfg(all(unix, feature = "adapters"))]
    if let Some((sock, ttl, pinned)) = oc.resident.clone() {
        return resident_serve_loop(adapter, render, &sock, ttl, pinned, oc);
    }
    run_wrapped(query, adapter, &render, kaiv_source, oc)
}

impl OutputCtx {
    /// The options one query runs under: the flags (--allow-shell,
    /// --quantifier-bound, --frontier-bound, --reproducible), the invocation instant
    /// (always bound in the CLI: --now, or one startup clock read),
    /// the output locale's collation, the session's sentence bonds.
    fn run_opts(&self) -> quarb::Run {
        quarb::Run {
            now: Some(self.now),
            allow_shell: self.allow_shell,
            session: Some(self.session.clone()),
            environments: self.environments.clone(),
            libraries: self.libraries.clone(),
            quantifier_bound: self.quant_bound,
            frontier_bound: self.front_bound,
            graph_bound: self.graph_bound,
            debug: self.session.borrow().diagnostics == quarb::Severity::Debug,
            reproducible: self.reproducible,
            collation: self.locale.map(|(l, _)| l.tag.to_string()),
            budget: self.budget.clone(),
            plan: self.plan,
            topic: self.topic.clone(),
            ..quarb::Run::ambient()
        }
    }

    /// The diagnostics a run raised beside its answer, on stderr,
    /// down to the level in force (`--diagnostics`; `session(--diagnostics=…)`
    /// shows the infos as well), in raising order, each on its own
    /// line as `SEVERITY CODE (site): message`.
    fn report_diagnostics(&self, diagnostics: &[quarb::Diagnostic]) {
        // The level: the session's setting (`session(--diagnostics=…)`
        // in the query sets it; the switch seeded it). The
        // diagnostics are the one channel: `--diagnostics=info` shows
        // the pushdown's account where `--explain` once did.
        let level = self.session.borrow().diagnostics;
        // the tool's own notes around the run come first: the
        // planner's account, the locale in force
        // and before them what the mounts raised (a sheet a workbook
        // could not read), told with the first run reported
        let shown: Vec<quarb::Diagnostic> = quarb::take_at_mount()
            .into_iter()
            .chain(take_notes())
            .chain(diagnostics.iter().cloned())
            .filter(|d| d.severity.shown_at(level))
            .collect();
        if shown.is_empty() {
            return;
        }
        // Under the resident server the lines travel to the client
        // with the answer, plain (the client's stderr decides its
        // own colour); otherwise they go to stderr here, the
        // severity word painted when colour is on.
        let sunk = DIAG_SINK.with(|s| {
            if let Some(v) = s.borrow_mut().as_mut() {
                v.extend(shown.iter().map(|d| d.to_string()));
                true
            } else {
                false
            }
        });
        if !sunk {
            for d in &shown {
                eprintln!("{}", painted_line(d));
            }
        }
    }

    /// The notes the tool raised with no run to report them under,
    /// and what the mounts raised that no run of the engine told (a
    /// plan the source answered opens none).
    fn flush_notes(&self) {
        for d in quarb::take_at_mount() {
            note(d);
        }
        if NOTES.with(|n| n.borrow().is_empty()) {
            return;
        }
        self.report_diagnostics(&[]);
    }

    /// The unresolved references a run left, and the folder leaves
    /// a reading refused (they answer null): infos, reported with
    /// the run's diagnostics.
    fn explain_refs(&self, refs: &[String]) {
        #[cfg(feature = "adapters")]
        let notes = quarb_open::take_notes();
        #[cfg(not(feature = "adapters"))]
        let notes: Vec<String> = Vec::new();
        for r in refs {
            note_info(
                UNRESOLVED,
                "query",
                format!("unresolved external reference: {r} (mount it, or declare a tree for it)"),
            );
        }
        for n in notes {
            note_info(READING, "mount", n);
        }
    }
}

/// `--budget nodes=N,bytes=N,requests=N[,strict]`.
fn parse_budget(text: &str) -> anyhow::Result<quarb::plan::Budget> {
    quarb::plan::Budget::parse(text).map_err(|e| anyhow::anyhow!("--{e}"))
}

/// Execution for one query under the run's options — `run` for the
/// one-shot path, and per-query inside a resident session.
fn run_wrapped<A: AstAdapter>(
    query: &str,
    adapter: &A,
    render: impl Fn(NodeId) -> String,
    kaiv_source: Option<&str>,
    oc: &OutputCtx,
) -> anyhow::Result<()> {
    note_debug(MOUNT, kaiv_source.unwrap_or("input"), || {
        format!("mounted through {}", std::any::type_name::<A>())
    });
    let run = oc.run_opts();
    // --expand with an input: expansion with the dataset at hand,
    // so data-aware macros (&name!) can read it.
    if oc.expand_1 {
        for t in quarb::expand_first_with(query, &quarb::Defs::default(), adapter, &run)
            .context("expanding the query")?
        {
            println!("{t}");
        }
        return Ok(());
    }
    if oc.expand {
        println!(
            "{}",
            quarb::expand_with(query, &quarb::Defs::default(), adapter, &run)
                .context("expanding the query")?
        );
        return Ok(());
    }
    let parsed = quarb::Query::parse_with(query, &quarb::Defs::default(), adapter, &run)?;
    if oc.plan {
        print!("{}", parsed.plan(adapter).to_kaiv(query));
        return Ok(());
    }
    let run_query = |q: &quarb::Query| -> anyhow::Result<quarb::Outcome> {
        Ok(if oc.calc {
            q.run_calc(&run)?
        } else {
            q.run(adapter, &run)?
        })
    };
    if let Some(source) = kaiv_source {
        let rows = if oc.calc {
            parsed.run_traced_prov_calc(&run)?
        } else {
            parsed.run_traced_prov(adapter, &run)?
        };
        print!(
            "{}",
            emit_kaiv(
                &rows,
                source,
                &render,
                |n| quarb::resolved_provenance(adapter, n),
                oc.kaiv_origins,
            )?
        );
        return Ok(());
    }
    let save = oc.save.clone();
    if let Some((path, table)) = save {
        let out = run_query(&parsed)?;
        oc.explain_refs(&out.refs);
        oc.report_diagnostics(&out.diagnostics);
        let values = match out.result {
            QueryResult::Values(vs) => vs,
            QueryResult::Nodes(ns) => ns.into_iter().map(|n| Value::Str(render(n))).collect(),
        };
        let n = values.len();
        save_result(&path, &table, values)?;
        eprintln!("saved {n} row(s) to {}", path.display());
        return Ok(());
    }
    // Buffered: one flush at the end, not a syscall per line.
    let out = OutSink::new(oc.encoding.clone(), oc.copy);
    let mode = oc.output;
    // Under an output locale a closing `@| csv` / `@| pretty` is the
    // tool's to render: the rows come back as they stand before it.
    let outcome = match oc.locale.map(|(l, _)| l) {
        Some(_) if mode == Output::Quarb => run_query(&parsed.for_rendering())?,
        _ => run_query(&parsed)?,
    };
    let quarb::Outcome {
        result,
        closing,
        refs,
        diagnostics,
        ..
    } = outcome;
    // The unresolved references and the diagnostics follow the
    // result (the sink flushes first), as the transcripts read them.
    let printed = print_result(out, result, closing, render, oc);
    oc.explain_refs(&refs);
    oc.report_diagnostics(&diagnostics);
    printed
}

fn print_result(
    mut out: OutSink,
    result: QueryResult,
    closing: Option<quarb::ClosingTable>,
    render: impl Fn(NodeId) -> String,
    oc: &OutputCtx,
) -> anyhow::Result<()> {
    use std::io::Write as _;
    let mode = oc.output;
    if let (Some(t), Some(l)) = (&closing, oc.locale.map(|(l, _)| l)) {
        let rows = match result {
            QueryResult::Values(values) => values,
            QueryResult::Nodes(nodes) => nodes.into_iter().map(|n| Value::Str(render(n))).collect(),
        };
        let columns = (!t.columns.is_empty()).then_some(t.columns.as_slice());
        let text = match t.pretty {
            // `@| pretty`: floats to the digits, numeric columns
            // right-aligned (spec: Output Commands, draft 166)
            Some(precision) => quarb::tabulate_pretty(
                &rows,
                columns,
                t.delimiter.unwrap_or(l.csv_delimiter),
                &|v| l.cell(v),
                precision,
            ),
            None => quarb::tabulate_in(
                &rows,
                columns,
                t.csv,
                t.delimiter.unwrap_or(l.csv_delimiter),
                &|v| l.cell(v),
            ),
        };
        writeln!(out, "{text}")?;
        return out.finish();
    }
    let values = match result {
        QueryResult::Nodes(nodes) => {
            if mode == Output::Quarb {
                for node in nodes {
                    writeln!(out, "{}", render(node))?;
                }
                return out.finish();
            }
            nodes.into_iter().map(|n| Value::Str(render(n))).collect()
        }
        // a node among the values (a union's branch without a
        // projector) prints as a node does
        QueryResult::Values(values) => values
            .into_iter()
            .map(|v| match v {
                Value::Node(n) => Value::Str(render(NodeId(n.id))),
                v => v,
            })
            .collect(),
    };
    emit_values(&mut out, values, mode, oc)?;
    out.finish()
}

/// Write the values in the chosen output form.
fn emit_values(
    out: &mut impl std::io::Write,
    values: Vec<Value>,
    mode: Output,
    oc: &OutputCtx,
) -> anyhow::Result<()> {
    // A library value prints as its own text; every other output
    // form serializes its rows, each a value of the output.
    let values = match mode {
        Output::Quarb => values,
        _ => {
            let mut rows = Vec::with_capacity(values.len());
            for v in values {
                match v {
                    Value::Foreign(f) => match f.rows() {
                        Ok(Value::List(items)) => rows.extend(items.iter().cloned()),
                        Ok(other) => rows.push(other),
                        Err(_) => rows.push(Value::Str(f.display())),
                    },
                    Value::Table(t) => match t.rows_value() {
                        Value::List(items) => rows.extend(items.iter().cloned()),
                        other => rows.push(other),
                    },
                    other => rows.push(other),
                }
            }
            rows
        }
    };
    match mode {
        // The Quarb form: a scalar bare, a record `%(k = v; …)`, a
        // list `@(a; b)` — text that reads back as a query; under
        // an output locale, rendered in its numbers and dates.
        Output::Quarb => {
            let locale = oc.locale.map(|(l, _)| l);
            // the session's setting: `session(--pretty=always)` prints
            // every result through pretty, `structures` the lists,
            // records and tables (draft 166)
            let (mode, precision) = {
                let s = oc.session.borrow();
                (s.pretty, s.precision)
            };
            for value in values {
                if mode.applies(&value) {
                    writeln!(out, "{}", quarb::pretty_value(&value, precision))?;
                    continue;
                }
                match &locale {
                    Some(l) => writeln!(out, "{}", l.display(&value))?,
                    None => writeln!(out, "{}", value.display_form())?,
                }
            }
        }
        // One JSON document: the values as an array.
        Output::Json => {
            let items: Vec<String> = values.iter().map(Value::to_json).collect();
            writeln!(out, "[{}]", items.join(", "))?;
        }
        // JSON Lines: one document per line.
        Output::Jsonl => {
            for value in values {
                writeln!(out, "{}", value.to_json())?;
            }
        }
        // An aligned table, or CSV: records as columns.
        Output::Table => write_table(out, &values, false, oc)?,
        Output::Csv => write_table(out, &values, true, oc)?,
    }
    Ok(())
}

/// Records as columns, as the `@| pretty` and `@| csv` commands print
/// them: `--table` and `--csv` are the query with the command appended.
fn write_table(
    out: &mut impl std::io::Write,
    values: &[Value],
    csv: bool,
    oc: &OutputCtx,
) -> anyhow::Result<()> {
    match oc.locale.map(|(l, _)| l) {
        Some(l) => writeln!(
            out,
            "{}",
            quarb::tabulate_in(values, None, csv, l.csv_delimiter, &|v| l.cell(v))
        )?,
        None => writeln!(out, "{}", quarb::tabulate(values, None, csv))?,
    }
    Ok(())
}

/// Decide the output locale by its layers, nearest first: --locale,
/// QUARB_LOCALE, the config file, the system locale (LC_ALL, then
/// LANG; C and POSIX are canonical), else canonical. A tag no table
/// covers is reported on stderr and renders canonically.
fn set_output_locale(
    cli: &Cli,
) -> anyhow::Result<Option<(quarb::locale::OutputLocale, &'static str)>> {
    let layers: [(&'static str, Option<String>); 4] = [
        ("--locale", cli.locale.clone()),
        ("QUARB_LOCALE", std::env::var("QUARB_LOCALE").ok()),
        ("config", config_locale()),
        (
            "system",
            std::env::var("LC_ALL")
                .ok()
                .filter(|v| !v.is_empty())
                .or_else(|| std::env::var("LANG").ok()),
        ),
    ];
    let chosen = layers
        .iter()
        .find_map(|(layer, tag)| tag.as_deref().map(|t| (*layer, t.to_string())));
    let Some((layer, tag)) = chosen else {
        return Ok(None);
    };
    if quarb::locale::is_canonical(&tag) {
        return Ok(None);
    }
    match quarb::locale::for_tag(&tag) {
        Some(mut l) => {
            l.grouping = cli.grouping
                || std::env::var("QUARB_GROUPING").is_ok_and(|v| v == "1" || v == "true")
                || config_output("grouping").is_some_and(|v| v.as_bool() == Some(true));
            note_info(LOCALE, layer, format!("locale: {tag} (from {layer})"));
            return Ok(Some((l, layer)));
        }
        // a tag without rules is replaced by the canonical form,
        // warned about whatever layer named it (spec: Diagnostics)
        None => {
            note_warning(
                LOCALE_UNKNOWN,
                layer,
                format!(
                    "locale: {tag} (from {layer}) has no rendering rules; canonical (shipped: {}; C is the canonical form)",
                    quarb::locale::SHIPPED.join(", ")
                ),
            );
        }
    }
    Ok(None)
}

/// `[output] locale = "…"` in ~/.quarb/config.toml (QUARB_CONFIG
/// names another file).
fn config_locale() -> Option<String> {
    config_output("locale")?.as_str().map(str::to_string)
}

/// One key of the config file's `[output]` table.
fn config_output(key: &str) -> Option<toml::Value> {
    let path = match std::env::var_os("QUARB_CONFIG") {
        Some(p) => PathBuf::from(p),
        None => std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".quarb/config.toml"))?,
    };
    let text = std::fs::read_to_string(path).ok()?;
    let doc: toml::Table = toml::from_str(&text).ok()?;
    doc.get("output")?.get(key).cloned()
}

/// Materialize a result: `.json` writes a JSON array (records as
/// objects — the shape the JSON adapter reads back); anything else
/// writes a SQLite table (each record a row, its fields the columns,
/// scalars a `value` column). Refuses to overwrite: an existing .json file,
/// or an existing table in a .db.
fn save_result(path: &Path, table: &str, values: Vec<Value>) -> anyhow::Result<()> {
    let ext = path
        .extension()
        .and_then(|e| e.to_str())
        .unwrap_or("")
        .to_ascii_lowercase();
    if ext == "json" {
        use std::io::Write as _;
        // create_new: the existence check and the create are one
        // atomic open, so a concurrent writer cannot slip between.
        let mut f = match std::fs::OpenOptions::new()
            .create_new(true)
            .write(true)
            .open(path)
        {
            Ok(f) => f,
            Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
                anyhow::bail!("{} already exists (refusing to overwrite)", path.display())
            }
            Err(e) => return Err(e).with_context(|| format!("creating {}", path.display())),
        };
        let items: Vec<String> = values.iter().map(|v| v.to_json()).collect();
        f.write_all(
            format!(
                "[{}]
",
                items.join(
                    ",
 "
                )
            )
            .as_bytes(),
        )?;
        return Ok(());
    }
    // SQLite: the records' fields are the columns (first-appearance union),
    // scalars a single `value` column.
    let mut conn =
        rusqlite::Connection::open(path).with_context(|| format!("opening {}", path.display()))?;
    let exists: i64 = conn.query_row(
        "SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name = ?1",
        [table],
        |r| r.get(0),
    )?;
    if exists > 0 {
        anyhow::bail!(
            "table '{table}' already exists in {} (refusing to overwrite)",
            path.display()
        );
    }
    let mut columns: Vec<String> = Vec::new();
    let all_records = values.iter().all(|v| matches!(v, Value::Record(_)));
    if all_records {
        for v in &values {
            if let Value::Record(fields) = v {
                for (k, _) in fields {
                    if !columns.contains(k) {
                        columns.push(k.clone());
                    }
                }
            }
        }
    }
    if columns.is_empty() {
        columns.push("value".to_string());
    }
    // Identifiers come from the data (record field names can be
    // arbitrary document keys): escape embedded quotes rather than
    // letting them break — or rewrite — the statement.
    let ident = |name: &str| format!("\"{}\"", name.replace('"', "\"\""));
    let decl: Vec<String> = columns.iter().map(|c| ident(c)).collect();
    // One transaction for the whole save: per-row implicit
    // transactions would fsync every insert.
    let tx = conn.transaction()?;
    tx.execute(
        &format!("CREATE TABLE {} ({})", ident(table), decl.join(", ")),
        [],
    )?;
    let placeholders: Vec<String> = (1..=columns.len()).map(|i| format!("?{i}")).collect();
    {
        let mut stmt = tx.prepare(&format!(
            "INSERT INTO {} ({}) VALUES ({})",
            ident(table),
            decl.join(", "),
            placeholders.join(", ")
        ))?;
        for v in values {
            let row: Vec<rusqlite::types::Value> = if all_records {
                let Value::Record(fields) = &v else {
                    unreachable!()
                };
                columns
                    .iter()
                    .map(|c| {
                        fields
                            .iter()
                            .find(|(k, _)| k == c)
                            .map(|(_, v)| sqlite_value(v))
                            .unwrap_or(rusqlite::types::Value::Null)
                    })
                    .collect()
            } else {
                vec![sqlite_value(&v)]
            };
            stmt.execute(rusqlite::params_from_iter(row))?;
        }
    }
    tx.commit()?;
    Ok(())
}

fn sqlite_value(v: &Value) -> rusqlite::types::Value {
    match v {
        Value::Null => rusqlite::types::Value::Null,
        Value::Bool(b) => rusqlite::types::Value::Integer(*b as i64),
        Value::Int(n) => rusqlite::types::Value::Integer(*n),
        Value::Float(f) => rusqlite::types::Value::Real(*f),
        other => rusqlite::types::Value::Text(other.to_string()),
    }
}

/// The `--kaiv` document: every result under `/@results/N` — a
/// record spreading as its namespace's fields, a node as `::node`
/// (its locator), anything else as `::value` — with each leaf line
/// carrying the provenance of the value it holds: the value's
/// origins (where it was read, per field for a record, per item for
/// a list), resolved through the adapter's layers into kaiv
/// entries, `;`-separated, deduplicated by (source, dpid) with the
/// newest instant kept, at most `cap` named before the elision
/// marker `;+N` counts the rest. A value with no recorded origin
/// (a literal, a count) is attributed to its row's node. Sources
/// are declared once each, `.?srcN uri`, in first-appearance
/// order; `q` names the query's own source (the fallback). Lists of
/// records place their fields under `/@results/N/@tags/M` (records
/// open namespaces, lists open arrays); quantities keep their unit
/// (`!float:B`). What canonical kaiv cannot hold on a flat line
/// falls back to its JSON text (quoted, single-line) as `str`.
fn emit_kaiv(
    rows: &[quarb::Traced],
    source: &str,
    render: impl Fn(NodeId) -> String,
    prov_of: impl Fn(NodeId) -> quarb::ProvenanceList,
    cap: usize,
) -> anyhow::Result<String> {
    use kaiv::{KaivBuilder, ProvEntry, Provenance};
    use quarb::Prov;
    use quarb::kaiv_out::{ProvCtx, ident_of, kaiv_put};
    let mut b = KaivBuilder::new();
    b.declare_source("q", source).map_err(kaiv_err)?;
    // Every node a leaf may be attributed to, in first-appearance
    // order: the row's own, then its value's origins, tree-walked.
    fn origin_nodes(p: &Prov, out: &mut Vec<NodeId>) {
        out.extend(p.origins.positions().map(quarb::NodeId::from));
        for (_, q) in p.parts.iter() {
            origin_nodes(q, out);
        }
    }
    let mut nodes: Vec<NodeId> = Vec::new();
    for r in rows {
        nodes.push(r.node);
        origin_nodes(&r.prov, &mut nodes);
    }
    // Declare each distinct source once under a short id — the
    // point of the declaration is that the URI travels once, up
    // top. A source the builder refuses maps to the fallback.
    let mut source_ids: std::collections::HashMap<String, String> =
        std::collections::HashMap::new();
    for n in &nodes {
        for p in prov_of(*n).entries {
            let Some(src) = p.source else { continue };
            if source_ids.contains_key(&src) {
                continue;
            }
            let id = format!("src{}", source_ids.len() + 1);
            let id = match b.declare_source(&id, &src) {
                Ok(()) => id,
                Err(_) => "q".to_string(),
            };
            source_ids.insert(src, id);
        }
    }
    // One kaiv entry per (origin node, recorded entry): the declared
    // source id (else `q`), the instant in the canonical dashed form
    // (an instant the form cannot hold — a year outside 0000–9999 —
    // is dropped rather than emitted invalid), and the dpid — the
    // source's own, else the node's path within the source (the
    // rule for a source without keys), else the sanitized locator;
    // never one that only repeats the source (a filesystem node's
    // source is its path, and a document's root is `/`).
    let entry_of = |n: NodeId, p: &quarb::Provenance| -> ProvEntry {
        ProvEntry {
            source: p
                .source
                .as_ref()
                .and_then(|s| source_ids.get(s).cloned())
                .unwrap_or_else(|| "q".to_string()),
            timestamp: p
                .instant
                .map(|(secs, _, _)| quarb::temporal::format_instant(secs, 0, Some(0)))
                .filter(|t| t.len() == 20),
            dpid: p.dpid.as_deref().map(ident_of).or_else(|| {
                let loc = match p.path.as_deref() {
                    Some(path) if path != "/" => ident_of(path),
                    _ => ident_of(&render(n)),
                };
                match &p.source {
                    Some(s) if ident_of(s) == loc => None,
                    _ => Some(loc),
                }
            }),
        }
    };
    for (i, row) in rows.iter().enumerate() {
        // A leaf's prefix from its origin set: the entries in
        // first-read order, deduplicated by (source, dpid) keeping
        // the newest instant, bounded by `cap`; what the bound and
        // the origins' own records elide is counted. No origin at
        // all attributes the value to the row's node.
        let resolve = |o: &quarb::Origins| -> Option<Provenance> {
            let mut entries: Vec<ProvEntry> = Vec::new();
            let mut elided = o.more;
            let ns: Vec<NodeId> = if o.is_empty() {
                vec![row.node]
            } else {
                o.positions().map(quarb::NodeId::from).collect()
            };
            for n in ns {
                let list = prov_of(n);
                elided = elided.saturating_add(list.elided);
                let ps = if list.entries.is_empty() {
                    vec![quarb::Provenance::default()]
                } else {
                    list.entries
                };
                for p in ps {
                    let e = entry_of(n, &p);
                    match entries
                        .iter()
                        .position(|q| q.source == e.source && q.dpid == e.dpid)
                    {
                        // The dashed form orders as it reads.
                        Some(at) => {
                            if e.timestamp > entries[at].timestamp {
                                entries[at].timestamp = e.timestamp;
                            }
                        }
                        None if entries.len() < cap => entries.push(e),
                        None => elided = elided.saturating_add(1),
                    }
                }
            }
            Some(Provenance { entries, elided })
        };
        let ctx = ProvCtx {
            prov: Some(&row.prov),
            resolve: &resolve,
        };
        let base = format!("/@results/{i}");
        let mut used = std::collections::HashSet::new();
        match &row.topic {
            None => {
                let loc = render(row.node);
                kaiv_put(&mut b, &base, "node", &Value::Str(loc), &ctx, &mut used)
                    .map_err(anyhow::Error::msg)?;
            }
            Some(Value::Record(fields)) => {
                for (k, v) in fields {
                    let part = row.prov.part(k);
                    let fc = ProvCtx {
                        prov: Some(&part),
                        resolve: &resolve,
                    };
                    kaiv_put(&mut b, &base, k, v, &fc, &mut used).map_err(anyhow::Error::msg)?;
                }
            }
            Some(v) => {
                kaiv_put(&mut b, &base, "value", v, &ctx, &mut used).map_err(anyhow::Error::msg)?
            }
        }
    }
    b.finish().map_err(kaiv_err)
}

fn kaiv_err(e: kaiv::PipelineError) -> anyhow::Error {
    anyhow::anyhow!("emitting kaiv: {e}")
}

#[cfg(test)]
mod tests {
    use super::{split_alias, split_scheme_query};
    use std::path::{Path, PathBuf};

    #[test]
    fn mount_aliases_split() {
        assert_eq!(
            split_alias(Path::new("ga=bigquery://p/quarb_ga?account=a@b.c")),
            Some((
                "ga".to_string(),
                PathBuf::from("bigquery://p/quarb_ga?account=a@b.c")
            ))
        );
        assert_eq!(
            split_alias(Path::new("raw_2026-06=events.jsonl")),
            Some(("raw_2026-06".to_string(), PathBuf::from("events.jsonl")))
        );
        // Not aliases: no '=', empty target, non-name prefix.
        assert_eq!(split_alias(Path::new("events.jsonl")), None);
        assert_eq!(split_alias(Path::new("ga=")), None);
        // A mount name in another script.
        assert_eq!(
            split_alias(Path::new("толстой=corpus:anna-karenina.atd")),
            Some((
                "толстой".to_string(),
                PathBuf::from("corpus:anna-karenina.atd")
            ))
        );
        assert_eq!(split_alias(Path::new("2ga=x.json")), None);
        assert_eq!(split_alias(Path::new("a/b=x.json")), None);
    }

    #[test]
    fn scheme_prefixed_queries_split() {
        assert_eq!(
            split_scheme_query("github:/torvalds/linux::stars"),
            Some(("github:", "/torvalds/linux::stars"))
        );
        assert_eq!(
            split_scheme_query("gitlab:/tesslab//*<repo>"),
            Some(("gitlab:", "/tesslab//*<repo>"))
        );
        assert_eq!(
            split_scheme_query("k8s:/namespaces/*"),
            Some(("k8s:", "/namespaces/*"))
        );
        // Anchored targets, payload schemes, and plain queries
        // keep the two-argument form.
        assert_eq!(split_scheme_query("github:torvalds/linux"), None);
        assert_eq!(split_scheme_query("git:/repo"), None);
        assert_eq!(split_scheme_query("/a/b::c"), None);
    }

    fn row(n: u64, topic: Option<quarb::Value>) -> quarb::Traced {
        quarb::Traced {
            node: quarb::NodeId(n),
            topic,
            prov: quarb::Prov::default(),
        }
    }

    #[test]
    fn emit_kaiv_provenance_per_row() {
        use quarb::{NodeId, Provenance, ProvenanceList, Value};
        // Values with no recorded origin are attributed to their
        // row's node.
        let rows = vec![
            row(1, Some(Value::Int(7))),
            row(2, Some(Value::Int(9))),
            row(3, Some(Value::Int(11))),
        ];
        let render = |n: NodeId| format!("/row/{}", n.0);
        // Node 1: a full triple. Node 2: same source, no ts/dpid.
        // Node 3: nothing — falls back to `q` + locator dpid.
        let (secs, _, _) = quarb::temporal::parse_iso("2026-07-17T12:00:00Z").unwrap();
        let prov_of = move |n: NodeId| match n.0 {
            1 => Provenance {
                source: Some("https://sensors.example.com/1".into()),
                instant: Some((secs, 0, Some(0))),
                dpid: Some("req-42".into()),
                ..Default::default()
            },
            2 => Provenance {
                source: Some("https://sensors.example.com/1".into()),
                ..Default::default()
            },
            _ => Provenance::default(),
        };
        let out = super::emit_kaiv(
            &rows,
            "a.daiv, b.csv",
            render,
            |n| ProvenanceList::single(prov_of(n)),
            8,
        )
        .unwrap();
        // One declaration per distinct source, after the fallback.
        assert!(out.contains(".?q a.daiv, b.csv\n"));
        assert_eq!(out.matches("sensors.example.com").count(), 1);
        // The declared id is short (`src1`, first appearance); it
        // carries the dashed instant and the pass-through dpid on
        // row 0 (authored block form); row 1 shares the source but
        // falls back to its locator dpid; row 2 rides `q`.
        assert!(out.contains(".?src1 https://sensors.example.com/1\n"));
        assert!(
            out.contains("!int?src1@2026-07-17T12:00:00Z#req-42\nvalue=7"),
            "{out}"
        );
        assert!(out.contains("!int?src1#row-2\nvalue=9"));
        assert!(out.contains("!int?q#row-3\nvalue=11"));

        // A locator that only repeats the source (a filesystem node's
        // source is its own path) adds no dpid.
        let fs = super::emit_kaiv(
            &[row(1, Some(Value::Int(1)))],
            ".",
            |_| "/a/b.txt".to_string(),
            |_| {
                ProvenanceList::single(Provenance {
                    source: Some("/a/b.txt".into()),
                    ..Default::default()
                })
            },
            8,
        )
        .unwrap();
        assert!(fs.contains("!int?src1\nvalue=1"), "{fs}");
        assert!(!fs.contains('#'), "{fs}");

        // A record field opens a namespace; a list an array; a
        // quantity keeps its unit.
        let nested = super::emit_kaiv(
            &[row(
                1,
                Some(Value::record(vec![
                    (
                        "r".to_string(),
                        Value::record(vec![
                            ("n".to_string(), Value::Str("grc.atd".into())),
                            (
                                "size".to_string(),
                                Value::Quantity {
                                    value: 4025440.0,
                                    base: "B".into(),
                                    written: None,
                                },
                            ),
                        ]),
                    ),
                    (
                        "tags".to_string(),
                        Value::list(vec![Value::Str("a".into()), Value::Str("b".into())]),
                    ),
                ])),
            )],
            "u.json",
            |_| "/0".to_string(),
            |_| ProvenanceList::default(),
            8,
        )
        .unwrap();
        assert!(nested.contains("(/r)"), "{nested}");
        assert!(nested.contains("\nn=grc.atd\n"), "{nested}");
        assert!(nested.contains("!float:B?q#0\nsize=4025440\n"), "{nested}");
        assert!(nested.contains("@tags"), "{nested}");
        assert!(!nested.contains("{\"n\""), "{nested}");

        // Provenance-less rows emit exactly the pre-upgrade shape.
        let plain = super::emit_kaiv(
            &rows,
            "data.json",
            |n: NodeId| format!("/r/{}", n.0),
            |_| ProvenanceList::default(),
            8,
        )
        .unwrap();
        assert!(plain.contains(".?q data.json\n"));
        assert!(plain.contains("!int?q#r-1\nvalue=7"));
        assert!(!plain.contains(".?q-"));
    }

    fn prov_back(back: &quarb_kaiv::KaivAdapter, q: &str) -> Vec<String> {
        match quarb::run(q, back).unwrap() {
            quarb::QueryResult::Values(vs) => vs.iter().map(|v| v.to_string()).collect(),
            other => panic!("{other:?}"),
        }
    }

    #[test]
    fn emit_kaiv_per_field_and_plural() {
        use quarb::{NodeId, Origin, Origins, Prov, Provenance, ProvenanceList, Value};
        let (t1, _, _) = quarb::temporal::parse_iso("2026-07-17T12:00:00Z").unwrap();
        let (t2, _, _) = quarb::temporal::parse_iso("2026-07-18T12:00:00Z").unwrap();
        let prov_of = move |n: NodeId| {
            ProvenanceList::single(Provenance {
                source: Some(format!("https://s.example.com/{}", n.0)),
                instant: Some((if n.0 == 2 { t2 } else { t1 }, 0, Some(0))),
                dpid: Some(format!("row-{}", n.0)),
                ..Default::default()
            })
        };
        let at = |ns: &[u64]| {
            let mut o = Origins::default();
            for &n in ns {
                o.insert(Origin {
                    position: (NodeId(n)).into(),
                    command: 1,
                });
            }
            Prov::leaf(o)
        };
        // A record whose fields were read at different nodes: each
        // leaf line carries its own prefix; a field read from two
        // nodes lists both, `;`-separated, in first-read order.
        let rec = Value::record(vec![
            ("v".into(), Value::Int(1)),
            ("n".into(), Value::Int(2)),
            ("k".into(), Value::Int(3)),
        ]);
        let mut prov = Prov::record(vec![("v".into(), at(&[1])), ("n".into(), at(&[1, 2]))]);
        // A field with no origin of its own (a literal) rides the
        // row's node.
        std::sync::Arc::make_mut(&mut prov.parts).push(("k".into(), Prov::default()));
        let rows = vec![quarb::Traced {
            node: NodeId(3),
            topic: Some(rec),
            prov,
        }];
        let out = super::emit_kaiv(&rows, "t", |n| format!("/r/{}", n.0), prov_of, 8).unwrap();
        assert!(out.contains(".?src1 https://s.example.com/3\n"), "{out}");
        assert!(out.contains(".?src2 https://s.example.com/1\n"), "{out}");
        assert!(out.contains(".?src3 https://s.example.com/2\n"), "{out}");
        assert!(
            out.contains("!int?src2@2026-07-17T12:00:00Z#row-1\nv=1\n"),
            "{out}"
        );
        assert!(
            out.contains(
                "!int?src2@2026-07-17T12:00:00Z#row-1;src3@2026-07-18T12:00:00Z#row-2\nn=2\n"
            ),
            "{out}"
        );
        assert!(
            out.contains("!int?src1@2026-07-17T12:00:00Z#row-3\nk=3\n"),
            "{out}"
        );
        // The round trip: the emitted document re-mounts, and the
        // list-carrying field answers the same two entries — the
        // declared ids resolved back to their URIs.
        let back = quarb_kaiv::KaivAdapter::parse_kaiv(&out).unwrap();
        let prov = |q: &str| match quarb::run(q, &back).unwrap() {
            quarb::QueryResult::Values(vs) => vs.iter().map(|v| v.to_string()).collect::<Vec<_>>(),
            other => panic!("{other:?}"),
        };
        assert_eq!(
            prov("/@results/0/n:provenance"),
            [
                "?https://s.example.com/1@2026-07-17T12:00:00Z#row-1;https://s.example.com/2@2026-07-18T12:00:00Z#row-2"
            ]
        );
        assert_eq!(prov("/@results/0/n:instant"), ["2026-07-18T12:00:00Z"]);
        assert_eq!(prov("/@results/0/n:@provenance | count"), ["2"]);
        assert_eq!(prov("/@results/0/v:elided"), ["0"]);

        // The bound: a value read from twelve nodes names `cap` of
        // them and counts the rest; the engine's own bound adds to
        // the count.
        let mut o = Origins::default();
        for n in 1..=12 {
            o.insert(Origin {
                position: (NodeId(n)).into(),
                command: 1,
            });
        }
        assert_eq!(o.more, 12 - quarb::ORIGIN_CAP as u32);
        let rows = vec![quarb::Traced {
            node: NodeId(1),
            topic: Some(Value::Int(78)),
            prov: Prov::leaf(o),
        }];
        let out = super::emit_kaiv(&rows, "t", |n| format!("/r/{}", n.0), prov_of, 3).unwrap();
        let line = out.lines().find(|l| l.starts_with("!int?")).unwrap();
        assert_eq!(line.matches("#row-").count(), 3, "{line}");
        assert!(line.ends_with(";+9"), "{line}");
        let back = quarb_kaiv::KaivAdapter::parse_kaiv(&out).unwrap();
        assert_eq!(prov_back(&back, "/@results/0/value:elided"), ["9"]);
        assert_eq!(
            prov_back(&back, "/@results/0/value:@provenance | count"),
            ["3"]
        );

        // The same (source, dpid) read twice keeps one entry with
        // the newest instant.
        let same = move |_: NodeId| {
            ProvenanceList::single(Provenance {
                source: Some("https://s.example.com/x".into()),
                instant: None,
                dpid: Some("row-x".into()),
                ..Default::default()
            })
        };
        let rows = vec![quarb::Traced {
            node: NodeId(1),
            topic: Some(Value::Int(1)),
            prov: at(&[1, 2]),
        }];
        let out = super::emit_kaiv(&rows, "t", |n| format!("/r/{}", n.0), same, 8).unwrap();
        assert!(out.contains("!int?src1#row-x\nvalue=1\n"), "{out}");
    }

    /// A session is keyed on the build of the engine: the version,
    /// and the binary itself, so that a client is never answered by
    /// a session of another build (after an upgrade a standing
    /// session went on answering with the old engine).
    #[cfg(unix)]
    #[cfg(feature = "adapters")]
    #[test]
    fn a_session_is_of_one_build() {
        use super::engine_build_of;
        let dir = std::env::temp_dir().join(format!("qua-build-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let (a, b) = (dir.join("a"), dir.join("b"));
        std::fs::write(&a, b"one build").unwrap();
        std::fs::write(&b, b"one build").unwrap();
        // the same binary, twice: one build
        let first = engine_build_of("0.67.0", Some(&a));
        assert_eq!(first, engine_build_of("0.67.0", Some(&a)));
        assert!(first.starts_with("0.67.0 "), "{first}");
        // another version of it, another binary, the binary rewritten
        assert_ne!(first, engine_build_of("0.67.1", Some(&a)));
        assert_ne!(first, engine_build_of("0.67.0", Some(&b)));
        std::fs::write(&a, b"another build of it").unwrap();
        assert_ne!(first, engine_build_of("0.67.0", Some(&a)));
        // this process has one
        assert_eq!(super::engine_build(), super::engine_build());
        let _ = std::fs::remove_dir_all(&dir);
    }
}