quarb 0.48.0

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

/// Ruling #33 — the glob matcher behind pattern literals.
#[test]
fn glob_match_anchors_and_stars() {
    use PatSeg::{Lit, Star};
    let lit = |t: &str| Lit(t.to_string());
    // contains
    assert!(glob_match(&[Star, lit("web"), Star], "app-web-2"));
    assert!(!glob_match(&[Star, lit("web"), Star], "app"));
    // prefix / suffix anchor
    assert!(glob_match(&[lit("app"), Star], "app-web"));
    assert!(!glob_match(&[lit("app"), Star], "the-app"));
    assert!(glob_match(&[Star, lit(".gz")], "data.gz"));
    assert!(!glob_match(&[Star, lit(".gz")], "data.gz.bak"));
    // both-anchored multi-segment
    assert!(glob_match(&[lit("a"), Star, lit("z")], "abcz"));
    assert!(glob_match(&[lit("a"), Star, lit("z")], "az"));
    assert!(!glob_match(&[lit("a"), Star, lit("z")], "abc"));
    // the star spans empty
    assert!(glob_match(&[Star, lit("x"), Star], "x"));
    // backtracking: the first occurrence is not the match
    assert!(glob_match(&[Star, lit("ab"), Star, lit("b")], "ab-ab-b"));
    // no segments match only the empty text
    assert!(glob_match(&[] as &[PatSeg], ""));
    assert!(!glob_match(&[] as &[PatSeg], "x"));
    // multi-byte text walks char boundaries safely
    assert!(glob_match(&[Star, lit("gun")], "льюис gun"));
}

/// Ruling #33 — null never matches; `!=` therefore keeps holes.
#[test]
fn pattern_test_null_semantics() {
    use PatSeg::{Lit, Star};
    let p = [Star, Lit("x".into()), Star];
    assert!(!pattern_test(&p, &Value::Null));
    assert!(pattern_test(&p, &Value::Str("axb".into())));
    // non-string values test their string rendering, as `*=` does
    assert!(pattern_test(
        &[Star, Lit("42".into()), Star],
        &Value::Int(142)
    ));
}

#[test]
fn quantital_coercion_and_arith() {
    let sc: &dyn Fn(&str) -> Option<(f64, String)> = &crate::value::quantity::scale_expr;
    let q = |value: f64, base: &str, written: Option<(f64, &str)>| Value::Quantity {
        value,
        base: base.into(),
        written: written.map(|(v, u)| (v, u.to_string())),
    };
    let len = q(42000.0, "m", Some((42.0, "km")));
    // Coercion: unit text either side; a bare number carries no
    // dimension, so it is never equal to a length (spec:
    // Relations), whichever unit one might read it in.
    assert_eq!(
        value_cmp(&len, &Value::Str("5km".into()), sc),
        Some(Ordering::Greater)
    );
    assert!(value_eq(&len, &Value::Str("42km".into()), sc));
    assert!(!value_eq(&len, &Value::Float(42.0), sc));
    assert!(!value_eq(&len, &Value::Float(42000.0), sc));
    assert_eq!(value_cmp(&len, &Value::Float(42.0), sc), None);
    assert_eq!(
        value_cmp(&len, &Value::Str("30mi".into()), sc),
        Some(Ordering::Less)
    );
    // Dimension mismatch: the comparison fails rather than lies.
    let power = q(290.0, "m^2*kg/s^3", Some((290.0, "W")));
    assert_eq!(value_cmp(&power, &Value::Str("5km".into()), sc), None);
    assert!(!value_eq(&power, &Value::Str("5km".into()), sc));
    // kW text against a W-minted quantity — the motivating case.
    assert_eq!(
        value_cmp(&power, &Value::Str("0.2kW".into()), sc),
        Some(Ordering::Greater)
    );
    // Arithmetic: Q ± unit text, Q × n; the display forms.
    assert_eq!(len.to_string(), "42_km");
    let sum = arith(ArithOp::Add, &len, &Value::Str("500 m".into()), sc);
    assert_eq!(sum.to_string(), "42.5_km");
    let doubled = arith(ArithOp::Mul, &len, &Value::Int(2), sc);
    assert_eq!(doubled.to_string(), "84_km");
    // Numbers never lift into ± (| convert is the explicit road).
    assert!(matches!(
        arith(ArithOp::Add, &len, &Value::Int(5), sc),
        Value::Null
    ));
}

#[test]
fn durational_coercion_and_lift() {
    let sc: &dyn Fn(&str) -> Option<(f64, String)> = &crate::value::quantity::scale_expr;
    let two_h = Value::seconds(7200, 0);
    // Comparison coercion beside a typed Duration: span text
    // (either grammar); a bare number is not seconds, time being
    // a dimension like the others (spec: Relations).
    assert_eq!(
        value_cmp(&two_h, &Value::Str("90min".into()), sc),
        Some(Ordering::Greater)
    );
    assert!(value_eq(&two_h, &Value::Str("PT2H".into()), sc));
    assert!(!value_eq(&two_h, &Value::Int(7200), sc));
    // No durational reading: the comparison fails.
    assert_eq!(value_cmp(&two_h, &Value::Str("hello".into()), sc), None);
    assert!(!value_eq(&two_h, &Value::Str("hello".into()), sc));
    // The arithmetic text-lift: instant − span text = instant,
    // instant − instant text = duration (disjoint grammars).
    let (s, n, _) = crate::temporal::parse_iso("2026-07-12T09:00:00Z").unwrap();
    let now = Value::Instant {
        secs: s,
        nanos: n,
        offset_min: Some(0),
        calendar: Default::default(),
    };
    let earlier = arith(ArithOp::Sub, &now, &Value::Str("12h".into()), sc);
    assert_eq!(earlier.to_string(), "2026-07-11T21:00:00Z");
    let span = arith(ArithOp::Sub, &now, &Value::Str("2026-07-12".into()), sc);
    // instant − instant: a span with no written unit prints scaled
    assert_eq!(span.to_string(), "9h");
    // Numbers never lift in arithmetic (epoch or seconds?).
    assert!(matches!(
        arith(ArithOp::Sub, &now, &Value::Int(300), sc),
        Value::Null
    ));
    // Duration ± span text stays a duration.
    let sum = arith(ArithOp::Add, &two_h, &Value::Str("30min".into()), sc);
    assert_eq!(sum.to_string(), "2h 30min");
    // A quantity is no scaling factor: Duration × Quantity (and
    // ÷) is dimensional nonsense — null, like Q × Q — never the
    // base magnitude leaking in as a bare number (5 kg × 2 h
    // must not be PT10H).
    let five_kg = Value::Quantity {
        value: 5.0,
        base: "kg".into(),
        written: Some((5.0, "kg".into())),
    };
    assert!(matches!(
        arith(ArithOp::Mul, &two_h, &five_kg, sc),
        Value::Null
    ));
    assert!(matches!(
        arith(ArithOp::Mul, &five_kg, &two_h, sc),
        Value::Null
    ));
    assert!(matches!(
        arith(ArithOp::Div, &two_h, &five_kg, sc),
        Value::Null
    ));
}

/// A tiny in-memory arbor for testing navigation without I/O.
struct MockTree {
    names: Vec<Option<String>>,
    kids: HashMap<u64, Vec<u64>>,
    /// Nodes outside the tree (crosslink targets only).
    loose: Vec<u64>,
    /// Outgoing crosslinks: node -> [(label, target)].
    links: HashMap<u64, Vec<(String, u64)>>,
    /// Edge properties: (source, label, target) -> [(name, value)].
    edge_props: HashMap<(u64, String, u64), Vec<(String, Value)>>,
    /// Per-node data provenance overrides.
    prov: HashMap<u64, Provenance>,
}

impl MockTree {
    /// ```text
    /// (root) ├ a ├ x.rs
    ///        │   └ y.txt
    ///        └ b ├ z.rs
    ///            └ deep └ w.rs
    /// ```
    fn sample() -> Self {
        let names = vec![
            None,                 // 0 root
            Some("a".into()),     // 1
            Some("x.rs".into()),  // 2
            Some("y.txt".into()), // 3
            Some("b".into()),     // 4
            Some("z.rs".into()),  // 5
            Some("deep".into()),  // 6
            Some("w.rs".into()),  // 7
        ];
        let mut kids = HashMap::new();
        kids.insert(0, vec![1, 4]);
        kids.insert(1, vec![2, 3]);
        kids.insert(4, vec![5, 6]);
        kids.insert(6, vec![7]);
        // x.rs --ref--> w.rs
        let mut links = HashMap::new();
        links.insert(2, vec![("ref".to_string(), 7)]);
        MockTree {
            names,
            kids,
            loose: Vec::new(),
            links,
            edge_props: HashMap::new(),
            prov: HashMap::new(),
        }
    }

    /// An n×n grid of cells `c1`…`cN` under the root, each linked
    /// `r` to its right neighbour and `d` to the one below.
    fn lattice(n: u64) -> Self {
        let mut names = vec![None];
        names.extend((1..=n * n).map(|i| Some(format!("c{i}"))));
        let mut kids = HashMap::new();
        kids.insert(0, (1..=n * n).collect());
        let mut links = HashMap::new();
        for i in 1..=n * n {
            let (x, y) = ((i - 1) % n, (i - 1) / n);
            let mut out = Vec::new();
            if x < n - 1 {
                out.push(("r".to_string(), i + 1));
            }
            if y < n - 1 {
                out.push(("d".to_string(), i + n));
            }
            links.insert(i, out);
        }
        MockTree {
            names,
            kids,
            loose: Vec::new(),
            links,
            edge_props: HashMap::new(),
            prov: HashMap::new(),
        }
    }

    /// The sample tree with a `mgr` crosslink cycle laid over it:
    /// x.rs → z.rs → w.rs → x.rs.
    fn cyclic() -> Self {
        let mut t = MockTree::sample();
        t.links = HashMap::new();
        t.links.insert(2, vec![("mgr".to_string(), 5)]);
        t.links.insert(5, vec![("mgr".to_string(), 7)]);
        t.links.insert(7, vec![("mgr".to_string(), 2)]);
        t
    }

    /// ```text
    /// (root) └ div └ ul └ li └ ul └ li └ ul └ li
    /// ```
    /// Three levels of nesting for `(/ul/li)` repetition.
    fn lists() -> Self {
        let names = vec![
            None,
            Some("div".into()), // 1
            Some("ul".into()),  // 2
            Some("li".into()),  // 3
            Some("ul".into()),  // 4
            Some("li".into()),  // 5
            Some("ul".into()),  // 6
            Some("li".into()),  // 7
        ];
        let mut kids = HashMap::new();
        for (parent, child) in [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7)] {
            kids.insert(parent, vec![child]);
        }
        MockTree {
            names,
            kids,
            loose: Vec::new(),
            links: HashMap::new(),
            edge_props: HashMap::new(),
            prov: HashMap::new(),
        }
    }

    /// The weighted tree with a second edge converging on
    /// deep: a -4-> x.rs -12-> deep, a -1-> y.txt -5-> deep.
    fn converging() -> Self {
        let mut t = MockTree::weighted();
        t.links.get_mut(&3).map(|v| v.push(("e".to_string(), 6)));
        t.links.insert(3, vec![("e".to_string(), 6)]);
        t.edge_props.insert(
            (3, "e".to_string(), 6),
            vec![("qty".to_string(), Value::Int(5))],
        );
        t
    }

    /// A crosslink diamond with a back edge:
    /// a → x.rs, a → y.txt; x.rs → deep, y.txt → deep;
    /// deep → x.rs. All edges labeled `e`.
    fn diamond() -> Self {
        let mut t = MockTree::sample();
        t.links = HashMap::new();
        t.links
            .insert(1, vec![("e".to_string(), 2), ("e".to_string(), 3)]);
        t.links.insert(2, vec![("e".to_string(), 6)]);
        t.links.insert(3, vec![("e".to_string(), 6)]);
        t.links.insert(6, vec![("e".to_string(), 2)]);
        t
    }
}

impl MockTree {
    /// The diamond with lengths on its `e` edges, as unit text:
    /// a -4km-> x.rs, a -1km-> y.txt, x.rs -12km-> deep,
    /// y.txt -2km-> deep; deep -3km-> x.rs closes the cycle. The
    /// a→y.txt edge also carries a duration, the y.txt→deep edge a
    /// second length (`detour`), for the dimension rules.
    fn roads() -> Self {
        let mut t = MockTree::diamond();
        let mut w = |s: u64, t_: u64, props: Vec<(&str, Value)>| {
            t.edge_props.insert(
                (s, "e".to_string(), t_),
                props.into_iter().map(|(n, v)| (n.to_string(), v)).collect(),
            );
        };
        w(1, 2, vec![("len", Value::Str("4 km".into()))]);
        w(
            1,
            3,
            vec![
                ("len", Value::Str("1 km".into())),
                ("time", Value::Str("2 h".into())),
            ],
        );
        w(2, 6, vec![("len", Value::Str("12 km".into()))]);
        w(3, 6, vec![("len", Value::Str("2 km".into()))]);
        w(6, 2, vec![("len", Value::Str("3 km".into()))]);
        t
    }

    /// The sample tree with weighted `e` edges laid over it:
    /// a -4-> x.rs, a -1-> y.txt; x.rs -12-> deep.
    fn weighted() -> Self {
        let mut t = MockTree::sample();
        t.links = HashMap::new();
        t.links
            .insert(1, vec![("e".to_string(), 2), ("e".to_string(), 3)]);
        t.links.insert(2, vec![("e".to_string(), 6)]);
        let mut w = |s: u64, t_: u64, q: i64| {
            t.edge_props.insert(
                (s, "e".to_string(), t_),
                vec![("qty".to_string(), Value::Int(q))],
            );
        };
        w(1, 2, 4);
        w(1, 3, 1);
        w(2, 6, 12);
        t
    }
}

impl AstAdapter for MockTree {
    fn root(&self) -> NodeId {
        NodeId(0)
    }
    fn children(&self, node: NodeId) -> Vec<NodeId> {
        self.kids
            .get(&node.0)
            .map(|v| v.iter().map(|&i| NodeId(i)).collect())
            .unwrap_or_default()
    }
    fn name(&self, node: NodeId) -> Option<String> {
        self.names[node.0 as usize].clone()
    }
    fn parent(&self, node: NodeId) -> Option<NodeId> {
        self.kids
            .iter()
            .find(|(_, v)| v.contains(&node.0))
            .map(|(&p, _)| NodeId(p))
    }
    fn non_tree_nodes(&self) -> Vec<NodeId> {
        self.loose.iter().map(|&i| NodeId(i)).collect()
    }
    fn links(&self, node: NodeId) -> Vec<(String, NodeId)> {
        self.links
            .get(&node.0)
            .map(|v| v.iter().map(|(l, t)| (l.clone(), NodeId(*t))).collect())
            .unwrap_or_default()
    }
    /// `.rs` files are `<code>`, other files `<text>`; the
    /// directories carry no traits (so `<!*>` finds them).
    fn traits(&self, node: NodeId) -> Vec<String> {
        match self.names[node.0 as usize].as_deref() {
            Some(n) if n.ends_with(".rs") => vec!["code".into(), "file".into()],
            Some(n) if n.contains('.') => vec!["text".into(), "file".into()],
            _ => Vec::new(),
        }
    }
    fn backlinks(&self, node: NodeId) -> Vec<(String, NodeId)> {
        self.links
            .iter()
            .flat_map(|(&src, v)| {
                v.iter()
                    .filter(|(_, t)| *t == node.0)
                    .map(move |(l, _)| (l.clone(), NodeId(src)))
            })
            .collect()
    }
    fn link_property_names(&self, source: NodeId, label: &str, target: NodeId) -> Vec<String> {
        self.edge_props
            .get(&(source.0, label.to_string(), target.0))
            .map(|ps| ps.iter().map(|(n, _)| n.clone()).collect())
            .unwrap_or_default()
    }

    fn link_property(
        &self,
        source: NodeId,
        label: &str,
        target: NodeId,
        name: &str,
    ) -> Option<Value> {
        self.edge_props
            .get(&(source.0, label.to_string(), target.0))?
            .iter()
            .find(|(k, _)| k == name)
            .map(|(_, v)| v.clone())
    }
    fn provenance(&self, node: NodeId) -> Provenance {
        self.prov.get(&node.0).cloned().unwrap_or_default()
    }
}

fn run(q: &str, t: &impl AstAdapter) -> Vec<u64> {
    match eval(&parse(&lex(q).unwrap()).unwrap(), t) {
        QueryResult::Nodes(ns) => ns.into_iter().map(|n| n.0).collect(),
        QueryResult::Values(_) => panic!("expected nodes, got values"),
    }
}

fn vals(q: &str, t: &MockTree) -> Vec<Value> {
    match eval(&parse(&lex(q).unwrap()).unwrap(), t) {
        QueryResult::Values(vs) => vs,
        QueryResult::Nodes(_) => panic!("expected values, got nodes"),
    }
}

/// `*//` is the universal search: the root and its descendants
/// in document order, then the nodes outside the tree in the
/// adapter's order; `^//` and `//` stay the proper descendants.
#[test]
fn universal_search_reaches_the_whole_arbor() {
    let mut t = MockTree::sample();
    // A node joined to the tree by a crosslink alone.
    t.names.push(Some("x.rs".into())); // 8
    t.loose.push(8);
    t.links.insert(3, vec![("see".to_string(), 8)]);
    assert_eq!(run("*//x.rs", &t), vec![2, 8]);
    assert_eq!(run("//x.rs", &t), vec![2]);
    assert_eq!(run("^//x.rs", &t), vec![2]);
    // The root is in the universe and first.
    assert_eq!(run("*//*", &t), vec![0, 1, 2, 3, 4, 5, 6, 7, 8]);
    assert_eq!(run("//*", &t), vec![1, 2, 3, 4, 5, 6, 7]);
    assert_eq!(run("*//*[:is-non-tree]", &t), vec![8]);
    // Steps continue from the found nodes as usual.
    assert_eq!(run("*//y.txt->see", &t), vec![8]);
    // Head position only, no reach.
    assert!(parse(&lex("*//?x.rs").unwrap()).is_err());
    assert!(parse(&lex("/a/*//x.rs").unwrap()).is_ok());
    assert_eq!(run("/a/*//x.rs", &t), Vec::<u64>::new());
    assert_eq!(
        crate::syntax::unparse::unparse(&parse(&lex("*//x.rs[1]").unwrap()).unwrap()),
        "*//x.rs[1]"
    );
    // As an operand, root-anchored like `^`.
    assert_eq!(
        vals("/a | %(n = (*//x.rs @| count); d = (//x.rs @| count))", &t),
        vec![Value::record(vec![
            ("n".to_string(), Value::Int(2)),
            ("d".to_string(), Value::Int(1)),
        ])]
    );
}

#[test]
fn child_and_descendant() {
    let t = MockTree::sample();
    assert_eq!(run("/a", &t), vec![1]);
    assert_eq!(run("/a/x.rs", &t), vec![2]);
    assert_eq!(run("//*.rs", &t), vec![2, 5, 7]);
}

#[test]
fn parent_and_ancestor() {
    let t = MockTree::sample();
    assert_eq!(run("//w.rs\\deep", &t), vec![6]);
    // ancestors of w.rs named 'b' -> node 4
    assert_eq!(run("//w.rs\\\\b", &t), vec![4]);
}

#[test]
fn proximal_and_distal_descendant() {
    let t = MockTree::sample();
    // .rs descendants of b: z.rs (depth 1), w.rs (depth 2)
    assert_eq!(run("/b//*.rs", &t), vec![5, 7]);
    assert_eq!(run("/b//?*.rs", &t), vec![5]); // nearest
    assert_eq!(run("/b//!*.rs", &t), vec![7]); // farthest
}

#[test]
fn siblings() {
    let t = MockTree::sample();
    assert_eq!(run("/a/x.rs>y.txt", &t), vec![3]);
    assert_eq!(run("/a/y.txt<x.rs", &t), vec![2]);
    assert!(run("/a/y.txt>*", &t).is_empty()); // no next sibling
}

#[test]
fn leaf_anchor() {
    let t = MockTree::sample();
    // 'deep' has a child, so it is not a leaf
    assert!(run("/b/deep$", &t).is_empty());
    assert_eq!(run("/b/z.rs$", &t), vec![5]);
}

#[test]
fn regex_name() {
    let t = MockTree::sample();
    assert_eq!(run("//(/.*\\.rs/)", &t), vec![2, 5, 7]);
}

#[test]
fn correlation() {
    let t = MockTree::sample();
    // Driver-first: the first expression drives; the joined
    // expression's ON clause references the driver as `$$…`.
    // Nodes at the same depth as `a` (depth 1): a and b.
    assert_eq!(run("//* <=> //a[:depth = $$0:depth]", &t), vec![1, 4]);
    // All .rs files except the one `x.rs` names (join by name).
    assert_eq!(run("//*.rs <=> //x.rs[:name != $$0:name]", &t), vec![5, 7]);
    // Chained: an unconstrained second entry binds its first
    // candidate; the depth condition still filters the driver.
    assert_eq!(
        run("//* <=> //a[:depth = $$0:depth] <=> //x.rs", &t),
        vec![1, 4]
    );
    // A later entry may reference an earlier one's witness
    // (`$*1`): x.rs sits at depth 2, the a-witness at depth 1,
    // so no driver survives the second ON.
    assert!(
        run(
            "//* <=> //a[:depth = $$0:depth] <=> //x.rs[:depth = $$1:depth]",
            &t
        )
        .is_empty()
    );
}

#[test]
fn nested_predicates_read_the_thread_witness() {
    let t = MockTree::sample();
    // Driver: every .rs file; joined: the node of the same name,
    // so each thread's witness is itself (x.rs→2, z.rs→5, w.rs→7).
    // A root-anchored subexpression in a pipeline filter reads
    // `$*1`: it must see THIS thread's witness, never search the
    // trace for some tuple that happens to satisfy it. Only
    // w.rs's witness sits at depth 3; x.rs's and z.rs's at 2.
    assert_eq!(
        run(
            "//*.rs <=> //*[:name = $$0:name] \
             | [(^//*[:name = $$1:name && :depth = 3])]",
            &t
        ),
        vec![7]
    );
    assert_eq!(
        run(
            "//*.rs <=> //*[:name = $$0:name] \
             | [(^//*[:name = $$1:name && :depth = 2])]",
            &t
        ),
        vec![2, 5]
    );
    // A pipe hop's step predicate reads the same witness: from
    // each thread, climb to every ancestor and step to its .rs
    // children other than the witness itself, at depth 2. Only
    // w.rs's thread reaches one (z.rs, under b); x.rs's and
    // z.rs's only reach themselves. Under the old re-search any
    // .rs file was "not the witness" for SOME tuple, admitting
    // x.rs and z.rs too.
    assert_eq!(
        run(
            "//*.rs <=> //*[:name = $$0:name] \
             | \\\\*/*.rs[:name != $$1:name && :depth = 2]",
            &t
        ),
        vec![5]
    );
}

#[test]
fn crosslinks() {
    let t = MockTree::sample();
    // x.rs --ref--> w.rs
    assert_eq!(run("//x.rs->ref", &t), vec![7]);
    assert_eq!(run("//x.rs->*", &t), vec![7]);
    // wrong label -> nothing
    assert!(run("//x.rs->other", &t).is_empty());
    // incoming: w.rs is pointed at by x.rs
    assert_eq!(run("//w.rs<-ref", &t), vec![2]);
    // continue navigating from the crosslink target
    assert_eq!(run("//x.rs->ref\\deep", &t), vec![6]);
}

#[test]
fn quantified_child_group() {
    let t = MockTree::lists();
    // li nodes at nesting depths 1..3 (nodes 3, 5, 7)
    assert_eq!(run("/div(/ul/li)+", &t), vec![3, 5, 7]);
    assert_eq!(run("/div(/ul/li)+?", &t), vec![3]); // shallowest
    assert_eq!(run("/div(/ul/li)+!", &t), vec![7]); // deepest
    assert_eq!(run("/div(/ul/li){2}", &t), vec![5]);
    assert_eq!(run("/div(/ul/li){1;2}", &t), vec![3, 5]);
    assert_eq!(run("/div(/ul/li){1;2}!", &t), vec![5]);
    // min above the tree's depth: nothing
    assert!(run("/div(/ul/li){4;}", &t).is_empty());
}

#[test]
fn quantified_crosslinks_on_a_cycle() {
    // mgr cycle: x.rs (2) → z.rs (5) → w.rs (7) → x.rs (2)
    let t = MockTree::cyclic();
    // Simple paths: the anchor is visited, so the cycle cannot
    // close — the chain stops after two hops, bound or no bound.
    assert_eq!(run("//x.rs(->mgr)+", &t), vec![5, 7]);
    assert_eq!(run("//x.rs(->mgr)+?", &t), vec![5]);
    assert_eq!(run("//x.rs(->mgr)+!", &t), vec![7]);
    assert_eq!(run("//x.rs(->mgr){2}", &t), vec![7]);
    // `*` admits zero repetitions: the anchor itself joins.
    assert_eq!(run("//x.rs(->mgr)*", &t), vec![2, 5, 7]);
    // Zero-repetition proximal: the anchor is the shortest match.
    assert_eq!(run("//x.rs(->mgr)*?", &t), vec![2]);
    // Incoming links run the cycle backwards.
    assert_eq!(run("//x.rs(<-mgr)+", &t), vec![7, 5]);
}

#[test]
fn group_alternation() {
    let t = MockTree::sample();
    // Strict form: each alternative spells its own nav-op.
    assert_eq!(run("(/a|/b)", &t), vec![1, 4]);
    // Tolerated form: the op before '(' distributes over names.
    assert_eq!(run("/a/(x.rs|y.txt)", &t), vec![2, 3]);
    // Subpath alternatives of different lengths.
    assert_eq!(run("/b/(z.rs|deep/w.rs)", &t), vec![5, 7]);
    // Nested group inside an alternative.
    assert_eq!(run("(/a/(x.rs|y.txt)|/b/z.rs)", &t), vec![2, 3, 5]);
    // Mixing strict and tolerated alternatives refuses.
    let toks = lex("/a/(x.rs|/y.txt)").unwrap();
    assert!(parse(&toks).is_err());
    // An empty alternative refuses.
    let toks = lex("(/a|)").unwrap();
    assert!(parse(&toks).is_err());
}

#[test]
fn label_algebra() {
    // x.rs --ref--> w.rs, --doc--> w.rs, --ref--> z.rs: the
    // selection reads the labels a crosslink carries together.
    let mut t = MockTree::sample();
    t.links.insert(
        2,
        vec![
            ("ref".to_string(), 7),
            ("doc".to_string(), 7),
            ("ref".to_string(), 5),
        ],
    );
    assert_eq!(run("/a/x.rs->(ref && doc)", &t), vec![7]);
    // (a label selection reads the labels to one node together,
    // one thread per node — spec: Label Selections)
    assert_eq!(run("/a/x.rs->(ref || doc)", &t), vec![7, 5]);
    assert_eq!(run("/a/x.rs->(doc || ref)", &t), vec![7, 5]);
    assert_eq!(run("/a/x.rs->(!doc)", &t), vec![5]);
    assert_eq!(run("/a/x.rs->(!(ref || doc))", &t), Vec::<u64>::new());
    assert_eq!(run("/a/x.rs->(ref && !doc)", &t), vec![5]);
    assert_eq!(run("/a/x.rs->(r* && !d*)", &t), vec![5]);
    // every crosslink carries a label: `!*` selects nothing
    assert_eq!(run("/a/x.rs->(!*)", &t), Vec::<u64>::new());
    // the incoming arrow mirrors it
    assert_eq!(run("//w.rs<-(ref && doc)", &t), vec![2]);
    assert_eq!(run("//z.rs<-(!doc)", &t), vec![2]);
    assert_eq!(run("//z.rs<-(ref && doc)", &t), Vec::<u64>::new());
    // a quantifier applies to the hop whatever it carries
    let c = MockTree::cyclic();
    assert_eq!(run("/a/x.rs->(mgr && !x){2}", &c), vec![7]);
    assert_eq!(run("/a/x.rs(->(mgr || x)){2}", &c), vec![7]);
    // the plain alternation is the union of two hops under its
    // older spelling: one thread per edge, so 7 twice; collapsed,
    // the selection's node set
    assert_eq!(run("/a/x.rs->(ref|doc)", &t), vec![7, 5, 7]);
    assert_eq!(
        run("/a/x.rs->(ref|doc) @| collapse", &t),
        run("/a/x.rs->(ref || doc)", &t)
    );
    // the words of the family spell the operators too
    assert_eq!(run("/a/x.rs->(ref .and. .not. doc)", &t), vec![5]);
}

#[test]
fn dot_wildcard_and_sugar() {
    let t = MockTree::sample();
    // `//` is expressible as a dot-wildcard pattern.
    assert_eq!(run("/b(/.)*/w.rs", &t), run("/b//w.rs", &t));
    // `(/.){2}` — grandchildren; `/{2}` is sugar for it.
    assert_eq!(run("(/.){2}", &t), vec![2, 3, 5, 6]);
    assert_eq!(run("/{2}", &t), run("(/.){2}", &t));
    // A named hop takes a brace quantifier directly.
    let lists = MockTree::lists();
    assert_eq!(run("/div/ul/li(/ul/li){1}", &lists), vec![5]);
    // Outside a pattern, `.` stays a literal name (no such node).
    assert!(run("/.", &t).is_empty());
}

#[test]
fn zero_repetitions_keep_the_anchor() {
    let t = MockTree::sample();
    // b itself (0 reps) plus deep (1 rep).
    assert_eq!(run("/b(/deep)*", &t), vec![4, 6]);
    // {0,1} spells the same reach explicitly.
    assert_eq!(run("/b(/deep){0;1}", &t), vec![4, 6]);
    // {;1} is {0;1}: the ceiling alone, the start included.
    assert_eq!(run("/b(/deep){;1}", &t), vec![4, 6]);
}

#[test]
fn quantifier_bound_refuses_out_loud() {
    /// The lists tree with a quantifier bound of 2.
    struct Bounded(MockTree);
    impl AstAdapter for Bounded {
        fn root(&self) -> NodeId {
            self.0.root()
        }
        fn children(&self, node: NodeId) -> Vec<NodeId> {
            self.0.children(node)
        }
        fn name(&self, node: NodeId) -> Option<String> {
            self.0.name(node)
        }
        fn parent(&self, node: NodeId) -> Option<NodeId> {
            self.0.parent(node)
        }
        fn links(&self, node: NodeId) -> Vec<(String, NodeId)> {
            self.0.links(node)
        }
        fn quantifier_bound(&self) -> usize {
            2
        }
    }
    let t = Bounded(MockTree::lists());
    let refusal = |q: &str| {
        let out = run(q, &t);
        let msg = take_refusal();
        (out, msg)
    };
    // The proximal reach is a set expansion to its first tier with
    // a match: the quantifier bound does not count its rounds.
    let (out, msg) = refusal("/div(/ul/li)+?");
    assert_eq!(out, vec![3]);
    assert!(msg.is_none());
    // Every walk is answered (spec: Expansion paths): `+` is an
    // exact walk under the bound, and the third li sits beyond it —
    // edges still to take when the rounds run out, so the closure
    // would be silently incomplete: refused, out loud.
    let (out, msg) = refusal("/div(/ul/li)+");
    assert!(out.is_empty());
    assert!(msg.unwrap().contains("quantifier bound reached"));
    let (out, msg) = refusal("/div(/ul/li)+!");
    assert!(out.is_empty());
    assert!(msg.unwrap().contains("quantifier bound reached"));
    // An explicit ceiling beyond the bound refuses up front —
    // never a silent clamp, never a silent empty.
    let (out, msg) = refusal("/div(/ul/li){1;3}");
    assert!(out.is_empty());
    assert!(msg.unwrap().contains("explicit ceiling"));
    // A minimum beyond the bound can never be satisfied.
    let (out, msg) = refusal("/div(/ul/li){3;}");
    assert!(out.is_empty());
    assert!(msg.unwrap().contains("minimum"));
    // An explicit ceiling INSIDE the bound is the user asking
    // for exactly that depth: complete at n, silent.
    let (out, msg) = refusal("/div(/ul/li){1;2}");
    assert_eq!(out, vec![3, 5]);
    assert!(msg.is_none());
    // The iteration loop is bounded the same way: an exact
    // count, a ceiling or a minimum beyond the bound refuses,
    // an open loop runs to the bound and stops.
    let looped = |q: &str| match crate::run(q, &t) {
        Ok(QueryResult::Values(vs)) => (vs, take_refusal()),
        Ok(QueryResult::Nodes(ns)) => (
            ns.into_iter().map(|n| Value::Int(n.0 as i64)).collect(),
            take_refusal(),
        ),
        Err(e) => {
            let _ = take_refusal();
            (Vec::new(), Some(e.to_string()))
        }
    };
    let (out, msg) = looped("/div | .n(1){5} | $.n");
    assert!(out.is_empty());
    assert!(msg.unwrap().contains("loop's explicit ceiling"));
    let (out, msg) = looped("/div | .n(1){1;3} | $.n");
    assert!(out.is_empty());
    assert!(msg.unwrap().contains("loop's explicit ceiling"));
    let (out, msg) = looped("/div | .n(1){3;} | $.n");
    assert!(out.is_empty());
    assert!(msg.unwrap().contains("loop's minimum"));
    let (out, msg) = looped("/div | .n(1){1;2} | $.n");
    assert_eq!(out, vec![Value::Int(1)]);
    assert!(msg.is_none());
}

#[test]
fn bound_hit_with_drained_frontier_is_complete() {
    /// The lists tree bounded at exactly its chain depth.
    struct Exact(MockTree);
    impl AstAdapter for Exact {
        fn root(&self) -> NodeId {
            self.0.root()
        }
        fn children(&self, node: NodeId) -> Vec<NodeId> {
            self.0.children(node)
        }
        fn name(&self, node: NodeId) -> Option<String> {
            self.0.name(node)
        }
        fn parent(&self, node: NodeId) -> Option<NodeId> {
            self.0.parent(node)
        }
        fn links(&self, node: NodeId) -> Vec<(String, NodeId)> {
            self.0.links(node)
        }
        fn quantifier_bound(&self) -> usize {
            3
        }
    }
    let t = Exact(MockTree::lists());
    // Three rounds reach all three li's and the probe round
    // finds nothing more: the closure is complete — no refusal.
    assert_eq!(run("/div(/ul/li)+", &t), vec![3, 5, 7]);
    assert!(take_refusal().is_none());
}

#[test]
fn proximal_answer_within_bound_is_complete() {
    /// The mgr cycle bounded below its circumference.
    struct Tight(MockTree);
    impl AstAdapter for Tight {
        fn root(&self) -> NodeId {
            self.0.root()
        }
        fn children(&self, node: NodeId) -> Vec<NodeId> {
            self.0.children(node)
        }
        fn name(&self, node: NodeId) -> Option<String> {
            self.0.name(node)
        }
        fn parent(&self, node: NodeId) -> Option<NodeId> {
            self.0.parent(node)
        }
        fn links(&self, node: NodeId) -> Vec<(String, NodeId)> {
            self.0.links(node)
        }
        fn quantifier_bound(&self) -> usize {
            2
        }
    }
    let t = Tight(MockTree::cyclic());
    // The nearest tier with a survivor is the whole answer —
    // a live frontier past it is irrelevant, not a truncation.
    assert_eq!(run("//x.rs(->mgr)+?", &t), vec![5]);
    assert!(take_refusal().is_none());
}

#[test]
fn group_in_a_predicate_path() {
    let t = MockTree::sample();
    // x.rs has an outgoing ref chain; y.txt does not.
    assert_eq!(run("/a/*[(->ref)+]", &t), vec![2]);
    let cyc = MockTree::cyclic();
    // every node on the mgr cycle reaches something in two hops
    assert_eq!(run("//*[(->mgr){2}]", &cyc), vec![2, 5, 7]);
}

#[test]
fn group_predicates_filter_before_reach() {
    // mgr cycle: x.rs (2) → z.rs (5) → w.rs (7) → 2
    let t = MockTree::cyclic();
    // nearest satisfying: w.rs is two hops out; without the
    // predicate, +? would stop at z.rs (tier one).
    assert_eq!(run("//x.rs(->mgr)+[:name = w.rs]?", &t), vec![7]);
    assert_eq!(run("//x.rs(->mgr)+?", &t), vec![5]);
    // farthest satisfying
    assert_eq!(run("//x.rs(->mgr)+[:name == (/rs/)]!", &t), vec![7]);
    // no survivor anywhere: empty, not an error
    assert!(run("//x.rs(->mgr)+[:name = \"nope\"]?", &t).is_empty());
    // an unquantified group takes predicates too — endpoints of
    // different-length alternatives, filtered uniformly
    let s = MockTree::sample();
    assert_eq!(run("/b/(z.rs|deep/w.rs)[:name = w.rs]", &s), vec![7]);
    // zero repetitions: the anchor itself must pass
    assert_eq!(run("/a(/x.rs)*[:name = \"a\"]", &s), vec![1]);
    // the walked edge is in scope for the group's predicate
    let w = MockTree::weighted();
    assert_eq!(run("//a(->e)+[$-::qty = 12]", &w), vec![6]);
    // positional predicates refuse
    let toks = lex("/a(/b)+[1]").unwrap();
    assert!(parse(&toks).is_err());
}

#[test]
fn arrived_edges_aggregate() {
    let t = MockTree::converging();
    // deep is reached by two crossings: two threads, each with its
    // own arriving edge (spec: Expansion paths); `@| collapse`
    // gathers them into one with both edges
    assert_eq!(
        vals("//a->e->e | .(@-::qty) | $.", &t),
        vec![
            Value::list(vec![Value::Int(12)]),
            Value::list(vec![Value::Int(5)])
        ]
    );
    assert_eq!(
        vals("//a->e->e @| collapse | .(@-::qty) | $.", &t),
        vec![Value::list(vec![Value::Int(12), Value::Int(5)])]
    );
    // bare @- reads the labels
    assert_eq!(
        vals("//a->e->e @| collapse | .(@-) | $.", &t),
        vec![Value::list(vec![
            Value::Str("e".into()),
            Value::Str("e".into())
        ])]
    );
    // tree walks arrive by [child] edges
    assert_eq!(
        vals("/a | .(@-) | $.", &t),
        vec![Value::list(vec![Value::Str("[child]".into())])]
    );
    // per-path capsae stay distinct — one final crossing each;
    // collapsed, identical breadcrumbs are kept once and the
    // crossings aggregate
    assert_eq!(
        vals("//a(->e .($-::qty))->e | .(@-) @| count", &t),
        vec![Value::Int(2)]
    );
    assert_eq!(
        vals("//a(->e .(1))->e @| collapse | .(@-::qty) | $.", &t),
        vec![Value::list(vec![Value::Int(12), Value::Int(5)])]
    );
    // command form: `| @-::prop` sets the topic directly, and
    // `each` forks it
    assert_eq!(
        vals("//a->e->e | @-::qty | ... @| sum", &t),
        vec![Value::Int(17)]
    );
}

#[test]
fn context_accessor_and_inline_pipes() {
    let t = MockTree::sample();
    // Bare @_ reads the peers' topics; projected, their nodes.
    assert_eq!(
        vals("//*.rs:name | .all((@_ @| join(\", \"))) | $.all", &t),
        vec![
            Value::Str("x.rs, z.rs, w.rs".into()),
            Value::Str("x.rs, z.rs, w.rs".into()),
            Value::Str("x.rs, z.rs, w.rs".into()),
        ]
    );
    // The snapshot rule: a filter's own predicate reads the
    // command's INPUT (all three), not the shrinking output.
    assert_eq!(
        vals("//*.rs | [(@@_:name @| count) = 3] @| count", &t),
        vec![Value::Int(3)]
    );
    // Inline | mirrors per-capsa semantics (list reduction);
    // inline @| explodes a lone list into a context.
    assert_eq!(
        vals("/a/x.rs | .n(((@@_:name | count))) | $.n", &t),
        vec![Value::Int(1)]
    );
    // Capsa-preserving aggregates ride the inline pipe too.
    assert_eq!(
        vals(
            "//*.rs | .top((@@_:name @| sort @| [1..2] @| join(\"-\"))) | $.top",
            &t
        )[0],
        Value::Str("w.rs-x.rs".into())
    );
    // Outside any context (navigation predicates), @_ is null.
    assert_eq!(run("/*[@_ = null]", &t).len(), 2);
    // Pushes refuse inline.
    let toks = lex("/a | .x((@_ | .bad))").unwrap();
    assert!(parse(&toks).is_err());
}

#[test]
fn conditionals() {
    let t = MockTree::sample();
    // basic selection by truthiness
    assert_eq!(
        vals(
            "/a/* | %(:name; kind = (:name == (/rs/) ? \"code\" : \"text\"))",
            &t
        ),
        vec![
            Value::record(vec![
                ("name".into(), Value::Str("x.rs".into())),
                ("kind".into(), Value::Str("code".into())),
            ]),
            Value::record(vec![
                ("name".into(), Value::Str("y.txt".into())),
                ("kind".into(), Value::Str("text".into())),
            ]),
        ]
    );
    // chained else — the multi-branch form, no inner parens
    assert_eq!(
        vals(
            "//w.rs | ((:depth = 1 ? \"top\" : :depth = 2 ? \"mid\" : \"deep\"))",
            &t
        ),
        vec![Value::Str("deep".into())]
    );
    // only the taken branch evaluates: the untaken side would
    // be null-valued, not an error, and structural conditions
    // work in the condition
    assert_eq!(
        vals("/b | ((/deep ? \"has-deep\" : \"flat\"))", &t),
        vec![Value::Str("has-deep".into())]
    );
    // composes with pipe tails
    assert_eq!(
        vals("/a | (((1 = 1 ? \"yes\" : \"no\") | upper))", &t),
        vec![Value::Str("YES".into())]
    );
    // null condition is falsy
    assert_eq!(
        vals("/a | (($_ ? \"topic\" : \"none\"))", &t),
        vec![Value::Str("none".into())]
    );
}

#[test]
fn trait_negation() {
    let t = MockTree::sample();
    // files that are not code
    assert_eq!(run("//*<file && !code>", &t), vec![3]);
    // traitless nodes (the directories)
    assert_eq!(run("/*<!*>", &t), vec![1, 4]);
    // negation inside a disjunction: text or non-file — all
    // but the .rs files
    assert_eq!(run("/a/*<text || !file>", &t), vec![3]);
    // parenthesized algebra, CNF underneath
    assert_eq!(run("//*<(code || text) && !text>", &t), vec![2, 5, 7]);
}

#[test]
fn map_pipe() {
    // deep is reached by two weighted crossings: qty [12, 5].
    let t = MockTree::converging();
    // map: transform each element, capsae unchanged (the two
    // routes to deep collapsed into one thread first)
    assert_eq!(
        vals(
            "//a->e->e @| collapse | .(@-::qty) | $. $| ($_ * 10) | json",
            &t
        ),
        vec![Value::Str("[120, 50]".into())]
    );
    // filter elements ($_ = the element): the comprehension WHERE
    assert_eq!(
        vals(
            "//a->e->e @| collapse | .(@-::qty) | $. $| [$_ > 6] | json",
            &t
        ),
        vec![Value::Str("[12]".into())]
    );
    // positional slice
    assert_eq!(
        vals(
            "//a->e->e @| collapse | .(@-::qty) | $. $| [1..1] | json",
            &t
        ),
        vec![Value::Str("[12]".into())]
    );
    // @_ inside a map reads the ELEMENT context: self-normalize
    assert_eq!(
        vals(
            "//a->e->e @| collapse | .(@-::qty) | $. $| (($_ * 100 div (@_ @| sum) | round)) | json",
            &t
        ),
        vec![Value::Str("[71, 29]".into())]
    );
    // null maps to null; a non-list degenerates to plain |
    assert_eq!(vals("/a | $_ $| upper", &t), vec![Value::Null]);
    assert_eq!(
        vals("/a | :name $| upper", &t),
        vec![Value::Str("A".into())]
    );
    // pushes refuse inside a map
    let toks = lex("/a | @. $| .bad").unwrap();
    assert!(parse(&toks).is_err());
}

#[test]
fn set_walk_and_exact_walk_on_a_diamond() {
    // a → {x.rs, y.txt} → deep → x.rs (all labeled `e`). Every
    // walk is a thread (spec: Expansion paths): x, y, deep by x,
    // deep by y, x by y and deep; the proximal reach is the first
    // tier alone; `@| collapse` the node set.
    let t = MockTree::diamond();
    assert_eq!(run("//a(->e)+", &t), vec![2, 3, 6, 6, 2]);
    assert_eq!(run("//a(->e)+ @| collapse", &t), vec![2, 3, 6]);
    assert_eq!(run("//a(->e)+?", &t), vec![2, 3]);
    assert_eq!(run("//a(->e)*", &t).len(), 6);
    assert_eq!(run("//a(->e)* @| collapse", &t).len(), 4);
    // The exact walk (a count, a range, a floor above one, the
    // distal reach) asks about acyclic walks of a given length:
    // x.rs stands three hops out along a, y.txt, deep, and is the
    // farthest end.
    assert_eq!(run("//a(->e)+!", &t), vec![2]);
    assert_eq!(run("//a(->e){3}", &t), vec![2]);
    assert_eq!(run("//a(->e){2;3}", &t), vec![6, 6, 2]);
    assert_eq!(run("//a(->e){2;}", &t), vec![6, 6, 2]);
    // A recording walk is exact whatever its form: one result per
    // walk, the route through y.txt three breadcrumbs long.
    assert_eq!(
        vals("//a(->e .(1))+! | @. | count", &t),
        vec![Value::Int(3)]
    );
    assert_eq!(
        vals("//a(->e .(1)){3}:name", &t),
        vec![Value::Str("x.rs".into())]
    );
}

#[test]
fn set_walk_over_a_lattice_is_polynomial() {
    // A 12×12 grid, each cell linked right and down: the routes to
    // the far corner number in the hundreds of thousands, the
    // cells in the dozens. A set walk's frontier is one diagonal,
    // and it runs past the quantifier bound of 32 to its fixpoint
    // (the far corner is 22 rounds out; a 20×20 grid's would be 38).
    // (`?` is the nearest tier: the two neighbours of c1, and c1
    // itself under `*`)
    let t = MockTree::lattice(12);
    assert_eq!(run("/c1(->r|->d)+?", &t).len(), 2);
    assert_eq!(run("/c1(->r|->d)*?", &t).len(), 1);
    // (the far corner once: the markers answer each node once)
    assert_eq!(run("/c1(->r|->d)+[:name = \"c144\"]?", &t), vec![144]);
    assert!(take_refusal().is_none());
    // every walk is answered otherwise (spec: Expansion paths): the
    // routes through the grid are the frontier bound's to refuse
    assert!(run("/c1(->r|->d)+", &t).is_empty());
    assert!(take_refusal().unwrap().contains("frontier bound"));
    // The exact forms walk every route: a 6×6 grid has 252 at most.
    let s = MockTree::lattice(6);
    // (every walk to the far corner, 252 of them, one thread each)
    let far = run("/c1(->r|->d){10}", &s);
    assert_eq!(far.len(), 252);
    assert!(far.iter().all(|&n| n == 36));
    assert_eq!(run("/c1(->r|->d)+!", &s), vec![36]);
    assert_eq!(run("/c1(->r|->d){10} @| collapse", &s), vec![36]);
    // (every walk: 2^5 of five steps, 252 + 252 of nine and ten)
    assert_eq!(run("/c1(->r|->d){5}", &s).len(), 32);
    assert_eq!(run("/c1(->r|->d){9;}", &s).len(), 504);
    assert!(take_refusal().is_none());
}

#[test]
fn the_degenerate_name_list_is_the_wildcard() {
    // `/(*)` ≡ `/*` (spec: Name algebra): the plain step, with its
    // positional predicates and projection; quantified it is the
    // group of one it always was; `(!*)` selects nothing
    let t = MockTree::sample();
    assert_eq!(run("//a/(*)", &t), run("//a/*", &t));
    assert_eq!(run("//a/(*)[..1]", &t), run("//a/*[..1]", &t));
    assert_eq!(vals("//a/(*)[..1]:name", &t), vals("//a/*[..1]:name", &t));
    assert_eq!(run("/a/(*){1}", &t), run("/a/*", &t));
    assert_eq!(run("//(*)", &t), run("//*", &t));
    assert_eq!(run("//a->(*)", &t), run("//a->*", &t));
    assert!(run("//a/(!*)", &t).is_empty());
    assert!(take_refusal().is_none());
}

#[test]
fn the_graph_as_a_table() {
    let t = MockTree::roads();
    let table = |q: &str| -> (Vec<String>, Vec<Vec<String>>) {
        let vs = vals(q, &t);
        assert_eq!(vs.len(), 1, "{q}");
        let Value::Table(tb) = &vs[0] else {
            panic!("{q}: not a table: {}", vs[0].display_form())
        };
        (
            tb.header.clone().unwrap(),
            tb.rows
                .iter()
                .map(|r| r.iter().map(Value::display_form).collect())
                .collect(),
        )
    };
    // the induced subgraph of a, x.rs, y.txt and deep: five stored
    // `e` edges, their `len` and `time` properties as columns
    let (h, rows) = table("//a(->e)* @| edges(->e)");
    assert_eq!(h, ["source", "target", "label", "directed", "len", "time"]);
    assert_eq!(rows.len(), 5);
    assert_eq!(rows[0], ["/a", "/a/x.rs", "e", "true", "4_km", "null"]);
    assert_eq!(rows[1], ["/a", "/a/y.txt", "e", "true", "1_km", "2h"]);
    // bare edges is edges(->*); `--e` the same edges with directed
    // false; `<-e` the same five from the far ends
    assert_eq!(table("//a(->e)* @| edges").1.len(), 5);
    let (_, rows) = table("//a(->e)* @| edges(--e)");
    assert_eq!(rows.len(), 5);
    assert!(rows.iter().all(|r| r[3] == "false"));
    assert_eq!(table("//a(->e)* @| edges(<-e)").1.len(), 5);
    // narrowing the context narrows the graph: without deep, two edges
    assert_eq!(table("//a(->e)*[:name != \"deep\"] @| edges").1.len(), 2);
    // `~*` takes the tree edges too, labelled as the navop star does
    let (_, rows) = table("//a(->e)* @| edges(~*)");
    assert!(rows.iter().any(|r| r[2] == "[child]"), "{rows:?}");
    assert_eq!(rows.iter().filter(|r| r[2] == "e").count(), 5);
    // --weight=UNIT: the property of the unit's dimension, converted
    let (h, rows) = table("//a(->e)* @| edges(->e; --weight=km)");
    assert_eq!(h.last().unwrap(), "weight");
    assert_eq!(
        rows.iter().map(|r| r[6].as_str()).collect::<Vec<_>>(),
        ["4_km", "1_km", "12_km", "2_km", "3_km"]
    );
    let (_, rows) = table("//a(->e)* @| edges(->e; --weight=h)");
    assert_eq!(rows[1][6], "2_h");
    assert_eq!(rows[0][6], "null");
    // nodes: the context as node, name, kind
    let (h, rows) = table("//a(->e)* @| nodes");
    assert_eq!(h, ["node", "name", "kind"]);
    assert_eq!(rows.len(), 4);
    assert_eq!(rows[1][0], "/a/x.rs");
    assert_eq!(rows[1][1], "x.rs");
    assert!(take_refusal().is_none());
    // a wrong operand refuses naming the forms
    assert!(vals("//a(->e)* @| edges(:name)", &t).is_empty());
    assert!(take_refusal().unwrap().contains("the collecting hop"));
    assert!(vals("//a(->e)* @| edges(->e; --weight=furlong)", &t).is_empty());
    assert!(take_refusal().unwrap().contains("no unit"));
}

#[test]
fn pagerank_over_the_induced_subgraph() {
    let t = MockTree::diamond();
    let table = |q: &str| -> (Vec<String>, Vec<Vec<Value>>) {
        let vs = vals(q, &t);
        let Value::Table(tb) = &vs[0] else {
            panic!("{q}: not a table")
        };
        (tb.header.clone().unwrap(), tb.rows.clone())
    };
    // a → {x.rs, y.txt} → deep → x.rs: the rank over the `e` edges
    // sums to one; a, linked by nothing, holds the floor (1 - d) / n
    let ranks = |q: &str| -> Vec<f64> {
        vals(q, &t)
            .iter()
            .map(|v| match v {
                Value::Float(f) => *f,
                other => panic!("{other:?}"),
            })
            .collect()
    };
    let pr = ranks("//a(->e)* @| collapse @| graph:pagerank(->e)");
    assert_eq!(pr.len(), 4);
    assert!((pr.iter().sum::<f64>() - 1.0).abs() < 1e-9, "{pr:?}");
    assert!((pr[0] - 0.15 / 4.0).abs() < 1e-9, "{pr:?}");
    assert!(pr[1] > pr[2] && pr[3] > pr[2], "{pr:?}");
    // the damping and the rounds are the knobs; the label algebra
    // picks the labels; `--e` ranks both ways
    let a = ranks("//a(->e)* @| collapse @| graph:pagerank(->e; --damping=0.5 --rounds=5)")[0];
    assert!((a - 0.5 / 4.0).abs() < 1e-9, "{a}");
    assert_eq!(
        ranks("//a(->e)* @| collapse @| graph:pagerank(->(e || f))").len(),
        4
    );
    let a = ranks("//a(->e)* @| collapse @| graph:pagerank(--e)")[0];
    assert!(a > 0.15 / 4.0, "{a}");
    // the label algebra and the group serve `edges`
    assert_eq!(table("//a(->e)* @| edges(->(e || f))").1.len(), 5);
    assert_eq!(table("//a(->e)* @| edges((->e|->f))").1.len(), 5);
    assert!(take_refusal().is_none());
    assert!(vals("//a(->e)* @| graph:pagerank(->e; --damping=2)", &t).is_empty());
    assert!(take_refusal().unwrap().contains("outside 0..1"));
    // the bare table form is retired, with its pointer
    let err = parse(&lex("//a(->e)* @| pagerank(->e)").unwrap())
        .unwrap_err()
        .to_string();
    assert!(err.contains("graph:pagerank"), "{err}");
}

#[test]
fn every_walk_is_its_own_thread() {
    // deep is reached at round 2 by x (4 + 12 km) and by y (1 + 2
    // km): two threads at the exit, each with its own facts and
    // arriving edge (spec: Expansion paths); `@| collapse` makes
    // the one thread the navigation used to, both edges in `@-`
    let t = MockTree::roads();
    let show = |q: &str| {
        vals(q, &t)
            .iter()
            .map(Value::display_form)
            .collect::<Vec<_>>()
    };
    assert_eq!(
        show("//a(->e){;100_km}[:name = \"deep\"] | $-:total"),
        vec!["16_km", "3_km"]
    );
    assert_eq!(
        show("//a(->e){;100_km}[:name = \"deep\"] | $-::len"),
        vec!["12 km", "2 km"]
    );
    assert_eq!(
        show("//a(->e){;100_km}[:name = \"deep\"] @| collapse | @-::len"),
        vec!["@(\"12 km\"; \"2 km\")"]
    );
    assert_eq!(
        show("//a(->e){;100_km}[:name = \"deep\"] @| collapse @| count"),
        vec!["1"]
    );
    // the proximal reach is the one per-node selection: the least
    // total under a budget
    assert_eq!(
        show("//a(->e){;100_km}[:name = \"deep\"]? | $-:total"),
        vec!["3_km"]
    );
    // x.rs at round 1 (4 km) and again at round 3 by y, deep (6 km)
    assert_eq!(
        show("//a(->e){;100_km}[:name = \"x.rs\"] | $-:total"),
        vec!["4_km", "6_km"]
    );
    assert_eq!(
        show("//a(->e){;100_km}[:name = \"x.rs\"] | $-:hops"),
        vec!["1", "3"]
    );
    assert_eq!(
        show("//a(->e){1;3}[:name = \"x.rs\"] | $-:hops"),
        vec!["1", "3"]
    );
    // a hop from two threads to one node is two threads, as a join's
    // rows are; collapse(-e) keeps them apart by arriving edge
    assert_eq!(show("//a->e->e | :name"), vec!["deep", "deep"]);
    assert_eq!(show("//a->e->e @| collapse | :name"), vec!["deep"]);
    assert_eq!(
        show("//a->e->e @| collapse(-e) | :name"),
        vec!["deep", "deep"]
    );
    assert!(take_refusal().is_none());
}

#[test]
fn a_nested_tree_path_answers_the_node_set() {
    // w.rs lies under b and under deep, so `//*//w.rs` from the root
    // reaches it twice; the tree axes answer a node set, one w.rs at
    // the top level and one inside an operand alike (the same fold:
    // node, arriving edge, capsa) — where a walk answers one value
    // per walk in both places too
    let t = MockTree::roads();
    let show = |q: &str| {
        vals(q, &t)
            .iter()
            .map(Value::display_form)
            .collect::<Vec<_>>()
    };
    assert_eq!(show("//*//w.rs | :name"), vec!["w.rs"]);
    assert_eq!(show("//b | (\\//*//w.rs @| count)"), vec!["1"]);
    assert_eq!(
        show("//b | %(n = (\\//*//w.rs @| count))"),
        vec!["%(n = 1)"]
    );
    // climbing too: z.rs, deep and w.rs all have b above them, and
    // the ancestor axis answers b once, whichever child it was
    // reached through
    assert_eq!(show("//*\\\\b | :name"), vec!["b"]);
    assert_eq!(show("//*\\\\b @| count"), vec!["1"]);
    assert_eq!(show("//a | (\\//*\\\\b @| count)"), vec!["1"]);
    assert_eq!(
        show("//a(->e){;100_km}[:name = \"deep\"] @| count"),
        vec!["2"]
    );
    assert_eq!(
        show("//a | ((->e){;100_km}[:name = \"deep\"] @| count)"),
        vec!["2"]
    );
    assert!(take_refusal().is_none());
}

#[test]
fn a_gathered_mark_reads_back_every_node() {
    // x.rs and y.txt each mark themselves W and climb to a; collapse
    // folds the two threads, the mark gathered as a list of both
    // references, which `$$.W` reads back as both nodes
    let t = MockTree::sample();
    let show = |q: &str| {
        vals(q, &t)
            .iter()
            .map(Value::display_form)
            .collect::<Vec<_>>()
    };
    assert_eq!(show("/a/* .W | \\ | ($$.W @| count)"), vec!["1", "1"]);
    assert_eq!(
        show("/a/* .W | \\ @| collapse | ($$.W @| count)"),
        vec!["2"]
    );
    assert_eq!(
        show("/a/* .W | \\ @| collapse | ($$.W:name @| join(\", \"))"),
        vec!["x.rs, y.txt"]
    );
    assert!(take_refusal().is_none());
}

#[test]
fn the_acyclic_promise_expands_by_node_and_round() {
    /// A tree whose listed labels are promised acyclic.
    struct Promised(MockTree, &'static [&'static str]);
    impl AstAdapter for Promised {
        fn root(&self) -> NodeId {
            self.0.root()
        }
        fn children(&self, node: NodeId) -> Vec<NodeId> {
            self.0.children(node)
        }
        fn name(&self, node: NodeId) -> Option<String> {
            self.0.name(node)
        }
        fn parent(&self, node: NodeId) -> Option<NodeId> {
            self.0.parent(node)
        }
        fn links(&self, node: NodeId) -> Vec<(String, NodeId)> {
            self.0.links(node)
        }
        fn backlinks(&self, node: NodeId) -> Vec<(String, NodeId)> {
            self.0.backlinks(node)
        }
        fn acyclic_link(&self, label: &str) -> Option<String> {
            self.1
                .contains(&label)
                .then(|| format!("ref /c/*::{label} --> /c acyclic"))
        }
        fn frontier_bound(&self) -> usize {
            30
        }
    }
    // The promise changes no answer (spec: Acyclic links): a count
    // of walks across the 12×12 lattice still meets the frontier
    // bound, promise or no promise. It changes the cost of every
    // node-level reading — a collapsing reducer or a graph table
    // after the walk, a marker — where the expansion goes by node,
    // round and arriving edge (one diagonal in flight, 23 at most)
    // instead of by history.
    let t = Promised(MockTree::lattice(12), &["r", "d", "e"]);
    assert!(run("/c1(->r|->d){22}", &t).is_empty());
    assert!(take_refusal().unwrap().contains("frontier bound (30)"));
    assert_eq!(run("/c1(->r|->d){22} @| collapse", &t), vec![144]);
    assert_eq!(run("/c1(->r|->d)+!", &t), vec![144]);
    assert_eq!(run("/c1(->r|->d){5} @| collapse", &t).len(), 6);
    assert_eq!(run("/c1(->r|->d){20;} @| collapse", &t).len(), 6);
    assert_eq!(run("/c1(->r|->d)+ @| collapse", &t).len(), 143);
    assert!(take_refusal().is_none());
    // a recording walk reads its capsae, so it keeps every history
    // and meets the bound as any count does
    match eval(
        &parse(&lex("/c1(->r .(1)|->d .(1)){22} | @. | count").unwrap()).unwrap(),
        &t,
    ) {
        QueryResult::Values(vs) => assert!(vs.is_empty(), "{vs:?}"),
        QueryResult::Nodes(ns) => assert!(ns.is_empty()),
    }
    assert!(take_refusal().unwrap().contains("frontier bound (30)"));
    // a wildcard hop reads the promise off the edges it crosses
    assert_eq!(run("/c1(->*){22} @| collapse", &t), vec![144]);
    assert_eq!(run("/c1(->*)+!", &t), vec![144]);
    assert!(take_refusal().is_none());
    // an unpromised label among them keeps the histories, and the
    // bound refuses even the node-level reading — the wildcard too,
    // from the first unpromised edge
    let half = Promised(MockTree::lattice(12), &["r"]);
    assert!(run("/c1(->r|->d){5} @| collapse", &half).is_empty());
    assert!(take_refusal().unwrap().contains("frontier bound (30)"));
    assert!(run("/c1(->*){5} @| collapse", &half).is_empty());
    assert!(take_refusal().unwrap().contains("frontier bound (30)"));
    assert_eq!(run("/c1(->r){11}", &half), vec![12]);
    assert!(take_refusal().is_none());
    // without a promise a plain open walk read at the node level
    // expands by node as well: the set of reachable cells
    let plain = MockTree::lattice(12);
    assert_eq!(run("/c1(->r|->d)+ @| collapse", &plain).len(), 143);
    assert!(take_refusal().is_none());
    // The diamond closes a cycle (deep → x.rs): an exact walk under
    // the promise refuses naming the declaration; without the
    // promise it drops the revisit and answers.
    let d = Promised(MockTree::diamond(), &["e"]);
    assert!(run("//a(->e){3}", &d).is_empty());
    let msg = take_refusal().unwrap();
    assert!(
        msg.contains("a cycle under the promise 'ref /c/*::e --> /c acyclic'"),
        "{msg}"
    );
    assert!(
        msg.contains("the walk from /a returns to /a/x.rs after 3 hops"),
        "{msg}"
    );
    assert_eq!(run("//a(->e){3}", &MockTree::diamond()), vec![2]);
    assert!(take_refusal().is_none());
}

#[test]
fn frontier_bound_refuses_out_loud() {
    /// The lattice with a frontier bound of 12.
    struct Narrow(MockTree);
    impl AstAdapter for Narrow {
        fn root(&self) -> NodeId {
            self.0.root()
        }
        fn children(&self, node: NodeId) -> Vec<NodeId> {
            self.0.children(node)
        }
        fn name(&self, node: NodeId) -> Option<String> {
            self.0.name(node)
        }
        fn parent(&self, node: NodeId) -> Option<NodeId> {
            self.0.parent(node)
        }
        fn links(&self, node: NodeId) -> Vec<(String, NodeId)> {
            self.0.links(node)
        }
        fn frontier_bound(&self) -> usize {
            12
        }
    }
    let t = Narrow(MockTree::lattice(6));
    // An exact walk holds 2^4 = 16 paths at round 4: refused,
    // naming the bound and the round — recording or not.
    for q in ["/c1(->r .(1)|->d .(1)){4}", "/c1(->r|->d){4}"] {
        let out = run(q, &t);
        let msg = take_refusal().unwrap();
        assert!(out.is_empty());
        assert!(
            msg.contains("frontier bound (12) is exceeded at round 4"),
            "{msg}"
        );
        assert!(msg.contains("--frontier-bound"));
    }
    // The proximal reach holds one path per arrival and stops at
    // its first tier; every walk otherwise, which the bound refuses.
    assert_eq!(run("/c1(->r|->d)+?", &t).len(), 2);
    assert!(take_refusal().is_none());
    assert!(run("/c1(->r|->d)+", &t).is_empty());
    assert!(take_refusal().unwrap().contains("frontier bound (12)"));
}

#[test]
fn navop_star_walks_every_edge() {
    // The sample tree with x.rs --ref--> w.rs: `~` walks the tree
    // edges and the crosslinks alike, either direction, and keeps
    // the far ends whose edge matches — a child's or the parent's
    // name, a crosslink's label. Siblings are no edges.
    let t = MockTree::sample();
    assert_eq!(run("/a/x.rs~*", &t), vec![1, 7]);
    assert_eq!(run("/b/deep/w.rs~*", &t), vec![6, 2]);
    assert_eq!(run("/a/x.rs~ref", &t), vec![7]);
    assert_eq!(run("/a/x.rs~a", &t), vec![1]);
    assert_eq!(run("/a~*", &t), vec![2, 3, 0]);
    assert!(run("/a/x.rs~y.txt", &t).is_empty());
    // The edge walked is in scope: a tree edge reports its
    // structural label.
    assert_eq!(run("/a/x.rs~*[$- = \"ref\"]", &t), vec![7]);
    assert_eq!(run("/a/x.rs~*[$- = \"[parent]\"]", &t), vec![1]);
    // Quantified, the walk is plain: each node once, at the fewest
    // rounds. From x.rs: {a, w.rs}, then {root, y.txt, deep}.
    assert_eq!(run("/a/x.rs(~*){2}", &t), vec![3, 0, 6]);
    assert_eq!(run("/a/x.rs(~*)+[:name = \"deep\"]?", &t), vec![6]);
    // The deep form: the walk over every edge, then the matching
    // hop — w.rs by name is the child of deep, five hops out; the
    // nearest edges are a's and ref's; the farthest hop is the one
    // from z.rs back to b.
    assert_eq!(run("/a/x.rs~~w.rs", &t), vec![7]);
    assert_eq!(run("/a/x.rs~~?*", &t), vec![1, 7]);
    assert_eq!(run("/a/x.rs~~!*", &t), vec![4]);
    assert_eq!(
        crate::syntax::unparse::unparse(&parse(&lex("/a~~?x(~.)*").unwrap()).unwrap()),
        "/a~~?x(~.)*"
    );
}

#[test]
fn a_budget_sums_an_edge_weight_along_the_walk() {
    // Spec: The budget quantifier. The roads diamond: a→x 4 km,
    // a→y 1 km, x→deep 12 km, y→deep 2 km, deep→x 3 km.
    let t = MockTree::roads();
    // At most 5 km: the start at zero (an absent floor includes
    // it), x (4), y (1), deep by y (3); deep by x is 16.
    assert_eq!(run("//a(->e){;5_km}", &t), vec![1, 2, 3, 6]);
    // At most 3 km: the start, y, deep; x by y, deep is 6 — no.
    assert_eq!(run("//a(->e){;3_km}", &t), vec![1, 3, 6]);
    // A floor: walks of 3 km or more within 7 km — x alone (4),
    // deep by y (3), x by y, deep (6): one thread per walk
    assert_eq!(run("//a(->e){3_km;7_km}", &t), vec![2, 6, 2]);
    // The unit converts: 5000 m is 5 km.
    assert_eq!(run("//a(->e){;5000_m}", &t), vec![1, 2, 3, 6]);
    // The lightest walks: the start, then y at 1 km, deep at 3 km
    // (by y), x at 4 km — each node once at its least total, the
    // proximal reach.
    assert_eq!(run("//a(->e){;100_km}?", &t), vec![1, 3, 6, 2]);
    assert_eq!(run("//a(->e){;100_km}[:name = \"deep\"]?", &t), vec![6]);
    // The heaviest within the budget: x by y, deep at 6 km.
    assert_eq!(run("//a(->e){;7_km}!", &t), vec![2]);
    // The total, read by the one command after the group, in the
    // budget's unit; the hops and the round beside it.
    assert_eq!(
        vals("//a(->e){;100_km}[:name = \"deep\"]? | $-:total", &t),
        vec![Value::Quantity {
            value: 3000.0,
            base: "m".into(),
            written: Some((3.0, "km".into()))
        }]
    );
    assert_eq!(
        vals("//a(->e){;100_km}[:name = \"deep\"]? | $-:hops", &t),
        vec![Value::Int(2)]
    );
    // One command only: the next one sees no edge.
    assert_eq!(
        vals(
            "//a(->e){;100_km}[:name = \"deep\"]? | $-:hops | $-:hops",
            &t
        ),
        vec![Value::Null]
    );
    // An edge without the weight is not crossed: a time budget sees
    // only a→y (2 h); y→deep carries no time.
    assert_eq!(run("//a(->e){;3_h}", &t), vec![1, 3]);
    // Two lengths on one edge refuse naming both.
    let mut two = MockTree::roads();
    two.edge_props
        .get_mut(&(3, "e".to_string(), 6))
        .unwrap()
        .push(("detour".into(), Value::Str("5 km".into())));
    // (the refusal is recorded; the library voids the answer)
    let _ = run("//a(->e){;5_km}", &two);
    assert!(take_refusal().unwrap().contains("len and detour"));
    // One dimension per quantifier.
    assert!(run("//a(->e){1;5_km}", &t).is_empty());
    assert!(
        take_refusal()
            .unwrap()
            .contains("one dimension per quantifier")
    );
    // A negative weight refuses the lightest walk by name.
    let mut neg = MockTree::roads();
    neg.edge_props.insert(
        (6, "e".to_string(), 2),
        vec![("len".into(), Value::Str("-3 km".into()))],
    );
    let _ = run("//a(->e){;100_km}?", &neg);
    assert!(take_refusal().unwrap().contains("negative weight"));
    // The exact form has no meaning for a sum.
    assert!(lex("//a(->e){5_km}").is_err());
    // The facts on a counted walk: hops and the round, no total —
    // one thread per walk, deep by x and by y.
    assert_eq!(
        vals("//a(->e){2}[:name = \"deep\"] | $-:round", &t),
        vec![Value::Int(2), Value::Int(2)]
    );
    assert_eq!(
        vals("//a(->e){2} | $-:total", &t),
        vec![Value::Null, Value::Null]
    );
    // Inside the group's predicate the facts read too.
    assert_eq!(run("//a(->e)+[$-:hops = 2]", &t), vec![6, 6]);
    // Outside any group the facts are null.
    assert_eq!(vals("//a->e | $-:hops", &t), vec![Value::Null, Value::Null]);
    // The canonical text keeps the budget as written.
    assert_eq!(
        crate::syntax::unparse::unparse(&parse(&lex("//a(->e){;100_km}?").unwrap()).unwrap()),
        "//a(->e){;100_km}?"
    );
}

#[test]
fn edge_accessor() {
    let t = MockTree::weighted();
    // `$-::prop` filters BY the edge in the hop's own predicate:
    // a's heavy outgoing edges only.
    assert_eq!(run("//a->e[$-::qty > 1]", &t), vec![2]);
    // Bare `$-` reads the label.
    assert_eq!(run("//a->*[$- = \"e\"]", &t), vec![2, 3]);
    // Incoming direction: the walked edge points into the node.
    assert_eq!(run("//deep<-e[$-::qty = 12]", &t), vec![2]);
    // Null where no edge is in scope: nothing has walked one.
    assert!(run("/a[$-::qty = 4]", &t).is_empty());
    // Edge property in a projection-bearing predicate command after
    // the hop is NOT in scope (the edge belongs to the hop).
    assert_eq!(
        vals("//a->e[$-::qty > 1]:name", &t),
        vec![Value::Str("x.rs".into())]
    );
    // The command after a plain hop reads the edge the thread most
    // recently walked (spec: Arrived-by Edge), as it does after a
    // quantified group's exit: the label bare, the property
    // projected.
    assert_eq!(
        vals("//a->e | $-", &t),
        vec![Value::Str("e".into()), Value::Str("e".into())]
    );
    assert_eq!(
        vals("//a->e | $-::qty", &t),
        vec![Value::Int(4), Value::Int(1)]
    );
    // A tree hop walks the child edge: `//a` arrives by `[child]`.
    assert_eq!(vals("//a | $-", &t), vec![Value::Str("[child]".into())]);
}

#[test]
fn headless_hop_is_one_thread_per_edge() {
    // x.rs (2) has e→deep (6), and e←a (1), e←deep (6): deep is
    // linked both ways, so the headless hop reaches it twice — one
    // thread per edge (spec: Expansion paths), the edge context
    // keeping each edge's true direction.
    let t = MockTree::diamond();
    let mut reached = run("//x.rs--e", &t);
    reached.sort();
    assert_eq!(reached, vec![1, 6, 6]);
    assert_eq!(
        vals("//x.rs--e | $-", &t),
        vec![
            Value::Str("e".into()),
            Value::Str("e".into()),
            Value::Str("e".into())
        ]
    );
    // Inside a group the same: two walks stand at deep after one
    // round, each by its own edge.
    assert_eq!(run("//x.rs(--e){1} | [:name = \"deep\"]", &t), vec![6, 6]);
    assert_eq!(
        run("//x.rs(--e){1} | [:name = \"deep\"] @| collapse", &t),
        vec![6]
    );
}

#[test]
fn pattern_breadcrumbs() {
    let t = MockTree::weighted();
    // Push the walked edge's property; read it back per path.
    // a -4-> x.rs -12-> deep: one path, register [4, 12].
    assert_eq!(
        vals(
            "//a(->e .($-::qty))+ | [:name = \"deep\"] | @. | product",
            &t
        ),
        vec![Value::Int(48)]
    );
    // Bare $- pushes the label; tree hops push [child].
    assert_eq!(
        vals("(/a .($-)){1} | $.", &t),
        vec![Value::Str("[child]".into())]
    );
    // Depth as a value: count the breadcrumbs.
    assert_eq!(
        vals("//a(->e .(1))+! | @. | count", &t),
        vec![Value::Int(2)]
    );
    // A named push lands as a named regula. (Spaced: glued
    // `.q(` would lex into the matcher name, exactly as
    // `/x.rs(...)` keeps its filename.)
    assert_eq!(
        vals("//a(->e .q($-::qty)){1;2}! | $.q", &t),
        vec![Value::Int(12)]
    );
}

#[test]
fn per_path_results() {
    // The diamond: two routes from a to deep, each its own
    // result capsa once the pattern pushes.
    let t = MockTree::diamond();
    assert_eq!(
        vals(
            "//a(->e .(:name))+ | [:name = \"deep\"] | @. | join(\"-\")",
            &t
        ),
        vec![
            Value::Str("x.rs-deep".into()),
            Value::Str("y.txt-deep".into()),
        ]
    );
    // Without pushes the two walks to deep are two threads too
    // (spec: Expansion paths); `@| collapse` makes them one.
    assert_eq!(run("//a(->e)+ | [:name = \"deep\"]", &t), vec![6, 6]);
    assert_eq!(
        run("//a(->e)+ | [:name = \"deep\"] @| collapse", &t),
        vec![6]
    );
}

#[test]
fn structural_edge_labels() {
    let t = MockTree::sample();
    // Every hop defines $-: tree, sibling, and reach walks.
    assert_eq!(run("/a[$- = \"[child]\"]", &t), vec![1]);
    assert_eq!(run("//w.rs\\deep[$- = \"[parent]\"]", &t), vec![6]);
    assert_eq!(run("/a/x.rs>y.txt[$- = \"[next]\"]", &t), vec![3]);
    assert_eq!(run("/a/y.txt<x.rs[$- = \"[prev]\"]", &t), vec![2]);
    // Before any hop, $- is null (nothing walked).
    assert!(run("/a[$- = \"[parent]\"]", &t).is_empty());
}

#[test]
fn pipelines_and_union() {
    let t = MockTree::sample();
    // count all .rs files (aggregation via @|)
    assert_eq!(vals("//*.rs @| count", &t), vec![Value::Int(3)]);
    // names, sorted and joined
    assert_eq!(
        vals("//*.rs:name @| sort @| join(\", \")", &t),
        vec![Value::Str("w.rs, x.rs, z.rs".into())]
    );
    // per-capsa transform: uppercase each name
    assert_eq!(
        vals("//x.rs:name | upper", &t),
        vec![Value::Str("X.RS".into())]
    );
    // union of two node sets: x.rs and z.rs
    assert_eq!(run("//x.rs || //z.rs", &t), vec![2, 5]);
    // aggregation applies to the whole union: count = 2
    assert_eq!(vals("//x.rs || //z.rs @| count", &t), vec![Value::Int(2)]);
}

#[test]
fn registers_and_subcontexts() {
    let t = MockTree::sample();
    // subcontext: count of .rs descendants per top-level dir
    // a has x.rs (1 rs); b has z.rs and w.rs (2 rs)
    assert_eq!(
        vals("/*[:name = \"a\"] | .(//*.rs @| count) | $.", &t),
        vec![Value::Int(1)]
    );
    assert_eq!(
        vals("/*[:name = \"b\"] | .(//*.rs @| count) | $.", &t),
        vec![Value::Int(2)]
    );
    // push then recall a named breadcrumb
    assert_eq!(
        vals("//x.rs:name | .saved | upper | $.saved", &t),
        vec![Value::Str("x.rs".into())]
    );
}

#[test]
fn predicates() {
    let t = MockTree::sample();
    // dirs with exactly 2 children: a and b
    assert_eq!(run("/*[:n-children = 2]", &t), vec![1, 4]);
    // structural condition: root children that have a z.rs child -> b
    assert_eq!(run("/*[/z.rs]", &t), vec![4]);
    // index predicate: first child of a -> x.rs
    assert_eq!(run("/a/*[1]", &t), vec![2]);
    // negation: non-leaf children of root -> a, b
    assert_eq!(run("/*[!:is-leaf]", &t), vec![1, 4]);
    // and + regex match on the name
    assert_eq!(run("//*[:is-leaf && :name == (/rs/)]", &t), vec![2, 5, 7]);
    // comparison against a literal, via core depth
    assert_eq!(run("//*[:depth > 2]", &t), vec![7]);
}

/// `[n]` selects by position among the hop's results (per source
/// node, as filtered by the brackets to its left) — not by
/// sibling position, which is `[:index = n]`.
#[test]
fn index_predicate_positions_among_hop_results() {
    // (root) ├ h ├ p ├ p └ sect ├ title ├ p └ p
    let names = vec![
        None,                 // 0 root
        Some("h".into()),     // 1
        Some("p".into()),     // 2
        Some("p".into()),     // 3
        Some("sect".into()),  // 4
        Some("title".into()), // 5
        Some("p".into()),     // 6
        Some("p".into()),     // 7
    ];
    let mut kids = HashMap::new();
    kids.insert(0, vec![1, 2, 3, 4]);
    kids.insert(4, vec![5, 6, 7]);
    let t = MockTree {
        names,
        kids,
        loose: Vec::new(),
        links: HashMap::new(),
        edge_props: HashMap::new(),
        prov: HashMap::new(),
    };
    // the first p child of the root — even though no p is the
    // root's first *child*
    assert_eq!(run("/p[1]", &t), vec![2]);
    assert_eq!(run("/p[2]", &t), vec![3]);
    assert_eq!(run("/sect/p[2]", &t), vec![7]);
    // a descendant hop yields one list per source node, so a
    // root-anchored //p[1] is the first p in the whole tree
    assert_eq!(run("//p[1]", &t), vec![2]);
    assert_eq!(run("//p[4]", &t), vec![7]);
    // sibling position is the metadata predicate
    assert_eq!(run("/p[:index = 2]", &t), vec![2]);
    assert_eq!(run("/*[:index = 3]", &t), vec![3]);
    assert_eq!(run("/p[:index = 1]", &t), Vec::<u64>::new());
    // brackets apply left to right: filter-then-index differs
    // from index-then-filter
    assert_eq!(run("/*[:index > 1][1]", &t), vec![2]);
    assert_eq!(run("/*[1][:index > 1]", &t), Vec::<u64>::new());
    // negative indexes count from the end of the same list
    assert_eq!(run("/p[-1]", &t), vec![3]);
    assert_eq!(run("//p[-1]", &t), vec![7]);
    assert_eq!(run("//p[-4]", &t), vec![2]);
    assert_eq!(run("/*[:index > 1][-1]", &t), vec![4]);
    // out of range (including 0) selects nothing
    assert_eq!(run("//p[0]", &t), Vec::<u64>::new());
    assert_eq!(run("//p[5]", &t), Vec::<u64>::new());
    assert_eq!(run("//p[-5]", &t), Vec::<u64>::new());
}

/// `[a..b]` keeps the inclusive positional span of the hop's
/// results; either end may be omitted or negative, and ends
/// clamp to the list.
#[test]
fn range_predicates() {
    let names = vec![
        None,                 // 0 root
        Some("h".into()),     // 1
        Some("p".into()),     // 2
        Some("p".into()),     // 3
        Some("sect".into()),  // 4
        Some("title".into()), // 5
        Some("p".into()),     // 6
        Some("p".into()),     // 7
    ];
    let mut kids = HashMap::new();
    kids.insert(0, vec![1, 2, 3, 4]);
    kids.insert(4, vec![5, 6, 7]);
    let t = MockTree {
        names,
        kids,
        loose: Vec::new(),
        links: HashMap::new(),
        edge_props: HashMap::new(),
        prov: HashMap::new(),
    };
    // //p matches nodes 2, 3, 6, 7 in document order
    assert_eq!(run("//p[2..3]", &t), vec![3, 6]);
    assert_eq!(run("//p[2..]", &t), vec![3, 6, 7]);
    assert_eq!(run("//p[..2]", &t), vec![2, 3]);
    assert_eq!(run("//p[2..-1]", &t), vec![3, 6, 7]);
    assert_eq!(run("//p[..-2]", &t), vec![2, 3, 6]);
    // ends clamp; an empty span selects nothing
    assert_eq!(run("//p[..9]", &t), vec![2, 3, 6, 7]);
    assert_eq!(run("//p[5..]", &t), Vec::<u64>::new());
    assert_eq!(run("//p[3..2]", &t), Vec::<u64>::new());
    // ranges compose sequentially with filters
    assert_eq!(run("/*[..2][:index > 1]", &t), vec![2]);
    assert_eq!(run("/*[:index > 1][..2]", &t), vec![2, 3]);
}

/// Value expressions: arithmetic over numeric readings, with
/// conventional precedence, null propagation, and exact integer
/// arithmetic (spec: Value Expressions and Arithmetic).
#[test]
fn value_expressions() {
    let t = MockTree::sample();
    // literals, precedence, grouping (root children: a, b)
    assert_eq!(run("/*[1 + 2 * 3 = 7]", &t), vec![1, 4]);
    assert_eq!(run("/*[(1 + 2) * 3 = 9]", &t), vec![1, 4]);
    // metadata operands: a is the first child, b the second
    assert_eq!(run("/*[:index + 1 = 2]", &t), vec![1]);
    assert_eq!(run("/*[:index * 2 = 4]", &t), vec![4]);
    assert_eq!(run("/*[:index - 2 = -1]", &t), vec![1]);
    assert_eq!(run("/*[- :index = -2]", &t), vec![4]);
    // div is always a float; idiv truncates; mod follows the
    // dividend's sign
    assert_eq!(run("/*[7 div 2 = 3.5]", &t), vec![1, 4]);
    assert_eq!(run("/*[7 idiv 2 = 3]", &t), vec![1, 4]);
    assert_eq!(run("/*[7 mod 2 = 1]", &t), vec![1, 4]);
    assert_eq!(run("/*[0 - 7 mod 2 = -1]", &t), vec![1, 4]);
    // integer arithmetic is exact beyond float precision
    // (2^53 + 1 would round away under f64)
    assert_eq!(
        run("/*[9007199254740993 + 0 = 9007199254740993]", &t),
        vec![1, 4]
    );
    // division by zero gives inf or nan, both truthy as IEEE floats;
    // non-numeric operands are null, and null is falsy
    assert_eq!(run("/*[1 div 0]", &t), run("/*", &t));
    assert_eq!(run("/*[1 idiv 0]", &t), run("/*", &t));
    assert_eq!(run("/*[:name * 2]", &t), Vec::<u64>::new());
    // a glued minus stays a name character: no such property,
    // so the comparison selects nothing (but parses)
    assert_eq!(run("/*[::a-b = 1]", &t), Vec::<u64>::new());
    // boolean groups in operand position keep their old meaning
    assert_eq!(
        run("/*[(:index = 1 || :index = 2) && :is-leaf]", &t),
        Vec::<u64>::new()
    );
}

/// Value expressions as pipeline commands: computed topics and
/// computed (pushed) columns.
#[test]
fn value_expression_commands() {
    let t = MockTree::sample();
    // computed topic on one node: x.rs is child 1 of a
    assert_eq!(vals("/a/x.rs | :index * 2", &t), vec![Value::Int(2)]);
    // a computed column pushed per capsa, then aggregated:
    // indexes 1 and 2 doubled sum to 6
    assert_eq!(
        vals("/* | .double(:index * 2) | $.double @| sum", &t),
        vec![Value::Int(6)]
    );
    // grouped expression command
    assert_eq!(vals("/a/x.rs | (:index + 1) * 3", &t), vec![Value::Int(6)]);
}

/// Keyed aggregates reorder or filter capsae by per-capsa keys,
/// preserving node identity so later commands keep working.
/// `@| group(k) | count` runs fused (no member lists built);
/// it must answer exactly as the two commands do — same counts,
/// same key fields for recall, same order — whether the count
/// is the result or feeds a later command.
#[test]
fn fused_group_count_matches_the_two_commands() {
    let t = MockTree::sample();
    let fused = vals("//* @| group(d = :depth) | count", &t);
    // The unfused route: the group's list topic, counted inside
    // an operand, so no `| count` command follows the group.
    let unfused = vals("//* @| group(d = :depth) | %(n = ($_ @| count)) | :n", &t);
    assert_eq!(fused, unfused);
    assert!(fused.len() > 1);
    assert_eq!(
        fused
            .iter()
            .map(|v| v.to_string().parse::<i64>().unwrap())
            .sum::<i64>(),
        vals("//* @| count", &t)[0]
            .to_string()
            .parse::<i64>()
            .unwrap()
    );
    // The count then feeding a record with the recalled key.
    let recs = vals("//* @| group(d = :depth) | count | %($.d; n = $_)", &t);
    let refs = vals("//* @| group(d = :depth) | %($.d; n = ($_ @| count))", &t);
    assert_eq!(recs, refs);
    // A filter on the count keeps the fused capsae's registers.
    assert_eq!(
        vals("//* @| group(d = :depth) | count | [$_ > 1] | $.d", &t),
        vals(
            "//* @| group(d = :depth) | %(d = $.d; n = ($_ @| count)) | [:n > 1] | :d",
            &t
        )
    );
}

#[test]
fn keyed_aggregates() {
    let t = MockTree::sample();
    // sort leaves by name: w.rs, x.rs, y.txt, z.rs
    assert_eq!(
        vals("//*[:is-leaf] @| sort_by(:name) | :name", &t),
        vec![
            Value::Str("w.rs".into()),
            Value::Str("x.rs".into()),
            Value::Str("y.txt".into()),
            Value::Str("z.rs".into()),
        ]
    );
    // descending via reverse; positional selection takes top-2
    assert_eq!(
        vals(
            "//*[:is-leaf] @| sort_by(:name) @| reverse @| [..2] | :name",
            &t
        ),
        vec![Value::Str("z.rs".into()), Value::Str("y.txt".into())]
    );
    // ... which is what top does in one call
    assert_eq!(
        vals("//*[:is-leaf] @| top(2, :name) | :name", &t),
        vec![Value::Str("z.rs".into()), Value::Str("y.txt".into())]
    );
    assert_eq!(
        vals("//*[:is-leaf] @| bottom(1, :name) | :name", &t),
        vec![Value::Str("w.rs".into())]
    );
    // extreme-key selection keeps node identity (w.rs is node 7)
    assert_eq!(run("//*[:is-leaf] @| max_by(:depth)", &t), vec![7]);
    // ... and every tied capsa: both depth-1 nodes
    assert_eq!(run("//* @| min_by(:depth)", &t), vec![1, 4]);
    // unique_by keeps the first capsa per distinct key
    assert_eq!(run("//* @| unique_by(:depth)", &t), vec![1, 2, 7]);
    // composite keys tie-break
    assert_eq!(
        vals("//*[:is-leaf] @| sort_by(:depth, :name) | :name", &t)[0],
        Value::Str("x.rs".into())
    );
}

/// Positional selection (`@| [n]`, whole-context) and per-capsa
/// filters (`| [cond]`) as pipeline commands, each on its
/// doctrinally correct pipe.
#[test]
fn positional_and_filter_commands() {
    let t = MockTree::sample();
    assert_eq!(run("//*.rs @| [1]", &t), vec![2]);
    assert_eq!(run("//*.rs @| [-1]", &t), vec![7]);
    assert_eq!(run("//*.rs @| [2..]", &t), vec![5, 7]);
    assert_eq!(
        vals("//*.rs @| [..2] | :name", &t),
        vec![Value::Str("x.rs".into()), Value::Str("z.rs".into())]
    );
    // per-capsa filter: each capsa tested against its node
    assert_eq!(run("//* | [:is-leaf]", &t), vec![2, 3, 5, 7]);
    assert_eq!(run("//*.rs @| sort_by(:name) | [:depth > 2]", &t), vec![7]);
    // `| [1]` parses (it is a row of a table, spec: The Table Kind)
    // and refuses at the run on anything else, pointing at `@| [n]`
    assert!(parse(&lex("//* | [1]").unwrap()).is_ok());
    assert!(parse(&lex("//* @| [:is-leaf]").unwrap()).is_err());
    // ...and the inline `@|` enforces the same discipline
    assert!(parse(&lex("//a | ((::x @| [:is-leaf] @| count))").unwrap()).is_err());
    assert!(parse(&lex("//a | ((::x @| bogus))").unwrap()).is_err());
}

/// The `@_` snapshot must materialize wherever the command reads
/// it: inside conditional/match operands, and in keyed-aggregate
/// keys (a silent `peers: None` there made `@_` null — and a
/// null key excludes every capsa).
#[test]
fn context_snapshot_in_cond_and_agg_keys() {
    let t = MockTree::sample();
    assert_eq!(
        vals("//*.rs | ((@_ @| count) > 2 ? \"many\" : \"few\")", &t),
        vec![
            Value::Str("many".into()),
            Value::Str("many".into()),
            Value::Str("many".into()),
        ]
    );
    // Keys (@_ @| count) - $ord = 2, 1, 0 — the minimum is the
    // third file; with `@_` null every capsa would drop.
    assert_eq!(run("//*.rs @| min_by((@_ @| count) - $ord)", &t), vec![7]);
}

#[test]
fn core_metadata_projection() {
    let t = MockTree::sample();
    assert_eq!(
        vals("/a/*:name", &t),
        vec![Value::Str("x.rs".into()), Value::Str("y.txt".into())]
    );
    assert_eq!(vals("/a:n-children", &t), vec![Value::Int(2)]);
    assert_eq!(vals("/b/deep:depth", &t), vec![Value::Int(2)]);
    assert_eq!(vals("/a/x.rs:is-leaf", &t), vec![Value::Bool(true)]);
    assert_eq!(vals("/b:is-leaf", &t), vec![Value::Bool(false)]);
    assert_eq!(vals("/a/y.txt:index", &t), vec![Value::Int(2)]);
    // parent metadata and level flags
    assert_eq!(vals("/a/x.rs:parent-id", &t), vec![Value::Int(1)]);
    assert_eq!(vals("/a/x.rs:parent-index", &t), vec![Value::Int(1)]);
    assert_eq!(vals("/a:is-top-level", &t), vec![Value::Bool(true)]);
    assert_eq!(vals("/a/x.rs:is-top-level", &t), vec![Value::Bool(false)]);
    // root-relative location paths (root contributes no segment)
    assert_eq!(
        vals("//w.rs:name-path", &t),
        vec![Value::Str("/b/deep/w.rs".into())]
    );
    assert_eq!(
        vals("//w.rs:index-path", &t),
        vec![Value::Str("/2/2/1".into())]
    );
    assert_eq!(
        vals("//w.rs:id-path", &t),
        vec![Value::Str("/4/6/7".into())]
    );
}

#[test]
fn provenance_core_metadata() {
    let mut t = MockTree::sample();
    // x.rs carries a full triple; y.txt only a source; z.rs only
    // a dpid; everything else answers null.
    let (secs, nanos, off) = crate::temporal::parse_iso("2026-04-07T02:00:01Z").unwrap();
    t.prov.insert(
        2,
        Provenance {
            source: Some("api-gateway".into()),
            instant: Some((secs, nanos, off)),
            dpid: Some("request-42".into()),
            ..Default::default()
        },
    );
    t.prov.insert(
        3,
        Provenance {
            source: Some("api-gateway".into()),
            ..Default::default()
        },
    );
    t.prov.insert(
        5,
        Provenance {
            dpid: Some("row-7".into()),
            ..Default::default()
        },
    );
    // Components, typed.
    assert_eq!(
        vals("/a/x.rs:source", &t),
        vec![Value::Str("api-gateway".into())]
    );
    assert_eq!(
        vals("/a/x.rs:instant", &t),
        vec![Value::Instant {
            secs,
            nanos,
            offset_min: off,
            calendar: Default::default()
        }]
    );
    assert_eq!(
        vals("/a/x.rs:dpid", &t),
        vec![Value::Str("request-42".into())]
    );
    // The composite follows kaiv's optionality grammar.
    assert_eq!(
        vals("/a/x.rs:provenance", &t),
        vec![Value::Str(
            "?api-gateway@2026-04-07T02:00:01Z#request-42".into()
        )]
    );
    assert_eq!(
        vals("/a/y.txt:provenance", &t),
        vec![Value::Str("?api-gateway".into())]
    );
    assert_eq!(
        vals("/b/z.rs:provenance", &t),
        vec![Value::Str("?#row-7".into())]
    );
    // Nulls where nothing is recorded.
    assert_eq!(vals("/b/deep:source", &t), vec![Value::Null]);
    assert_eq!(vals("/b/deep:instant", &t), vec![Value::Null]);
    assert_eq!(vals("/b/deep:provenance", &t), vec![Value::Null]);
    // Typed temporal comparison in a criterion.
    assert_eq!(run("//*[:instant > 2020-01-01]", &t), vec![2]);
    assert_eq!(run("//*[:instant > 2030-01-01]", &t), Vec::<u64>::new());
    // Layering: inner wins per component, outer fills the rest.
    let inner = Provenance {
        source: Some("leaf".into()),
        ..Default::default()
    };
    let outer = Provenance {
        source: Some("mount".into()),
        dpid: Some("d1".into()),
        ..Default::default()
    };
    let merged = inner.or(outer);
    assert_eq!(merged.source.as_deref(), Some("leaf"));
    assert_eq!(merged.dpid.as_deref(), Some("d1"));
    assert!(merged.instant.is_none());
    assert_eq!(Provenance::default().canonical(), None);
}

#[test]
fn ancestor_reach() {
    let t = MockTree::sample();
    // ancestors of w.rs that are directories: deep(1), b(2)
    assert_eq!(run("//w.rs\\\\*", &t), vec![6, 4, 0]);
    assert_eq!(run("//w.rs\\\\?*", &t), vec![6]); // nearest
    assert_eq!(run("//w.rs\\\\!*", &t), vec![0]); // farthest (root)
    // the bare ascent, and the two tautologies: the nearest
    // ancestor is the parent, the farthest is the root
    assert_eq!(run("//w.rs\\\\", &t), run("//w.rs\\\\*", &t));
    assert_eq!(run("//w.rs\\\\?", &t), run("//w.rs\\", &t));
    assert_eq!(run("//w.rs\\\\!", &t), run("^", &t));
    assert_eq!(run("//w.rs/..", &t), run("//w.rs\\", &t));
    assert_eq!(run("//w.rs/...", &t), run("//w.rs\\\\", &t));
}

#[test]
fn marks() {
    let t = MockTree::sample();
    // Mark mid-path; recall in a later step predicate — the
    // intra-path back-reference (Cypher's node variables).
    assert_eq!(run("/a .a /*[:name = $$.a:name]", &t), Vec::<u64>::new());
    assert_eq!(run("//deep .d /w.rs[$$.d:name = \"deep\"]", &t), vec![7]);
    // Recall in a pipeline command operand.
    assert_eq!(
        vals("//w.rs .w \\\\!* | $$.w:name", &t),
        vec![Value::Str("w.rs".into())]
    );
    // Marks inside patterns: recall in a group predicate sees
    // the walk's own marks.
    assert_eq!(run("/a/x.rs .x (->ref)[$$.x:name = \"x.rs\"]", &t), vec![7]);
    // The context-typed push: bare .name in a SCALAR context
    // still feeds the register, not the marks.
    assert_eq!(vals("//*.rs @| count | .n | $.n", &t), vec![Value::Int(3)]);
    // An unset mark yields nothing (predicate false), not an
    // error.
    assert_eq!(run("/a/*[$$.nope:name = \"a\"]", &t), Vec::<u64>::new());
    // Marks seed sub-navigation: an anchored operand's NESTED
    // predicate still sees the thread's marks...
    assert_eq!(
        run("/a/x.rs .x | [^//w.rs[$$.x:name = \"x.rs\"]]", &t),
        vec![2]
    );
    // ...and a subcontext body's branch can anchor on them.
    assert_eq!(
        vals("/a/x.rs .x | .n($$.x:name) | $.n", &t),
        vec![Value::Str("x.rs".into())]
    );
}

#[test]
fn shell_command() {
    let t = MockTree::sample();
    // The literal spellings are retired (ruling 2026-11-02): the
    // backtick refuses at the lexer, naming the mount.
    let e = crate::Query::parse("/a/x.rs | :name | `tr a-z A-Z`", &t)
        .err()
        .expect("retired")
        .to_string();
    assert!(e.contains("sh=shell:"), "{e}");
    // Unmounted, the environment command refuses before the run.
    assert!(crate::run("/a/x.rs | :name | sh:tr(a-z; A-Z)", &t).is_err());
    // Mounted, the topic goes through the program; a failure nulls.
    struct Shelly(MockTree);
    impl AstAdapter for Shelly {
        fn root(&self) -> NodeId {
            self.0.root()
        }
        fn children(&self, n: NodeId) -> Vec<NodeId> {
            self.0.children(n)
        }
        fn name(&self, n: NodeId) -> Option<String> {
            self.0.name(n)
        }
        fn parent(&self, n: NodeId) -> Option<NodeId> {
            self.0.parent(n)
        }
        fn links(&self, n: NodeId) -> Vec<(String, NodeId)> {
            self.0.links(n)
        }
    }
    let t = Shelly(MockTree::sample());
    let shell = crate::Run {
        environments: vec![crate::Environment::parse("sh", "shell:").unwrap()],
        ..crate::Run::ambient()
    };
    let run_shell = |q: &str| {
        crate::Query::parse_with(q, &crate::Defs::default(), &t, &shell)
            .unwrap()
            .run(&t, &shell)
            .map(|o| o.result)
    };
    let got = match run_shell("/a/x.rs | :name | sh:tr(a-z; A-Z)").unwrap() {
        QueryResult::Values(vs) => vs,
        _ => panic!("values"),
    };
    assert_eq!(got, vec![Value::Str("X.RS".into())]);
    let got = match run_shell("/a/x.rs | :name | sh:false").unwrap() {
        QueryResult::Values(vs) => vs,
        _ => panic!("values"),
    };
    assert_eq!(got, vec![Value::Null]);
}

#[test]
fn node_mode_json() {
    let t = MockTree::sample();
    // Serialize a subtree: x.rs has no children (leaf) → its
    // scalar; a.rs's parent 'a' has children → object.
    let out = match crate::run("/a | json", &t).unwrap() {
        QueryResult::Values(vs) => vs,
        _ => panic!("values"),
    };
    assert_eq!(out.len(), 1);
    assert!(out[0].to_string().contains("x.rs"));
    // decode(json): array → list, spread into rows.
    let out = match crate::run("^ | \"[1,2,3]\" | decode(json) | ...", &t).unwrap() {
        QueryResult::Values(vs) => vs,
        _ => panic!("values"),
    };
    assert_eq!(out, vec![Value::Int(1), Value::Int(2), Value::Int(3)]);
    // XML: | xml serializes a subtree; decode(xml) → value.
    let out = match crate::run("/a | xml", &t).unwrap() {
        QueryResult::Values(vs) => vs,
        _ => panic!("values"),
    };
    assert!(out[0].to_string().starts_with("<a>") && out[0].to_string().contains("x.rs"));
    let out = match crate::run("^ | \"<r><x>1</x></r>\" | decode(xml) | json", &t).unwrap() {
        QueryResult::Values(vs) => vs,
        _ => panic!("values"),
    };
    assert_eq!(out, vec![Value::Str("{\"x\": \"1\"}".into())]);
    // Object → record; round-trips through json.
    let out = match crate::run("^ | \"{\\\"a\\\":1}\" | decode(json) | json", &t).unwrap() {
        QueryResult::Values(vs) => vs,
        _ => panic!("values"),
    };
    assert_eq!(out, vec![Value::Str("{\"a\": 1}".into())]);
}

#[test]
fn value_match() {
    let t = MockTree::sample();
    // Equality arms; scrutinee evaluated once; else required.
    assert_eq!(
        vals("/a/* | (:name ?= \"x.rs\" ? 1 : \"y.txt\" ? 2 : 0)", &t),
        vec![Value::Int(1), Value::Int(2)]
    );
    // A regex arm tests == instead of equality.
    assert_eq!(
        vals(
            "//*.rs @| [..1] | (:name ?= (/^x/) ? \"ex\" : \"other\")",
            &t
        ),
        vec![Value::Str("ex".into())]
    );
    // No arm hits: the else.
    assert_eq!(
        vals("/a/*[1] | (:name ?= \"nope\" ? 1 : 9)", &t),
        vec![Value::Int(9)]
    );
}

#[test]
fn anchored_operands() {
    let t = MockTree::sample();
    // Same-name-as-some-node-under-/a: compares existentially
    // against a set gathered from the root, not the candidate.
    assert_eq!(run("//*[:name = ^/a/*:name]", &t), vec![2, 3]);
    // Structural: keep nodes only if the arbor has a w.rs
    // anywhere — true from every candidate.
    assert_eq!(run("/a/*[^//w.rs]", &t), vec![2, 3]);
    // Inline pipe with an anchored head: the whole-tree count,
    // readable from any capsa.
    assert_eq!(
        vals("/a/*[1] | (^//*.rs @| count)", &t),
        vec![Value::Int(3)]
    );
}

#[test]
fn outer_spread() {
    let t = MockTree::sample();
    // x.rs has a ref (to w.rs); y.txt has none. The plain
    // spread drops the refless thread; the outer spread keeps
    // it with a null topic.
    assert_eq!(
        vals("/a/* | .m(->ref:name) | $.m | ...", &t),
        vec![Value::Str("w.rs".into())]
    );
    assert_eq!(
        vals("/a/* | .m(->ref:name) | $.m | ...?", &t),
        vec![Value::Str("w.rs".into()), Value::Null]
    );
}

#[test]
fn outer_correlation() {
    let t = MockTree::sample();
    // Rows: every .rs file (the driver). Joined: /a's children
    // with a matching name. Only x.rs finds a partner; the
    // outer marker keeps the other rows with a null witness.
    let q = "//*.rs <=> /a/*[:name = $$0:name]";
    assert_eq!(run(q, &t), vec![2]);
    let q = "//*.rs <=>? /a/*[:name = $$0:name]";
    assert_eq!(run(q, &t), vec![2, 5, 7]);
    // The witness reads back: the partner's name, or null.
    assert_eq!(
        vals("//*.rs <=>? /a/*[:name = $$0:name] | $$1:name", &t),
        vec![Value::Str("x.rs".into()), Value::Null, Value::Null]
    );
    // The anti-join: a pipeline filter is the WHERE clause,
    // evaluated under the capsa's witness (null-propagating),
    // so testing the null slot keeps only the unmatched rows.
    let q = "//*.rs <=>? /a/*[:name = $$0:name] | [!$$1:name]";
    assert_eq!(run(q, &t), vec![5, 7]);
    // And the matched-only filter is its complement.
    let q = "//*.rs <=>? /a/*[:name = $$0:name] | [$$1:name]";
    assert_eq!(run(q, &t), vec![2]);
}

#[test]
fn outer_correlation_indirect_ctx() {
    let t = MockTree::sample();
    // A correlated reference reached *indirectly* — through a
    // value match's arm, or a nested step predicate — is still
    // part of the entry's ON clause, skipped under the outer
    // join's null binding exactly as a bare one is. Otherwise
    // the unmatched rows (z.rs, w.rs) are wrongly dropped, and
    // semantically equivalent spellings diverge.
    let q = "//*.rs <=>? /a/*[(:name ?= $$0:name ? 1 : 0) = 1]";
    assert_eq!(run(q, &t), vec![2, 5, 7]);
    // The same reference, buried in a nested step predicate
    // (`$$` inside the `/*` step's `[...]`). /a's children are
    // leaves, so no real binding admits any driver; only the
    // null binding keeps them.
    let q = "//*.rs <=>? /a/*[/*[$$0:name = :name]]";
    assert_eq!(run(q, &t), vec![2, 5, 7]);
}

#[test]
fn now_operand() {
    let t = MockTree::sample();
    // The default (library) adapter binds no invocation instant,
    // so now() reads as null.
    assert_eq!(vals("^ | (now())", &t), vec![Value::Null]);

    // A runner that pins the instant: now() denotes it, displayed
    // as UTC (offset_min = Some(0)).
    struct Clocked(MockTree, i64, u32);
    impl AstAdapter for Clocked {
        fn root(&self) -> NodeId {
            self.0.root()
        }
        fn children(&self, n: NodeId) -> Vec<NodeId> {
            self.0.children(n)
        }
        fn name(&self, n: NodeId) -> Option<String> {
            self.0.name(n)
        }
        fn parent(&self, n: NodeId) -> Option<NodeId> {
            self.0.parent(n)
        }
    }
    let (s, n, _) = crate::temporal::parse_iso("2026-07-12T09:00:00Z").unwrap();
    let t = Clocked(MockTree::sample(), s, n);
    let clocked = Run {
        now: Some((t.1, t.2)),
        ..Default::default()
    };
    let got = match eval_with(
        &parse(&lex("^ | (now())").unwrap()).unwrap(),
        &t,
        Some(clocked),
    ) {
        QueryResult::Values(vs) => vs,
        _ => panic!("expected values"),
    };
    assert_eq!(
        got,
        vec![Value::Instant {
            secs: s,
            nanos: n,
            offset_min: Some(0),
            calendar: Default::default(),
        }]
    );
    assert_eq!(got[0].to_string(), "2026-07-12T09:00:00Z");
}

#[test]
fn temporal_arith_overflow_nulls() {
    let sc: &dyn Fn(&str) -> Option<(f64, String)> = &crate::value::quantity::scale_expr;
    let inst = |secs| Value::Instant {
        secs,
        nanos: 0,
        offset_min: Some(0),
        calendar: Default::default(),
    };
    let dur = |secs| Value::seconds(secs, 0);
    // Instant + Duration past i64::MAX seconds: null, never a
    // panic (debug) or wrapped garbage instant (release).
    assert!(matches!(
        arith(ArithOp::Add, &inst(i64::MAX), &dur(1), sc),
        Value::Null
    ));
    // Span + span is the quantity arithmetic of dimension T, a
    // float magnitude: no overflow to null.
    assert!(matches!(
        arith(ArithOp::Add, &dur(i64::MAX), &dur(1), sc),
        Value::Quantity { .. }
    ));
    // Instant − Instant underflow.
    assert!(matches!(
        arith(ArithOp::Sub, &inst(i64::MIN), &inst(i64::MAX), sc),
        Value::Null
    ));
    // The non-overflowing path is unchanged.
    assert_eq!(
        arith(ArithOp::Add, &inst(0), &dur(60), sc).to_string(),
        "1970-01-01T00:01:00Z"
    );
}

#[test]
fn contains_and_regex_null_propagate() {
    let sc: &dyn Fn(&str) -> Option<(f64, String)> = &crate::value::quantity::scale_expr;
    let name = Value::Str("chapter one".into());
    // A null right-hand side must NOT vacuously match (the bug:
    // Null stringified to "" is a substring of everything).
    assert!(!compare(&name, CmpOp::Contains, &Value::Null, sc));
    // An actual empty string still matches, as it should.
    assert!(compare(
        &name,
        CmpOp::Contains,
        &Value::Str(String::new()),
        sc
    ));
    // A real substring still matches.
    assert!(compare(
        &name,
        CmpOp::Contains,
        &Value::Str("one".into()),
        sc
    ));
    // `=~` against a null pattern doesn't match everything (the
    // bug: Regex::new("") matches any input).
    assert!(!compare(&name, CmpOp::Match, &Value::Null, sc));
    // `!~` against null is true, mirroring `!=` on null.
    assert!(compare(&name, CmpOp::NotMatch, &Value::Null, sc));
    // A real pattern still matches.
    assert!(compare(
        &name,
        CmpOp::Match,
        &Value::Str("^chap".into()),
        sc
    ));
}

#[test]
fn nav_command_resumes_navigation() {
    let t = MockTree::sample();
    // A path-shaped command fans out per thread — the pipeline
    // spelling of a path continuation.
    assert_eq!(run("/* | /*", &t), vec![2, 3, 5, 6]);
    // The register rides across the hop: collect at both
    // levels, lay out as a record.
    let vs = vals("/* | .dir(:name) | /* | .file(:name) | %.", &t);
    assert_eq!(vs.len(), 4);
    let Value::Record(fields) = &vs[0] else {
        panic!("expected a record, got {:?}", vs[0]);
    };
    assert_eq!(
        fields[0],
        ("dir".to_string(), Value::Str("a".into())),
        "first column is the ancestor's push"
    );
    assert_eq!(fields[1], ("file".to_string(), Value::Str("x.rs".into())));
    // A trailing projection ends the command in scalar mode,
    // exactly like a branch projection.
    assert_eq!(
        vals("/a | /*:name", &t),
        vec![Value::Str("x.rs".into()), Value::Str("y.txt".into())]
    );
    // `^` — the anchored command navigates from the root.
    assert_eq!(run("/a/x.rs | ^/b", &t), vec![4]);
    // `(m)` — anchor on the thread's own pebble; both the
    // path-side and the pipe-side mark spellings feed it.
    assert_eq!(run("/a .m /x.rs | $$.m/y.txt", &t), vec![3]);
    assert_eq!(run("/a | .m | /x.rs | $$.m/y.txt", &t), vec![3]);
    // Arrows hop crosslinks as commands too.
    assert_eq!(run("/a/x.rs | ->ref", &t), vec![7]);
    // File-first: a projection enters scalar mode, the push
    // returns to navigation mode, and the hop is legal again.
    assert_eq!(run("/a | :name | . | /*", &t), vec![2, 3]);
}

#[test]
fn nav_command_mode_discipline() {
    let refuse = |q: &str| {
        parse(&lex(q).unwrap())
            .expect_err("should refuse")
            .to_string()
    };
    // Scalar mode: a hop would drop the live topic.
    assert!(refuse("/a:name | /b").contains("scalar mode"));
    assert!(refuse("/a | :name | /b").contains("scalar mode"));
    // Hops are per-thread: neither `@|` nor `$|` takes them.
    assert!(refuse("/a @| /b").contains("per-thread"));
    assert!(refuse("/a | ... $| /b").contains("map pipe"));
}

#[test]
fn named_groups_push_into_the_register() {
    // A named group is a capture, read from `%+`; filing it is
    // explicit — `| %+ | .%` pushes every group under its name,
    // seen by the record view and recalled as a register.
    let t = MockTree::sample();
    let bare = vals(
        "/a/* | [:name == (/^(?<stem>\\w+)\\.(?<ext>\\w+)$/)] | %.",
        &t,
    );
    assert!(
        bare.iter()
            .all(|r| matches!(r, Value::Record(f) if f.is_empty())),
        "{bare:?}"
    );
    let stems = vals(
        "/a/* | [:name == (/^(?<stem>\\w+)\\.(?<ext>\\w+)$/)] | %+:stem",
        &t,
    );
    assert!(
        stems.iter().all(|v| matches!(v, Value::Str(_))),
        "{stems:?}"
    );
    let q = "/a/* | [:name == (/^(?<stem>\\w+)\\.(?<ext>\\w+)$/)] | %+ | .% | %.";
    let rows = vals(q, &t);
    assert!(!rows.is_empty());
    for r in &rows {
        let Value::Record(fields) = r else {
            panic!("expected a record, got {r:?}");
        };
        let keys: Vec<&str> = fields.iter().map(|(k, _)| k.as_str()).collect();
        assert_eq!(keys, vec!["stem", "ext"], "{r:?}");
    }
    let exts = vals(
        "/a/* | [:name == (/^(?<stem>\\w+)\\.(?<ext>\\w+)$/)] | %+ | .% | $.ext",
        &t,
    );
    assert!(
        exts.iter()
            .all(|v| matches!(v, Value::Str(s) if s == "rs" || s == "txt")),
        "{exts:?}"
    );
    // the numbered captures still bind alongside
    let stems = vals("/a/* | [:name == (/^(?<stem>\\w+)\\.(\\w+)$/)] | $1", &t);
    assert_eq!(stems.len(), exts.len());
}

#[test]
fn record_fields_and_named_captures() {
    // Ruling #48: `:name` reads a record's field; `%+` is the
    // named-captures record.
    let t = MockTree::sample();
    let q = "/a/* | [:name == (/^(?<stem>\\w+)\\.(?<ext>\\w+)$/)] | %+:ext";
    let exts = vals(q, &t);
    assert!(
        !exts.is_empty()
            && exts
                .iter()
                .all(|v| matches!(v, Value::Str(s) if s == "rs" || s == "txt")),
        "{exts:?}"
    );
    let recs = vals("/a/* | [:name == (/^(?<stem>\\w+)/)] | %+", &t);
    assert!(
        recs.iter()
            .all(|r| matches!(r, Value::Record(f) if f.len() == 1 && f[0].0 == "stem")),
        "{recs:?}"
    );
    // a constructed record's field, from the topic and from a register
    let ones = vals("/a/* | %(:name; n = 1) | :n", &t);
    assert!(
        !ones.is_empty() && ones.iter().all(|v| matches!(v, Value::Int(1))),
        "{ones:?}"
    );
    let ones = vals("/a/* | %(:name; n = 1) | .r | $.r:n", &t);
    assert!(
        !ones.is_empty() && ones.iter().all(|v| matches!(v, Value::Int(1))),
        "{ones:?}"
    );
    // a missing field, and a non-record, read as null
    let nulls = vals("/a/* | %(:name; n = 1) | :zzz", &t);
    assert!(nulls.iter().all(|v| matches!(v, Value::Null)), "{nulls:?}");
    // outside any match, `%+` is the empty record
    let empty = vals("/a/* | %+", &t);
    assert!(
        empty
            .iter()
            .all(|v| matches!(v, Value::Record(f) if f.is_empty())),
        "{empty:?}"
    );
}

#[test]
fn list_literal_gathers_every_value() {
    // Ruling #52: `@(a; b)` — each item contributes all its
    // values; the rounded `*(…)` spells the same.
    let t = MockTree::sample();
    assert_eq!(
        vals("/a | @(1; \"x\"; 2 + 1)", &t),
        vec![Value::list(vec![
            Value::Int(1),
            Value::Str("x".into()),
            Value::Int(3)
        ])]
    );
    let gathered = vals("/a | @(/*:name)", &t);
    assert!(
        matches!(&gathered[0], Value::List(items) if items.len() > 1),
        "{gathered:?}"
    );
    assert_eq!(vals("/a | @()", &t), vec![Value::list(Vec::new())]);
    assert_eq!(vals("/a | *(1; 2)", &t), vals("/a | @(1; 2)", &t));
    // display: the Quarb form, bare scalars, quoted strings
    assert_eq!(
        vals("/a | @(1; \"x\")", &t)[0].display_form(),
        "@(1; \"x\")"
    );
}

#[test]
fn json_and_jsonl_over_the_stream() {
    // Ruling #51: `| json` serializes each value; `@| json` the
    // whole stream as one array; `@| jsonl` one document per line.
    let t = MockTree::sample();
    let each = vals("/a/* | :name | json", &t);
    assert!(
        each.len() > 1
            && each
                .iter()
                .all(|v| matches!(v, Value::Str(s) if s.starts_with('"'))),
        "{each:?}"
    );
    let whole = vals("/a/* | :name @| json", &t);
    assert!(
        matches!(&whole[..], [Value::Str(s)] if s.starts_with("[\"") && s.ends_with(']')),
        "{whole:?}"
    );
    let lines = vals("/a/* | :name @| jsonl", &t);
    assert!(
        matches!(&lines[..], [Value::Str(s)] if s.lines().count() == each.len()),
        "{lines:?}"
    );
    // a record's JSON is unchanged by the display ruling
    let rec = vals("/a/* | %(n = :name) | json", &t);
    assert!(
        rec.iter()
            .all(|v| matches!(v, Value::Str(s) if s.starts_with("{\"n\": "))),
        "{rec:?}"
    );
}

#[test]
fn record_push_in_one_step() {
    // Ruling #49: `.%(...)` builds and pushes; `.name%(...)` names it.
    let t = MockTree::sample();
    let ones = vals("/a/* | .r%(:name; n = 1) | $.r:n", &t);
    assert!(
        !ones.is_empty() && ones.iter().all(|v| matches!(v, Value::Int(1))),
        "{ones:?}"
    );
    let views = vals("/a/* | .r%(:name) | %.", &t);
    assert!(
        views
            .iter()
            .all(|v| matches!(v, Value::Record(f) if f.len() == 1 && f[0].0 == "r")),
        "{views:?}"
    );
    let anon = vals("/a/* | .%(:name; n = 2) | $.:n", &t);
    assert!(
        !anon.is_empty() && anon.iter().all(|v| matches!(v, Value::Int(2))),
        "{anon:?}"
    );
    // the enriched form carries the register's named regulae
    let rich = vals("/a/* | .k(:name) | .%%(n = 3) | $.:k", &t);
    assert!(
        !rich.is_empty() && rich.iter().all(|v| matches!(v, Value::Str(_))),
        "{rich:?}"
    );
}

#[test]
fn mark_array_symmetry() {
    // Anchors in double parentheses — the canonical spelling
    // (the single-paren spellings still parse, except `(.)`,
    // which is now the register file).
    let t = MockTree::sample();
    // Bare `.` pockets the node anonymously — mid-path and as
    // a pipe command — and `(N)` / `(.)` recall positionally.
    assert_eq!(run("/a . /x.rs | ((.1))/y.txt", &t), vec![3]);
    assert_eq!(run("/a . /x.rs | $$./y.txt", &t), vec![3]);
    assert_eq!(run("/a | . | /x.rs | ((.1))/y.txt", &t), vec![3]);
    // Names are references over the same slots: the named mark
    // is also position 2. (Bare `| (2)` stays the literal 2 —
    // digit anchors need a continuation; the bare re-seed
    // spellings are `(.)`, `(@)`, `(@name)`.)
    assert_eq!(
        vals("/a . /x.rs .m | ((.2)):name", &t),
        vec![Value::Str("x.rs".into())]
    );
    // The null wart is gone: a bare push in node context marks
    // and files NOTHING in the register.
    assert_eq!(
        vals("/a | . | @. | json", &t),
        vec![Value::Str("[]".into())]
    );
    // Positional recall of marks lives in operand space too.
    assert_eq!(run("/a . /*[((.1))/x.rs]", &t), vec![2, 3]);
}

#[test]
fn marks_fan_out() {
    let t = MockTree::sample();
    // `(@)` re-seeds the thread from every pocket, in push
    // order — one fork per marked node.
    assert_eq!(run("/a/x.rs | . | ^/b/z.rs | . | ((@))", &t), vec![2, 5]);
    // ... and navigation continues from each in parallel.
    assert_eq!(run("/a | . | ^/b | . | ((@))/*.rs", &t), vec![2, 5]);
    // `(@name)` fans over every mark under one name, shadowed
    // ones included.
    assert_eq!(run("/a .s /x.rs | ^/b .s /z.rs | ((@s))", &t), vec![1, 4]);
    // An empty pocket yields nothing, never an error.
    assert_eq!(run("/a | ((@))/x.rs", &t), Vec::<u64>::new());
}

#[test]
fn numeric_mark_names_refused() {
    let refuse = |q: &str| {
        parse(&lex(q).unwrap())
            .expect_err("should refuse")
            .to_string()
    };
    assert!(refuse("/a .1 /b").contains("starts with a letter"));
    assert!(refuse("/a | .1").contains("starts with a letter"));
}

#[test]
fn pushes_return_to_navigation_mode() {
    let t = MockTree::sample();
    // A computed push files the value (and shows it as the
    // topic, as ever) — but the thread is back in navigation
    // mode: the hop is legal, and it rebuilds the capsae with
    // the filed value safe in the register.
    let vs = vals("/* | .dir(:name) | /*[:name = x.rs] | %.", &t);
    assert_eq!(vs.len(), 1);
    let Value::Record(fields) = &vs[0] else {
        panic!("expected a record, got {:?}", vs[0]);
    };
    assert_eq!(fields[0], ("dir".to_string(), Value::Str("a".into())));
    // A bare push files the projected topic and reopens
    // navigation the same way.
    assert_eq!(vals("/a:name | . | $.", &t), vec![Value::Str("a".into())]);
}

// ---- capsa provenance: origins on every value ----------------

fn traced(q: &str, t: &MockTree) -> Vec<Traced> {
    eval_traced_prov(&parse(&lex(q).unwrap()).unwrap(), t)
}

fn origins(known: &[(u64, u32)]) -> Origins {
    Origins {
        known: known
            .iter()
            .map(|&(n, s)| Origin {
                position: (NodeId(n)).into(),
                command: s,
            })
            .collect(),
        more: 0,
        omitted: false,
    }
}

/// Two nodes with a provenance triple each, for the projections.
fn provenanced() -> MockTree {
    let mut t = MockTree::sample();
    let (s2, n2, o2) = crate::temporal::parse_iso("2026-04-07T02:00:01Z").unwrap();
    let (s7, n7, o7) = crate::temporal::parse_iso("2026-05-01T00:00:00Z").unwrap();
    t.prov.insert(
        2,
        Provenance {
            source: Some("api-gateway".into()),
            instant: Some((s2, n2, o2)),
            dpid: Some("request-42".into()),
            ..Default::default()
        },
    );
    t.prov.insert(
        7,
        Provenance {
            source: Some("crm".into()),
            instant: Some((s7, n7, o7)),
            dpid: Some("row-7".into()),
            ..Default::default()
        },
    );
    t
}

#[test]
fn push_records_the_read_node_and_command() {
    let t = MockTree::sample();
    // A push at command 1 reads the node it stands at; the recall
    // hands the filed value back with that origin.
    let rows = traced("/a/* | .n(:name) | $.n", &t);
    assert_eq!(rows.len(), 2);
    assert_eq!(rows[0].node, NodeId(2));
    assert_eq!(rows[0].prov.origins, origins(&[(2, 1)]));
    assert_eq!(rows[1].prov.origins, origins(&[(3, 1)]));
    // A branch-level projection is command 0.
    let rows = traced("/a/x.rs:name", &t);
    assert_eq!(rows[0].prov.origins, origins(&[(2, 0)]));
}

#[test]
fn expression_unions_its_operands_origins() {
    let t = MockTree::sample();
    // The recall carries the push's coordinate; the fresh read
    // is at the current node and command.
    let rows = traced("/a/x.rs | .n(:index) | ->ref | $.n + :index", &t);
    assert_eq!(rows.len(), 1);
    assert_eq!(rows[0].node, NodeId(7));
    assert_eq!(rows[0].prov.origins, origins(&[(2, 1), (7, 3)]));
}

#[test]
fn selection_aggregate_keeps_the_winners_origins() {
    let t = MockTree::sample();
    // `max` hands back one input: its origins are that input's
    // alone, not the union of everything reduced.
    let rows = traced("/a/*:index @| max", &t);
    assert_eq!(rows.len(), 1);
    assert_eq!(rows[0].prov.origins.known.len(), 1);
    let all = traced("/a/*:index @| count", &t);
    assert!(
        all[0].prov.origins.known.len() > 1,
        "a computed reduction keeps the union"
    );
}

#[test]
fn a_projected_count_streams_and_keeps_the_counted_nodes() {
    let t = MockTree::sample();
    // The streamed count over a projection is the node count (a
    // null value is an input too), and its origins are the nodes.
    let plain = traced("/a/* @| count", &t);
    let projected = traced("/a/*:index @| count", &t);
    assert_eq!(plain[0].topic, projected[0].topic);
    let Some(Value::Int(n)) = projected[0].topic else {
        panic!("{projected:?}")
    };
    assert_eq!(projected[0].prov.origins.known.len(), n as usize);
    let missing = traced("/a/*::no-such-property @| count", &t);
    assert_eq!(missing[0].topic, projected[0].topic);
}

#[test]
fn a_count_behind_a_descendant_lead_step_streams_and_agrees() {
    let t = MockTree::sample();
    // `//paragraph//token @| count`: a descendant lead step walks
    // its subtree for the frontier, and nested bases count a node
    // once — the same figure the materializing walk gives.
    let streamed = vals("//*//* @| count", &t);
    let walked = vals("//*//* @| unique @| count", &t);
    assert_eq!(streamed, walked);
    let streamed = vals("//a//x.rs @| count", &t);
    let walked = vals("//a//x.rs @| unique @| count", &t);
    assert_eq!(streamed, walked);
    assert_ne!(streamed, vec![Value::Int(0)]);
}

#[test]
fn fork_keeps_the_register_provenance() {
    let t = MockTree::sample();
    // The cross-capsa scenario: after a hop the capsa stands
    // elsewhere, but the regula still says where it was read.
    let rows = traced("/a/x.rs | .n(:name) | ->ref | $.n", &t);
    assert_eq!(rows[0].node, NodeId(7));
    assert_eq!(rows[0].topic, Some(Value::Str("x.rs".into())));
    assert_eq!(rows[0].prov.origins, origins(&[(2, 1)]));
}

#[test]
fn record_keeps_a_part_per_field() {
    let t = MockTree::sample();
    let rows = traced("/a/x.rs | .n(:index) | ->ref | %(a = $.n; b = :name)", &t);
    let p = &rows[0].prov;
    assert_eq!(p.origins, origins(&[(2, 1), (7, 3)]));
    assert_eq!(p.part("a").origins, origins(&[(2, 1)]));
    assert_eq!(p.part("b").origins, origins(&[(7, 3)]));
    // `.%` spreads the parts into registers; a recall gets the
    // field's own part back.
    let rows = traced(
        "/a/x.rs | .n(:index) | ->ref | %(a = $.n; b = :name) | .% | $.b",
        &t,
    );
    assert_eq!(rows[0].prov.origins, origins(&[(7, 3)]));
    let rows = traced(
        "/a/x.rs | .n(:index) | ->ref | %(a = $.n; b = :name) | .% | %.",
        &t,
    );
    assert_eq!(rows[0].prov.part("a").origins, origins(&[(2, 1)]));
    assert_eq!(rows[0].prov.part("b").origins, origins(&[(7, 3)]));
}

#[test]
fn aggregate_unions_and_bounds() {
    let t = MockTree::sample();
    let rows = traced("/a/* | :index @| count", &t);
    assert_eq!(rows.len(), 1);
    assert_eq!(rows[0].prov.origins, origins(&[(2, 1), (3, 1)]));
    // Past the cap only the count grows.
    let mut wide = MockTree::sample();
    wide.names = (0..13)
        .map(|i| if i == 0 { None } else { Some(format!("n{i}")) })
        .collect();
    wide.kids = HashMap::new();
    wide.kids.insert(0, (1..13).collect());
    wide.links = HashMap::new();
    let rows = traced("/* | :index @| sum", &wide);
    assert_eq!(rows[0].prov.origins.known.len(), ORIGIN_CAP);
    assert_eq!(rows[0].prov.origins.more, 4);
}

#[test]
fn predicate_reads_are_not_origins() {
    let t = MockTree::sample();
    // The condition's test reads w.rs, the taken branch reads
    // only the register.
    let rows = traced(
        "/a/x.rs | .n(:index) | ->ref | (:name = \"w.rs\" ? $.n : 0)",
        &t,
    );
    assert_eq!(rows[0].topic, Some(Value::Int(1)));
    assert_eq!(rows[0].prov.origins, origins(&[(2, 1)]));
}

#[test]
fn group_and_ungroup_carry_origins() {
    let t = MockTree::sample();
    // Files grouped by their directory's name: the key was read
    // at the parent (one origin, deduplicated on join); the
    // group's own provenance is its members' — the index each
    // member read at itself.
    let rows = traced("/*/* | .d(\\:name) | :index @| group(d = $.d)", &t);
    assert_eq!(rows.len(), 2);
    assert_eq!(rows[0].prov.origins, origins(&[(2, 2), (3, 2)]));
    assert_eq!(rows[1].prov.origins, origins(&[(5, 2), (6, 2)]));
    let rows = traced("/*/* | .d(\\:name) | :index @| group(d = $.d) | $.d", &t);
    assert_eq!(rows[0].prov.origins, origins(&[(1, 1)]));
    let rows = traced(
        "/*/* | .d(\\:name) | :index @| group(d = $.d) @| ungroup | $.d",
        &t,
    );
    assert_eq!(rows.len(), 4);
    assert_eq!(rows[3].prov.origins, origins(&[(4, 1)]));
}

#[test]
fn a_group_sums_a_record_field() {
    // A reducing aggregate over a group of records reads the field
    // to reduce through `--of` (draft 164: `sum(--of=:n)`), and a
    // field read on the group's list projects each member, so
    // `:n | sum` says the same. Both agree with grouping the values.
    let t = MockTree::sample();
    let by_value = traced("/*/* | .d(\\:name) | :index @| group(d = $.d) | sum", &t);
    let keyed = traced(
        "/*/* | .d(\\:name) | %(n = :index) @| group(d = $.d) | sum(--of=:n)",
        &t,
    );
    let read = traced(
        "/*/* | .d(\\:name) | %(n = :index) @| group(d = $.d) | :n | sum",
        &t,
    );
    assert_eq!(by_value.len(), 2);
    for i in 0..2 {
        assert!(by_value[i].topic.is_some());
        assert_eq!(keyed[i].topic, by_value[i].topic);
        assert_eq!(read[i].topic, by_value[i].topic);
    }
}

#[test]
fn piped_operand_reads_its_path() {
    let t = MockTree::sample();
    let rows = traced("/a/x.rs | .n(->ref @| count) | $.n", &t);
    assert_eq!(rows[0].topic, Some(Value::Int(1)));
    assert!(
        rows[0]
            .prov
            .origins
            .known
            .iter()
            .any(|o| o.position == NodeId(7).into())
    );
}

#[test]
fn value_side_provenance_projection() {
    let t = provenanced();
    // One origin: the node's own canonical text.
    assert_eq!(
        vals("/a/x.rs | .n(:index) | $.n:%provenance:text", &t),
        vec![Value::Str(
            "?api-gateway@2026-04-07T02:00:01Z#request-42".into()
        )]
    );
    assert_eq!(
        vals("/a/x.rs | .n(:index) | $.n:%provenance:source", &t),
        vec![Value::Str("api-gateway".into())]
    );
    // Two origins: the list, `;`-separated, first-read order;
    // the source and dpid of the first; the instant of the
    // newest.
    let q = "/a/x.rs | .n(:index) | ->ref | $.n + :index";
    assert_eq!(
        vals(&format!("{q} | $_:%provenance:text"), &t),
        vec![Value::Str(
            "?api-gateway@2026-04-07T02:00:01Z#request-42;crm@2026-05-01T00:00:00Z#row-7".into()
        )]
    );
    assert_eq!(
        vals(&format!("{q} | $_:%provenance:source"), &t),
        vec![Value::Str("api-gateway".into())]
    );
    assert_eq!(
        vals(&format!("{q} | $_:%provenance:dpid"), &t),
        vec![Value::Str("request-42".into())]
    );
    let (s7, n7, o7) = crate::temporal::parse_iso("2026-05-01T00:00:00Z").unwrap();
    assert_eq!(
        vals(&format!("{q} | $_:%provenance:instant"), &t),
        vec![Value::Instant {
            secs: s7,
            nanos: n7,
            offset_min: o7,
            calendar: Default::default()
        }]
    );
    // The shaped keys: the entries as records, the coordinates.
    let (s2, n2, o2) = crate::temporal::parse_iso("2026-04-07T02:00:01Z").unwrap();
    // The record: source, the node's path within it, the
    // instant and the rung it came from (the mock records
    // instants without a rung), the dpid.
    let rec = |src: &str, path: &str, inst: (i64, u32, Option<i16>), dpid: &str| {
        Value::record(vec![
            ("source".into(), Value::Str(src.into())),
            ("path".into(), Value::Str(path.into())),
            (
                "instant".into(),
                Value::Instant {
                    secs: inst.0,
                    nanos: inst.1,
                    offset_min: inst.2,
                    calendar: Default::default(),
                },
            ),
            ("instant-from".into(), Value::Null),
            ("dpid".into(), Value::Str(dpid.into())),
        ])
    };
    assert_eq!(
        vals(&format!("{q} | $_:@provenance"), &t),
        vec![Value::list(vec![
            rec("api-gateway", "/a/x.rs", (s2, n2, o2), "request-42"),
            rec("crm", "/b/deep/w.rs", (s7, n7, o7), "row-7"),
        ])]
    );
    // The record carries the singular keys, then the elided count
    // and the canonical text (spec: Record Fields).
    let Value::Record(whole) = &vals(&format!("{q} | $_:%provenance"), &t)[0] else {
        panic!("a record")
    };
    let Value::Record(core) = rec("api-gateway", "/a/x.rs", (s7, n7, o7), "request-42") else {
        panic!("a record")
    };
    assert_eq!(&whole[..5], &core[..]);
    assert_eq!(whole[5], ("elided".to_string(), Value::Int(0)));
    assert!(
        matches!(&whole[6], (k, Value::Str(t)) if k == "text" && t.starts_with("?api-gateway@"))
    );
    assert_eq!(
        vals(&format!("{q} | $_:%provenance:path"), &t),
        vec![Value::Str("/a/x.rs".into())]
    );
    // A node with no recorded provenance still has a path; the
    // access rung needs an invocation instant, which the mock
    // does not bind.
    assert_eq!(
        vals("/a/y.txt:path", &t),
        vec![Value::Str("/a/y.txt".into())]
    );
    assert_eq!(vals("/a/y.txt:instant", &t), vec![Value::Null]);
    let coord = |id: i64, command: i64| {
        Value::record(vec![
            ("id".into(), Value::Int(id)),
            ("command".into(), Value::Int(command)),
        ])
    };
    assert_eq!(
        vals(&format!("{q} | $_:%origin:id"), &t),
        vec![Value::Int(2)]
    );
    assert_eq!(vals(&format!("{q} | $_:%origin"), &t), vec![coord(2, 1)]);
    assert_eq!(
        vals(&format!("{q} | $_:@origin"), &t),
        vec![Value::list(vec![coord(2, 1), coord(7, 3)])]
    );
    // The coordinate stood on again: the node-id anchor.
    assert_eq!(
        vals(&format!("{q} | $_:%origin:id | . | ((!7)):name"), &t),
        vec![Value::Str("w.rs".into())]
    );
    assert_eq!(
        vals(&format!("{q} | $_:%provenance:elided"), &t),
        vec![Value::Int(0)]
    );
    // A record field's own part, through the field colon.
    assert_eq!(
        vals(
            "/a/x.rs | .n(:index) | ->ref | .r%(a = $.n; b = :name) | $.r:b:%provenance:source",
            &t
        ),
        vec![Value::Str("crm".into())]
    );
    // Built into a shape of the user's own.
    let vs = vals(
        "/a/x.rs | .n(:index) | %(v = $.n; from = $.n:%provenance:text)",
        &t,
    );
    let Value::Record(fields) = &vs[0] else {
        panic!("expected a record")
    };
    assert_eq!(
        fields[1],
        (
            "from".to_string(),
            Value::Str("?api-gateway@2026-04-07T02:00:01Z#request-42".into())
        )
    );
    // A node answers the shaped keys too: one entry, its own
    // coordinate, none elided.
    assert_eq!(vals("/a/x.rs:@provenance | count", &t), vec![Value::Int(1)]);
    assert_eq!(vals("/a/x.rs:origin", &t), vec![Value::Int(2)]);
    assert_eq!(vals("/a/x.rs:%origin", &t), vec![coord(2, 0)]);
    assert_eq!(vals("/a/x.rs:elided", &t), vec![Value::Int(0)]);
    // Origins without provenance answer null.
    assert_eq!(
        vals("/a/y.txt | .n(:index) | $.n:%provenance:text", &t),
        vec![Value::Null]
    );
}

#[test]
fn value_meta_needs_a_value_base() {
    assert!(parse(&lex("/a/x.rs | 1:::source").unwrap()).is_err());
    assert!(parse(&lex("/a | $.n:%provenance:text").unwrap()).is_ok());
}

// ---- attached regulae: .:name, X:.name ----------------------------

/// What a query refuses, as the error or the recorded refusal.
fn refused(q: &str, t: &MockTree) -> Option<String> {
    match crate::run(q, t) {
        Ok(_) => take_refusal(),
        Err(e) => Some(e.to_string()),
    }
}

#[test]
fn attached_read_is_by_node() {
    let t = MockTree::sample();
    // x.rs --ref--> w.rs. Every file attaches its index to its
    // node; x.rs reads what w.rs carries, w.rs reads x.rs's
    // through the reverse link; y.txt and z.rs reach no node: no
    // value, null as a scalar.
    assert_eq!(
        vals("//*<file> | .:v(:index) | ->ref:.v", &t),
        vec![Value::Int(1), Value::Null, Value::Null, Value::Null]
    );
    assert_eq!(
        vals("//*<file> | .:v(:index) | <-ref:.v", &t),
        vec![Value::Null, Value::Null, Value::Null, Value::Int(1)]
    );
    // A plain push files in the capsa only: nothing is attached,
    // the node read finds nothing.
    assert_eq!(
        vals("//*<file> | .v(:index) | ->ref:.v", &t),
        vec![Value::Null, Value::Null, Value::Null, Value::Null]
    );
    // The attaching push files in the capsa too, exactly as the
    // plain one does.
    assert_eq!(
        vals("//*<file> | .:v(:index) | $.v", &t),
        vec![Value::Int(1), Value::Int(2), Value::Int(1), Value::Int(1)]
    );
    // Bare, it attaches the topic.
    assert_eq!(
        vals("/a/x.rs | :index | .:v | :.v", &t),
        vec![Value::Int(1)]
    );
    // The record of everything attached, in first-attach order;
    // empty where nothing is.
    assert_eq!(
        vals("/a/x.rs | .:v(1) | .:w(\"k\") | :%.", &t),
        vec![Value::record(vec![
            ("v".to_string(), Value::Int(1)),
            ("w".to_string(), Value::Str("k".into())),
        ])]
    );
    assert_eq!(
        vals("/a/x.rs | .:v(1) | ->ref:%.", &t),
        vec![Value::record(Vec::new())]
    );
}

#[test]
fn attached_read_survives_filters_and_walks() {
    let t = MockTree::sample();
    // Identity, not location: w.rs's thread is filtered away, its
    // attachment stays readable — through the link, and standing
    // on the node after a hop.
    assert_eq!(
        vals(
            "//*<file> | .:v(:index * 10) | [:name = \"x.rs\"] | ->ref:.v",
            &t
        ),
        vec![Value::Int(10)]
    );
    assert_eq!(
        vals(
            "//*<file> | .:v(:index * 10) | [:name = \"x.rs\"] | ->ref | :.v",
            &t
        ),
        vec![Value::Int(10)]
    );
    assert_eq!(
        vals(
            "//*<file> | .:v(:index * 10) | [:name = \"x.rs\"] | ->ref | %(n = :name; v = :.v)",
            &t
        ),
        vec![Value::record(vec![
            ("n".to_string(), Value::Str("w.rs".into())),
            ("v".to_string(), Value::Int(10)),
        ])]
    );
    // In a predicate: the current node's, and a marked node's.
    assert_eq!(run("//*<file> | .:v(:index) | ->ref[:.v = 1]", &t), vec![7]);
    assert_eq!(
        run(
            "//*<file> | .:v(:index) | [:name = \"x.rs\"] | .M | ->ref[:.v = $$.M:.v]",
            &t
        ),
        vec![7]
    );
    assert_eq!(
        run(
            "//*<file> | .:v(:index * :index) | [:name = \"x.rs\"] | .M | ->ref[:.v > $$.M:.v]",
            &t
        ),
        Vec::<u64>::new()
    );
    // After `@| collapse` the one thread at the node reads it.
    assert_eq!(
        vals("/a/* | .:v(:index) | \\ @| collapse | /x.rs | :.v", &t),
        vec![Value::Int(1)]
    );
    // `@| nodes` carries the attachments as columns.
    let table = vals("/a/* | .:v(:index) | .:w(\"k\") @| nodes", &t);
    let Value::Table(table) = &table[0] else {
        panic!("expected a table, got {table:?}");
    };
    assert_eq!(
        table.header.as_ref().unwrap(),
        &["node", "name", "kind", "v", "w"]
    );
    assert_eq!(table.rows[0][3], Value::Int(1));
    assert_eq!(table.rows[1][3], Value::Int(2));
    assert_eq!(table.rows[1][4], Value::Str("k".into()));
}

#[test]
fn attached_read_sees_the_input_snapshot() {
    let t = MockTree::sample();
    // A round that both reads a neighbour's value and attaches the
    // same name: every thread reads what the command received,
    // whatever the evaluation order — x.rs and w.rs swap through
    // the link in one command.
    let pair = "//*<file>[:name = \"x.rs\" || :name = \"w.rs\"]";
    let vs = vals(
        &format!(
            "{pair} | .:v((:name = \"x.rs\" ? 5 : 9)) | .:v((:name = \"x.rs\" ? ->ref:.v : <-ref:.v)) | $.v"
        ),
        &t,
    );
    assert_eq!(vs, vec![Value::Int(9), Value::Int(5)]);
    // Two commands: x.rs attaches a from w.rs's v, w.rs then reads
    // x.rs's a as b. Without the colon, a is filed but not
    // attached, and the read finds nothing.
    assert_eq!(
        vals(
            &format!(
                "{pair} | .:v((:name = \"x.rs\" ? 5 : 9)) | .:a(->ref:.v) | .b(<-ref:.a) | $.b"
            ),
            &t
        ),
        vec![Value::Null, Value::Int(9)]
    );
    assert_eq!(
        vals(
            &format!(
                "{pair} | .:v((:name = \"x.rs\" ? 5 : 9)) | .a(->ref:.v) | .b(<-ref:.a) | $.b"
            ),
            &t
        ),
        vec![Value::Null, Value::Null]
    );
    // Across commands the push replaces: the node carries the
    // latest value under the name, the capsa every regula.
    assert_eq!(
        vals("/a/x.rs | .:v(1) | .:v(2) | :.v", &t),
        vec![Value::Int(2)]
    );
    assert_eq!(
        vals("/a/x.rs | .:v(1) | .:v(2) | @. | count", &t),
        vec![Value::Int(2)]
    );
}

#[test]
fn attaching_threads_at_one_node_must_agree() {
    let t = MockTree::sample();
    // Two threads converge on `a` by the parent axis. Equal values
    // pass; differing ones refuse, naming collapse; collapsed, the
    // one thread attaches.
    assert_eq!(
        vals("/a/* | .v(:index) | \\ | .:w(2) | :.w", &t),
        vec![Value::Int(2), Value::Int(2)]
    );
    let why = refused("/a/* | .v(:index) | \\ | .:w($.v) | :.w", &t).unwrap();
    assert!(why.contains("differing values under 'w'"), "{why}");
    assert!(why.contains("@| collapse"), "{why}");
    assert_eq!(
        vals(
            "/a/* | .v(:index) | \\ @| collapse | .:w(($.v | count)) | :.w",
            &t
        ),
        vec![Value::Int(2)]
    );
    // A thread standing nowhere has no node to attach to.
    let why = refused("/a/* | :index @| sum | .:w(1)", &t).unwrap();
    assert!(why.contains("stands nowhere"), "{why}");
}

#[test]
fn attached_regula_carries_its_provenance() {
    let t = MockTree::sample();
    // The value read from w.rs's node keeps where w.rs read it
    // (node 7, command 1); the node it is read at is not an
    // origin, nor is the navigation.
    let pair = "//*<file>[:name = \"x.rs\" || :name = \"w.rs\"]";
    let rows = traced(&format!("{pair} | .:v(:index) | ->ref:.v"), &t);
    assert_eq!(rows[0].node, NodeId(2));
    assert_eq!(rows[0].prov.origins, origins(&[(7, 1)]));
    let t2 = provenanced();
    assert_eq!(
        vals(
            &format!("{pair} | .:v(:index) | ->ref:.v:%provenance:source"),
            &t2
        )[0],
        Value::Str("crm".into())
    );
}

#[test]
fn attached_read_is_null_without_attachments() {
    let t = MockTree::sample();
    // Nothing attached: null, so the comparison fails.
    assert_eq!(run("/a/x.rs[->ref:.v = 1]", &t), Vec::<u64>::new());
    assert_eq!(run("/a/x.rs[!->ref:.v]", &t), vec![2]);
    assert_eq!(run("/a/x.rs[!:.v]", &t), vec![2]);
}

#[test]
fn attached_read_needs_a_node_side_or_none() {
    // A projected path is a value, not a node; so is a recall.
    assert!(parse(&lex("/a | $.v:.r").unwrap()).is_err());
    assert!(parse(&lex("/a | ->ref::x:.r").unwrap()).is_err());
    // Alone, the current node.
    assert!(parse(&lex("/a | :.r").unwrap()).is_ok());
    assert!(parse(&lex("/a | :%.").unwrap()).is_ok());
    assert!(parse(&lex("/a[:.r = 1]").unwrap()).is_ok());
    // A spaced colon is still the conditional's else.
    assert!(parse(&lex("/a | (::x ? 1 : .5)").unwrap()).is_ok());
    // The location read's accessors are retired.
    for q in [
        "/a | ->ref:.",
        "/a | ->ref:.1",
        "/a | ->ref:..",
        "/a | ->ref:@.",
        "/a | ->ref:@@.",
        "/a | ->ref:%%.",
        "/a | ->ref:%.*",
        "/a | ->ref:(*.)",
    ] {
        let err = parse(&lex(q).unwrap()).unwrap_err().to_string();
        assert!(err.contains("retired"), "{q}: {err}");
    }
    // The attaching push takes a name, and a body or the topic.
    assert!(parse(&lex("/a | .:(1)").unwrap()).is_err());
    assert!(lex("/a | .:v%(a = 1)").and_then(|t| parse(&t)).is_err());
    assert!(parse(&lex("/a | .:v(1){3}").unwrap()).is_ok());
    assert!(parse(&lex("/a | .:v").unwrap()).is_ok());
}

#[test]
fn edge_ends_are_node_operands() {
    let t = MockTree::sample();
    // `$-:source` / `$-:target` — the arrived-by edge's ends as node
    // references in the declaration's orientation, node operands
    // in their own right: a core field, a property, an attached
    // regula.
    assert_eq!(
        vals(
            "/a/x.rs | ->ref | %(s = $-:source:name; t = $-:target:name)",
            &t
        ),
        vec![Value::record(vec![
            ("s".to_string(), Value::Str("x.rs".into())),
            ("t".to_string(), Value::Str("w.rs".into())),
        ])]
    );
    assert_eq!(
        vals(
            "//*<file> | .:l(:name) | [:name = \"x.rs\"] | ->ref | %(s = $-:source:.l; t = $-:target:.l)",
            &t
        ),
        vec![Value::record(vec![
            ("s".to_string(), Value::Str("x.rs".into())),
            ("t".to_string(), Value::Str("w.rs".into())),
        ])]
    );
    // The undirected hop reads the ends as stored: from w.rs the
    // edge's source is still x.rs.
    assert_eq!(
        vals("//*<file>[:name = \"w.rs\"] | --ref | $-:source:name", &t),
        vec![Value::Str("x.rs".into())]
    );
    // The edges table's `source` and `target` cells are the same
    // references: a row filter reads both ends' attachments through
    // the columns.
    let pair = "//*<file>[:name = \"x.rs\" || :name = \"w.rs\"]";
    assert_eq!(
        vals(
            &format!("{pair} | .:l(:name) @| edges(->ref) | :target:.l"),
            &t
        ),
        vec![Value::Str("w.rs".into())]
    );
    assert_eq!(
        vals(
            &format!("{pair} | .:l(:name) @| edges(->ref) | [:source:.l = :target:.l] | dim"),
            &t
        ),
        vec![Value::list(vec![Value::Int(0), Value::Int(4)])]
    );
    assert_eq!(
        vals(
            &format!("{pair} | .:l(\"same\") @| edges(->ref) | [:source:.l = :target:.l] | dim"),
            &t
        ),
        vec![Value::list(vec![Value::Int(1), Value::Int(4)])]
    );
    // A node operand of any other kind than a reference names no
    // node; a plain value cannot carry a read.
    assert!(parse(&lex("/a | $-::x:.r").unwrap()).is_err());
    assert!(parse(&lex("/a | $-:round:.r").unwrap()).is_err());
    assert_eq!(
        vals("/a/x.rs | ->ref | %(n = :name) | :n:.l", &t),
        vec![Value::Null]
    );
}

// ---- the graph library: graph:pagerank, graph:distance, graph:kcore ----

#[test]
fn graph_pagerank_is_row_aligned_over_the_induced_subgraph() {
    let t = MockTree::roads();
    // one float per thread, the threads kept in place on their
    // nodes; the walk reaches x.rs and deep twice, and a thread
    // that reached a node twice reads the same number twice
    let six = vals("//a(->e)* @| graph:pagerank(->e)", &t);
    assert_eq!(six.len(), 6);
    assert_eq!(six[1], six[5]);
    assert_eq!(six[3], six[4]);
    // collapsed to the four nodes: one value each
    let ranks = vals("//a(->e)* @| collapse @| graph:pagerank(->e)", &t);
    assert_eq!(
        ranks,
        vec![
            six[0].clone(),
            six[1].clone(),
            six[2].clone(),
            six[3].clone()
        ]
    );
    let sum: f64 = ranks
        .iter()
        .map(|v| match v {
            Value::Float(f) => *f,
            other => panic!("{other:?}"),
        })
        .sum();
    assert!((sum - 1.0).abs() < 1e-12, "{sum}");
    assert_eq!(
        vals(
            "//a(->e)* @| collapse @| graph:pagerank(->e) | %(n = :name; r = $_) | :n",
            &t
        ),
        vec![
            Value::Str("a".into()),
            Value::Str("x.rs".into()),
            Value::Str("y.txt".into()),
            Value::Str("deep".into())
        ]
    );
    // `->*` when the hop is left out: the same here
    assert_eq!(vals("//a(->e)* @| collapse @| graph:pagerank", &t), ranks);
    // the induced rule: deep alone is a graph of one, rank one
    assert_eq!(
        vals("/b/deep @| graph:pagerank(->e)", &t),
        vec![Value::Float(1.0)]
    );
    // threads are folded to their positions: two threads at `a`
    // make a graph of one node, each reading its value
    assert_eq!(
        vals("/a/* | .v(:index) | \\ @| graph:pagerank(->e)", &t),
        vec![Value::Float(1.0), Value::Float(1.0)]
    );
    // weights: by unit or by property, the same shares; weighted
    // differs from unweighted
    let by_unit = vals(
        "//a(->e)* @| collapse @| graph:pagerank(->e; --weight=km)",
        &t,
    );
    let by_prop = vals(
        "//a(->e)* @| collapse @| graph:pagerank(->e; --weight=::len)",
        &t,
    );
    for (a, b) in by_unit.iter().zip(&by_prop) {
        let (Value::Float(a), Value::Float(b)) = (a, b) else {
            panic!("{a:?} {b:?}");
        };
        assert!((a - b).abs() < 1e-12);
    }
    assert_ne!(by_unit, ranks);
    // the rank reaches the node by the push after it
    assert_eq!(
        vals(
            "//a(->e)* @| collapse @| graph:pagerank(->e) | .:pr | [:name = \"deep\"] | :.pr",
            &t
        ),
        vec![ranks[3].clone()]
    );
    // what refuses: a value context, the plain pipe, an alternation
    // of hops, the reserved option, a value context
    // a value-mode thread still stands on its node: the positions
    // are ranked whatever the topic; only a thread standing nowhere
    // refuses
    assert_eq!(
        vals("//a(->e)* @| collapse | :index @| graph:pagerank(->e)", &t),
        ranks
    );
    let why = refused("//a(->e)* | :index @| sum @| graph:pagerank(->e)", &t).unwrap();
    assert!(why.contains("stands nowhere"), "{why}");
    let table = vals("/a/* | %(n = :name) | .:% @| nodes", &t);
    let Value::Table(table) = &table[0] else {
        panic!("{table:?}");
    };
    assert_eq!(table.rows.len(), 2);
    assert_eq!(table.header.as_ref().unwrap().last().unwrap(), "n");
    let why = refused("//a(->e)* | graph:pagerank(->e)", &t).unwrap();
    assert!(why.contains("aggregation pipe"), "{why}");
    let why = refused("//a(->e)* @| graph:pagerank((->e|->f))", &t).unwrap();
    assert!(why.contains("one hop"), "{why}");
    let why = refused("//a(->e)* @| graph:pagerank(->e; --teleport=/a)", &t).unwrap();
    assert!(why.contains("reserved"), "{why}");
}

#[test]
fn graph_distance_counts_hops_or_sums_weights_from_the_seeds() {
    let t = MockTree::roads();
    // a -> x.rs, a -> y.txt, x.rs -> deep, y.txt -> deep, deep -> x.rs
    assert_eq!(
        vals(
            "//a(->e)* @| collapse @| graph:distance(->e; --from=/a)",
            &t
        ),
        vec![Value::Int(0), Value::Int(1), Value::Int(1), Value::Int(2)]
    );
    // a seed by mark; a seed outside the context counts for nothing
    assert_eq!(
        vals(
            "/a .S (->e)* @| collapse @| graph:distance(->e; --from=$$.S)",
            &t
        ),
        vec![Value::Int(0), Value::Int(1), Value::Int(1), Value::Int(2)]
    );
    assert_eq!(
        vals("/a/* @| graph:distance(->e; --from=/a)", &t),
        vec![Value::Null, Value::Null]
    );
    // unreached nodes are null; the nearest of several seeds
    assert_eq!(
        vals(
            "//a(->e)* @| collapse @| graph:distance(->e; --from=/a/x.rs)",
            &t
        ),
        vec![Value::Null, Value::Int(0), Value::Null, Value::Int(1)]
    );
    assert_eq!(
        vals(
            "//a(->e)* @| collapse @| graph:distance(->e; --from=/a/*)",
            &t
        ),
        vec![Value::Null, Value::Int(0), Value::Int(0), Value::Int(1)]
    );
    // weights by unit: quantities in that unit, the shortest way
    // (a -1km-> y.txt -2km-> deep beats a -4km-> x.rs -12km-> deep)
    let km = vals(
        "//a(->e)* @| graph:distance(->e; --from=/a --weight=km)",
        &t,
    );
    assert_eq!(
        km[0],
        Value::Quantity {
            value: 0.0,
            base: "m".into(),
            written: Some((0.0, "km".into()))
        }
    );
    assert!(
        matches!(&km[3], Value::Quantity { value, .. } if (*value - 3000.0).abs() < 1e-9),
        "{km:?}"
    );
    // weights by property: integers stay integers
    let w = MockTree::weighted();
    assert_eq!(
        vals(
            "//a(->e)* @| graph:distance(->e; --from=/a --weight=::qty)",
            &w
        ),
        vec![Value::Int(0), Value::Int(4), Value::Int(1), Value::Int(16)]
    );
    // the seeds are required
    let why = refused("//a(->e)* @| graph:distance(->e)", &t).unwrap();
    assert!(why.contains("--from"), "{why}");
}

#[test]
fn graph_kcore_peels_undirected_distinct_neighbours() {
    let t = MockTree::roads();
    // the 4-cycle a - x.rs - deep - y.txt - a: every node in core 2,
    // whichever way the hop reads the edges
    assert_eq!(
        vals("//a(->e)* @| collapse @| graph:kcore(->e)", &t),
        vec![Value::Int(2); 4]
    );
    assert_eq!(
        vals("//a(->e)* @| graph:kcore(--e)", &t),
        vals("//a(->e)* @| graph:kcore(->e)", &t)
    );
    // one edge: its ends in core 1, the rest in core 0
    let s = MockTree::sample();
    assert_eq!(
        vals("//*<file> @| graph:kcore(->ref)", &s),
        vec![Value::Int(1), Value::Int(0), Value::Int(0), Value::Int(1)]
    );
    let why = refused("//a(->e)* @| graph:kcore(->e; --weight=km)", &t).unwrap();
    assert!(why.contains("weight"), "{why}");
}

#[test]
fn graph_betweenness_and_conncomp() {
    let t = MockTree::roads();
    let floats = |q: &str| -> Vec<f64> {
        vals(q, &t)
            .iter()
            .map(|v| match v {
                Value::Float(f) => *f,
                other => panic!("{other:?}"),
            })
            .collect()
    };
    // a -> x.rs, a -> y.txt, x.rs -> deep, y.txt -> deep, deep -> x.rs:
    // a is on no path between others; the pair (a, deep) splits its
    // unit between x.rs and y.txt; deep carries y.txt's way to x.rs
    let cb = floats("//a(->e)* @| collapse @| graph:betweenness(->e)");
    assert_eq!(cb, [0.0, 0.5, 0.5, 1.0]);
    // undirected: the 4-cycle a - x.rs - deep - y.txt - a, every node
    // carrying half of the one pair across from it (that pair has
    // two shortest ways round), 1/6 of the 3 pairs when normalized
    let und = floats("//a(->e)* @| collapse @| graph:betweenness(--e; --normalized)");
    assert!(und.iter().all(|&c| (c - 1.0 / 6.0).abs() < 1e-9), "{und:?}");
    // weighted: a -1km-> y.txt -2km-> deep beats a -4km-> x.rs -12km->
    // deep, so y.txt carries (a, deep) alone
    let w = floats("//a(->e)* @| collapse @| graph:betweenness(->e; --weight=km)");
    assert!(w[2] > w[1], "{w:?}");
    // components: directed, x.rs <-> deep are strongly connected, a
    // and y.txt alone; undirected, one component
    assert_eq!(
        vals("//a(->e)* @| collapse @| graph:conncomp(->e)", &t),
        vec![Value::Int(1), Value::Int(2), Value::Int(3), Value::Int(2)]
    );
    assert_eq!(
        vals("//a(->e)* @| collapse @| graph:conncomp(--e)", &t),
        vec![Value::Int(1); 4]
    );
    // the sample tree: one ref edge, two islands
    let s = MockTree::sample();
    assert_eq!(
        vals("//*<file> @| graph:conncomp(--ref)", &s),
        vec![Value::Int(1), Value::Int(2), Value::Int(3), Value::Int(1)]
    );
    let why = refused("//a(->e)* @| graph:conncomp(->e; --weight=km)", &t).unwrap();
    assert!(why.contains("weight"), "{why}");
}

#[test]
fn a_mark_re_seat_keeps_every_thread() {
    let t = MockTree::roads();
    // a .A --e .H --e: five walks (x.rs has two edges to deep),
    // three through x.rs and two through y.txt, their registers
    // alike within a group; re-seating on H keeps the five (a hop
    // would fold the alike), collapse folds them to the two H
    assert_eq!(
        vals("/a .A --e .H --e | $$.H @| count", &t),
        vec![Value::Int(5)]
    );
    assert_eq!(
        vals("/a .A --e .H --e | $$.H:name @| frequencies | :n", &t),
        vec![Value::Int(3), Value::Int(2)]
    );
    assert_eq!(
        vals("/a .A --e .H --e | $$.H @| collapse @| count", &t),
        vec![Value::Int(2)]
    );
    // a hop still folds the alike: x.rs and y.txt both to `a`
    assert_eq!(vals("/a/* | \\ @| count", &t), vec![Value::Int(1)]);
}

#[test]
fn copy_stands_last_and_is_the_tools() {
    let t = MockTree::sample();
    // the spelling: last, bare, on the plain pipe
    assert!(parse(&lex("/a/* | json | copy").unwrap()).is_ok());
    assert!(parse(&lex("/a/* @| json | copy").unwrap()).is_ok());
    let err = parse(&lex("/a/* | copy | first").unwrap())
        .unwrap_err()
        .to_string();
    assert!(err.contains("stands last"), "{err}");
    let err = parse(&lex("/a/* | copy(json)").unwrap())
        .unwrap_err()
        .to_string();
    assert!(err.contains("no operand"), "{err}");
    // the engine itself does not copy: reaching the executor refuses
    let why = refused("/a/* | copy", &t).unwrap();
    assert!(why.contains("the tool's"), "{why}");
    // the host takes it off the end, with the rendering's name
    assert_eq!(
        crate::take_copy("//page @| json | copy"),
        Some(("//page @| json".to_string(), "JSON"))
    );
    assert_eq!(
        crate::take_copy("/a/* | %(n = :name) | copy  "),
        Some(("/a/* | %(n = :name)".to_string(), "text"))
    );
    assert_eq!(
        crate::take_copy("/a/* @| csv(a; b) | copy"),
        Some(("/a/* @| csv(a; b)".to_string(), "CSV"))
    );
    assert_eq!(crate::take_copy("/a/* | copy | first"), None);
    // either pipe, one meaning
    assert_eq!(
        crate::take_copy("/a/* @| json @| copy"),
        Some(("/a/* @| json".to_string(), "JSON"))
    );
    assert!(parse(&lex("/a/* @| copy").unwrap()).is_ok());
    let err = parse(&lex("/a/* @| copy | first").unwrap())
        .unwrap_err()
        .to_string();
    assert!(err.contains("stands last"), "{err}");
    let why = refused("/a/* @| copy", &t).unwrap();
    assert!(why.contains("the tool's"), "{why}");
}

#[test]
fn the_attaching_fields_push_attaches_every_field() {
    let t = MockTree::sample();
    assert_eq!(
        vals("/a/x.rs | %(k = 1; v = \"a\") | .:% | :%.", &t),
        vec![Value::record(vec![
            ("k".to_string(), Value::Int(1)),
            ("v".to_string(), Value::Str("a".into())),
        ])]
    );
    assert_eq!(
        vals("/a/x.rs | %(k = 1; v = \"a\") | .:% | $.k", &t),
        vec![Value::Int(1)]
    );
    // read from elsewhere, by the node
    assert_eq!(
        vals(
            "//*<file> | %(n = :name) | .:% | [:n = \"x.rs\"] | ->ref:.n",
            &t
        ),
        vec![Value::Str("w.rs".into())]
    );
    assert!(parse(&lex("/a | .:%{2}").unwrap()).is_ok());
    assert!(parse(&lex("/a | .:%(a = 1)").unwrap()).is_err());
}

#[test]
fn quantified_attaching_push_floods_to_a_fixpoint() {
    // The 2×2 lattice: c1 -r-> c2, c1 -d-> c3, c2 -d-> c4, c3 -r->
    // c4. Every cell takes the least label among its own and its
    // neighbours', round after round, until nothing moves: c4
    // reaches 1 in the second round, the third changes nothing.
    let t = MockTree::lattice(2);
    assert_eq!(
        vals(
            "/* | .:l(:index) | .:l((@(:.l; (--*:.l)) | min)){1;} | $.l",
            &t
        ),
        vec![Value::Int(1); 4]
    );
    assert_eq!(
        vals(
            "/* | .:l(:index) | .:l((@(:.l; (--*:.l)) | min)){1;} | @. | count",
            &t
        ),
        vec![Value::Int(4); 4]
    );
    // Seeded: the labelled cells keep theirs, the rest take the
    // least neighbouring label.
    assert_eq!(
        vals(
            "/* | .:l((:index = 1 ? 1 : (:index = 4 ? 4 : null))) | .:l($.l ?? (--*:.l @| min)){1;} | $.l",
            &t
        ),
        vec![Value::Int(1), Value::Int(1), Value::Int(1), Value::Int(4)]
    );
}

#[test]
fn node_id_anchor() {
    let t = MockTree::sample();
    // `((!N))` stands on the node with that id, at the branch
    // level and in operand position; an id the adapter never
    // minted (the mock indexes by id and would panic) is no
    // node.
    assert_eq!(run("((!7))", &t), vec![7]);
    assert_eq!(vals("((!7)):name", &t), vec![Value::Str("w.rs".into())]);
    assert_eq!(
        vals("/a | ((!7))\\:name", &t),
        vec![Value::Str("deep".into())]
    );
    assert_eq!(run("((!99))", &t), Vec::<u64>::new());
    assert_eq!(vals("/a | ((!99)):name", &t), Vec::<Value>::new());
    // Round trip through the id key: what `:id` and
    // `:origin` report, the anchor accepts.
    assert_eq!(vals("/b/deep/w.rs:id", &t), vec![Value::Int(7)]);
    assert_eq!(
        vals("/a/x.rs | .v(:index) | ->ref | $.v:%origin:id", &t),
        vec![Value::Int(2)]
    );
    // The anchor takes an expression: a value's origin stood on
    // again, a coordinate record by its id, an arithmetic id, a
    // list of ids forking one thread each.
    assert_eq!(
        vals(
            "/a/x.rs | .v(:index) | ->ref | .o($.v:%origin:id) | ((!$.o)):name",
            &t
        ),
        vec![Value::Str("x.rs".into())]
    );
    assert_eq!(
        vals("/a/x.rs | .v(:index) | ->ref | ((!$.v:%origin)):name", &t),
        vec![Value::Str("x.rs".into())]
    );
    assert_eq!(
        vals("/a/* | .v(:index) | ((!$.v + 1)):name", &t),
        vec![Value::Str("x.rs".into()), Value::Str("y.txt".into())]
    );
    assert_eq!(
        vals("/a | ((!@(2; 3; 99))):name", &t),
        vec![Value::Str("x.rs".into()), Value::Str("y.txt".into())]
    );
    // The anchor's reads are not origins.
    let rows = traced(
        "/a/x.rs | .v(:index) | ->ref | ((!$.v:%origin:id)) | :name",
        &t,
    );
    assert_eq!(rows[0].node, NodeId(2));
    assert_eq!(rows[0].prov.origins, origins(&[(2, 4)]));
}

#[test]
fn quantified_push_iterates() {
    let t = MockTree::sample();
    // `{N}` files N regulae, each round reading the last.
    assert_eq!(
        vals("/a | .v(1) | .v($.v * 2){3} | $.v", &t),
        vec![Value::Int(8)]
    );
    assert_eq!(
        vals("/a | .v(1) | .v($.v * 2){3} | @. | count", &t),
        vec![Value::Int(4)]
    );
    // A round is synchronous: peers read the previous round's
    // values through the snapshot, whatever the order.
    let pair = "//*<file>[:name = \"x.rs\" || :name = \"w.rs\"]";
    assert_eq!(
        vals(
            &format!(
                "{pair} | .:v(:index * 10) | .:v(($.v + (->ref:.v | default(0)) + (<-ref:.v | default(0)))){{2}} | $.v"
            ),
            &t
        ),
        vec![Value::Int(40), Value::Int(40)]
    );
    // The open forms stop at a fixpoint: a round that repoints
    // no name — after `min` rounds, within the bound.
    assert_eq!(
        vals(
            "/a | .v(5) | .v(($.v > 8 ? $.v : $.v + 1)){1;} | @. | count",
            &t
        ),
        vec![Value::Int(6)]
    );
    assert_eq!(
        vals("/a | .v(5) | .v($.v){3;} | @. | count", &t),
        vec![Value::Int(5)]
    );
    assert_eq!(
        vals("/a | .v(5) | .v($.v + 1){2;3} | $.v", &t),
        vec![Value::Int(8)]
    );
    // Only a push takes the quantifier.
    assert!(parse(&lex("/a | upper{3}").unwrap()).is_err());
    assert!(parse(&lex("/a | .v(1){3;2}").unwrap()).is_err());
}

// ── the graph library's next commands (spec draft.189) ──────────────

fn table_of(q: &str, t: &MockTree) -> (Vec<String>, Vec<Vec<String>>) {
    let vs = vals(q, t);
    assert_eq!(vs.len(), 1, "{q}");
    let Value::Table(tb) = &vs[0] else {
        panic!("{q}: not a table: {}", vs[0].display_form())
    };
    (
        tb.header.clone().unwrap(),
        tb.rows
            .iter()
            .map(|r| r.iter().map(Value::display_form).collect())
            .collect(),
    )
}

fn list_strs(v: &Value) -> Vec<String> {
    match v {
        Value::List(items) => items.iter().map(|i| i.to_string()).collect(),
        other => panic!("a list, not {other}"),
    }
}

#[test]
fn artpoints_and_bridges_read_the_hop_undirected() {
    let t = MockTree::roads();
    // the whole roads graph is a cycle a-x-deep-y-a: nothing cuts
    let cut = vals("//a(->e)* @| collapse @| graph:artpoints(->e)", &t);
    assert_eq!(cut, vec![Value::Bool(false); 4]);
    assert_eq!(table_of("//a(->e)* @| graph:bridges(->e)", &t).1.len(), 0);
    // without deep it is a path x-a-y: a cuts, both edges are bridges
    let cut = vals(
        "//a(->e)*[:name != \"deep\"] @| collapse @| graph:artpoints(->e)",
        &t,
    );
    assert_eq!(
        cut,
        vec![Value::Bool(true), Value::Bool(false), Value::Bool(false)]
    );
    let (h, rows) = table_of("//a(->e)*[:name != \"deep\"] @| graph:bridges(->e)", &t);
    assert_eq!(h, ["source", "target", "label", "directed", "len", "time"]);
    assert_eq!(rows.len(), 2);
    assert_eq!(rows[0][..2], ["/a", "/a/x.rs"]);
    assert_eq!(rows[1][..2], ["/a", "/a/y.txt"]);
    // the direction of the hop is no matter, and a weight refuses
    assert_eq!(
        table_of("//a(->e)*[:name != \"deep\"] @| graph:bridges(<-e)", &t)
            .1
            .len(),
        2
    );
    assert!(vals("//a(->e)* @| graph:artpoints(->e; --weight=km)", &t).is_empty());
}

#[test]
fn routes_are_lists_of_nodes_seed_first() {
    let t = MockTree::roads();
    // by hops: deep is reached through x.rs or y.txt alike, and the
    // predecessor that stands first in document order wins
    let routes = vals("//a(->e)* @| collapse @| graph:route(->e; --from=/a)", &t);
    assert_eq!(list_strs(&routes[0]), ["/a"]);
    assert_eq!(list_strs(&routes[1]), ["/a", "/a/x.rs"]);
    assert_eq!(list_strs(&routes[2]), ["/a", "/a/y.txt"]);
    assert_eq!(list_strs(&routes[3]), ["/a", "/a/x.rs", "/b/deep"]);
    // by weight the light road through y.txt is shortest
    let routes = vals(
        "//a(->e)* @| collapse @| graph:route(->e; --from=/a --weight=km)",
        &t,
    );
    assert_eq!(list_strs(&routes[3]), ["/a", "/a/y.txt", "/b/deep"]);
    // unreached from deep: a and y.txt (deep's one edge leads to x.rs)
    let routes = vals(
        "//a(->e)* @| collapse @| graph:route(->e; --from=/b/deep)",
        &t,
    );
    assert_eq!(routes[0], Value::Null);
    assert_eq!(list_strs(&routes[1]), ["/b/deep", "/a/x.rs"]);
    assert_eq!(list_strs(&routes[3]), ["/b/deep"]);
    // every thread keeps its place and reads its node's route
    assert_eq!(
        vals("//a(->e)* @| graph:route(->e; --from=/a)", &t).len(),
        6
    );
    // no seeds refuses
    assert!(vals("//a(->e)* @| graph:route(->e)", &t).is_empty());
}

#[test]
fn edge_betweenness_is_the_edges_table_with_a_column() {
    let t = MockTree::roads();
    let (h, rows) = table_of("//a(->e)* @| graph:betweenness(->e; --edges)", &t);
    assert_eq!(
        h,
        [
            "source",
            "target",
            "label",
            "directed",
            "len",
            "time",
            "betweenness"
        ]
    );
    let got: Vec<f64> = rows.iter().map(|r| r[6].parse().unwrap()).collect();
    // a->x 1.5, a->y 1.5, x->deep 1.5, y->deep 2.5, deep->x 2
    assert_eq!(got, [1.5, 1.5, 1.5, 2.5, 2.0]);
    // normalized by the ordered pairs of distinct nodes, 12
    let (_, rows) = table_of(
        "//a(->e)* @| graph:betweenness(->e; --edges --normalized)",
        &t,
    );
    let got: Vec<f64> = rows.iter().map(|r| r[6].parse().unwrap()).collect();
    assert!((got[3] - 2.5 / 12.0).abs() < 1e-12, "{got:?}");
}

#[test]
fn a_library_command_is_refused_under_the_graph_bound_before_computing() {
    let t = MockTree::roads();
    let tight = crate::Run {
        graph_bound: Some(3),
        ..Default::default()
    };
    let run = |q: &str| {
        crate::Query::parse(q, &t)
            .unwrap()
            .run(&t, &tight)
            .map(|o| o.result)
    };
    // four nodes and five edges cost nine; kcore is refused, a walk
    // of the same context is not
    let err = run("//a(->e)* @| graph:kcore(->e)").err().expect("refused");
    let text = format!("{err}");
    assert!(
        text.contains("graph bound") && text.contains("4 nodes and 5 edges"),
        "{text}"
    );
    assert!(run("//a(->e)* @| count").is_ok());
    // betweenness costs nodes times edges
    let err = format!(
        "{}",
        run("//a(->e)* @| graph:betweenness(->e)").err().unwrap()
    );
    assert!(err.contains("20 cost units (nodes times edges)"), "{err}");
}

/// A mock that declares a graph and keeps what the engine computes.
struct Declaring {
    inner: MockTree,
    kept: std::cell::RefCell<HashMap<(String, String, String), Vec<Value>>>,
    asked: std::cell::Cell<usize>,
}

impl AstAdapter for Declaring {
    fn root(&self) -> NodeId {
        self.inner.root()
    }
    fn children(&self, n: NodeId) -> Vec<NodeId> {
        self.inner.children(n)
    }
    fn name(&self, n: NodeId) -> Option<String> {
        self.inner.name(n)
    }
    fn parent(&self, n: NodeId) -> Option<NodeId> {
        self.inner.parent(n)
    }
    fn non_tree_nodes(&self) -> Vec<NodeId> {
        self.inner.non_tree_nodes()
    }
    fn links(&self, n: NodeId) -> Vec<(String, NodeId)> {
        self.inner.links(n)
    }
    fn traits(&self, n: NodeId) -> Vec<String> {
        self.inner.traits(n)
    }
    fn backlinks(&self, n: NodeId) -> Vec<(String, NodeId)> {
        self.inner.backlinks(n)
    }
    fn link_property_names(&self, s: NodeId, l: &str, t: NodeId) -> Vec<String> {
        self.inner.link_property_names(s, l, t)
    }
    fn link_property(&self, s: NodeId, l: &str, t: NodeId, p: &str) -> Option<Value> {
        self.inner.link_property(s, l, t, p)
    }
    fn graph_declarations(&self) -> Vec<crate::GraphDeclaration> {
        vec![crate::GraphDeclaration {
            scope: "//a(->e)*".to_string(),
            hop: "->e".to_string(),
            measures: vec!["kcore".to_string(), "pagerank(--damping=0.5)".to_string()],
        }]
    }
    fn graph_measure(
        &self,
        scope: &str,
        hop: &str,
        measure: &str,
        nodes: &[NodeId],
    ) -> Option<Vec<Value>> {
        self.asked.set(self.asked.get() + 1);
        let kept = self.kept.borrow();
        let v = kept.get(&(scope.to_string(), hop.to_string(), measure.to_string()))?;
        (v.len() == nodes.len()).then(|| v.clone())
    }
    fn store_graph_measure(
        &self,
        scope: &str,
        hop: &str,
        measure: &str,
        _: &[NodeId],
        values: &[Value],
    ) {
        self.kept.borrow_mut().insert(
            (scope.to_string(), hop.to_string(), measure.to_string()),
            values.to_vec(),
        );
    }
}

#[test]
fn a_declared_graph_answers_once_the_context_is_the_scope() {
    let d = Declaring {
        inner: MockTree::roads(),
        kept: Default::default(),
        asked: Default::default(),
    };
    let run = |q: &str| match crate::Query::parse(q, &d)
        .unwrap()
        .run(&d, &Default::default())
        .unwrap()
        .result
    {
        QueryResult::Values(vs) => vs,
        _ => panic!("values"),
    };
    // the first query computes and offers the values back
    let first = run("//a(->e)* @| collapse @| graph:kcore(->e)");
    assert_eq!(d.asked.get(), 1);
    assert_eq!(d.kept.borrow().len(), 1);
    // the second is answered from what the source kept
    let second = run("//a(->e)* @| collapse @| graph:kcore(->e)");
    assert_eq!(first, second);
    assert_eq!(d.asked.get(), 2);
    assert_eq!(d.kept.borrow().len(), 1);
    // a narrower context is not the scope: computed, never stored
    let narrow = run("//a(->e)*[:name != \"deep\"] @| collapse @| graph:kcore(->e)");
    assert_eq!(narrow.len(), 3);
    assert_eq!(d.asked.get(), 2);
    assert_eq!(d.kept.borrow().len(), 1);
    // other options are another measure: pagerank at the declared
    // damping is kept, at the default damping it is not
    run("//a(->e)* @| collapse @| graph:pagerank(->e; --damping=0.5)");
    assert_eq!(d.kept.borrow().len(), 2);
    run("//a(->e)* @| collapse @| graph:pagerank(->e)");
    assert_eq!(d.kept.borrow().len(), 2);
}

// ── draft.191: a predicate on a hop operand, reading through a reference ──

#[test]
fn a_hop_operand_takes_the_walks_predicate() {
    let t = MockTree::roads();
    // the target node as topic: only the edges into deep
    let (_, rows) = table_of("//a(->e)* @| edges(->e[:name = \"deep\"])", &t);
    assert_eq!(rows.len(), 2, "{rows:?}");
    assert!(rows.iter().all(|r| r[1] == "/b/deep"));
    // `$-` the edge: the roads longer than 2 km
    let (_, rows) = table_of("//a(->e)* @| edges(->e[$-::len > 2_km])", &t);
    assert_eq!(rows.len(), 3, "{rows:?}");
    // the library reads the same hop: without the 12 km road deep is
    // reached through y.txt alone, so x.rs cuts nothing and deep's
    // route runs through y.txt
    let routes = vals(
        "//a(->e)* @| collapse @| graph:route(->e[$-::len < 10_km]; --from=/a)",
        &t,
    );
    assert_eq!(list_strs(&routes[3]), ["/a", "/a/y.txt", "/b/deep"]);
    // an undirected hop filtered by the edge: the 3 km road back from
    // deep keeps the cycle whole, so nothing cuts; under 3 km only
    // a-y.txt-deep remain, a path whose middle node cuts
    let cut = vals(
        "//a(->e)* @| collapse @| graph:artpoints(--e[$-::len < 10_km])",
        &t,
    );
    assert_eq!(cut, vec![Value::Bool(false); 4]);
    let cut = vals(
        "//a(->e)* @| collapse @| graph:artpoints(--e[$-::len < 3_km])",
        &t,
    );
    assert_eq!(
        cut,
        vec![
            Value::Bool(false),
            Value::Bool(false),
            Value::Bool(true),
            Value::Bool(false)
        ]
    );
}

#[test]
fn the_parser_reads_a_property_through_a_reference() {
    let q = parse(&lex("/x | :source::code").unwrap()).unwrap();
    assert!(format!("{:?}", q.pipeline).contains("Through"));
    let t = MockTree::roads();
    // the edges table's node columns read the node they name
    let (_, rows) = table_of("//a(->e)* @| edges(->e)", &t);
    assert_eq!(rows[0][0], "/a");
    let names = vals("//a(->e)* @| edges(->e) | :source:name", &t);
    assert_eq!(names.len(), 1);
    assert_eq!(list_strs(&names[0]), ["a", "a", "x.rs", "y.txt", "deep"]);
    // a route's nodes read their names along the way
    let names = vals(
        "//a(->e)* @| collapse @| graph:route(->e; --from=/a) | map(:name)",
        &t,
    );
    assert_eq!(list_strs(&names[3]), ["a", "x.rs", "deep"]);
    // a subcontext on a node-valued field reads the node too
    let names = vals("//a(->e)* @| edges(->e) | (:target | :name)", &t);
    assert_eq!(
        list_strs(&names[0]),
        ["x.rs", "y.txt", "deep", "deep", "x.rs"]
    );
}

// ── the third shipment: closeness, communities, modularity, triangles ──

#[test]
fn closeness_communities_modularity_and_triangles() {
    let t = MockTree::roads();
    // closeness along ->e: a reaches the three others in 1, 1, 2 hops
    let c = vals("//a(->e)* @| collapse @| graph:closeness(->e)", &t);
    let Value::Float(a) = c[0] else {
        panic!("{c:?}")
    };
    assert!((a - (3.0 / 3.0) * (3.0 / 4.0)).abs() < 1e-12, "{a}");
    // deep reaches x.rs only
    let Value::Float(deep) = c[3] else {
        panic!("{c:?}")
    };
    assert!((deep - (1.0 / 3.0) * (1.0 / 1.0)).abs() < 1e-12, "{deep}");
    let h = vals(
        "//a(->e)* @| collapse @| graph:closeness(->e; --harmonic)",
        &t,
    );
    let Value::Float(ah) = h[0] else {
        panic!("{h:?}")
    };
    assert!((ah - (1.0 + 1.0 + 0.5) / 3.0).abs() < 1e-12, "{ah}");
    // by weight the distances are in the unit named: from a, x.rs at
    // 4 km, y.txt at 1 km, deep at 3 km through y.txt, eight in all
    let c = vals(
        "//a(->e)* @| collapse @| graph:closeness(->e; --weight=km)",
        &t,
    );
    let Value::Float(a_km) = c[0] else {
        panic!("{c:?}")
    };
    assert!((a_km - 3.0 / 8.0).abs() < 1e-12, "{a_km}");
    // the ring a-x-deep-y is one community
    let cs = vals("//a(->e)* @| collapse @| graph:communities(--e)", &t);
    assert_eq!(cs, vec![Value::Int(1); 4]);
    // its modularity under its own partition is zero (one part), and
    // a partition by name scores below
    let q = vals(
        "//a(->e)* @| collapse @| graph:communities(--e) | .:c @| graph:modularity(--e; --by=:.c)",
        &t,
    );
    assert_eq!(q.len(), 1);
    let Value::Float(q0) = q[0] else {
        panic!("{q:?}")
    };
    assert!(q0.abs() < 1e-12, "{q0}");
    let q = vals(
        "//a(->e)* @| collapse | .:p(:name) @| graph:modularity(--e; --by=:.p)",
        &t,
    );
    let Value::Float(q1) = q[0] else {
        panic!("{q:?}")
    };
    assert!(q1 < 0.0, "{q1}");
    // --by is required
    assert!(vals("//a(->e)* @| graph:modularity(--e)", &t).is_empty());
    // no triangle on the roads; the coefficient is zero everywhere;
    // a weight refuses
    assert_eq!(
        vals("//a(->e)* @| collapse @| graph:triangles(--e)", &t),
        vec![Value::Int(0); 4]
    );
    assert_eq!(
        vals(
            "//a(->e)* @| collapse @| graph:triangles(--e; --coefficient)",
            &t
        ),
        vec![Value::Float(0.0); 4]
    );
    assert!(vals("//a(->e)* @| graph:triangles(--e; --weight=km)", &t).is_empty());
}

// ── omitted data (spec: omitted data, 2026-11-01) ──────────────────

/// The roads with a `salary` on a, x.rs and y.txt, y.txt's withheld,
/// and whole nodes dropped when asked.
struct Withholding {
    inner: MockTree,
    dropped_nodes: bool,
}

impl AstAdapter for Withholding {
    fn root(&self) -> NodeId {
        self.inner.root()
    }
    fn children(&self, n: NodeId) -> Vec<NodeId> {
        self.inner.children(n)
    }
    fn name(&self, n: NodeId) -> Option<String> {
        self.inner.name(n)
    }
    fn parent(&self, n: NodeId) -> Option<NodeId> {
        self.inner.parent(n)
    }
    fn non_tree_nodes(&self) -> Vec<NodeId> {
        self.inner.non_tree_nodes()
    }
    fn links(&self, n: NodeId) -> Vec<(String, NodeId)> {
        self.inner.links(n)
    }
    fn traits(&self, n: NodeId) -> Vec<String> {
        self.inner.traits(n)
    }
    fn backlinks(&self, n: NodeId) -> Vec<(String, NodeId)> {
        self.inner.backlinks(n)
    }
    fn property(&self, n: NodeId, name: &str) -> Option<Value> {
        match (n.0, name) {
            (1, "salary") => Some(Value::Int(10)),
            (2, "salary") => Some(Value::Int(20)),
            (1 | 2 | 3, "grade") => Some(Value::Str("b".into())),
            _ => None,
        }
    }
    fn property_names(&self, n: NodeId) -> Vec<String> {
        match n.0 {
            1 | 2 => vec!["salary".into(), "grade".into()],
            3 => vec!["grade".into()],
            _ => Vec::new(),
        }
    }
    fn property_withheld(&self, n: NodeId, name: &str) -> bool {
        n.0 == 3 && name == "salary"
    }
    fn nodes_withheld(&self) -> bool {
        self.dropped_nodes
    }
}

fn run_omitting(
    q: &str,
    dropped_nodes: bool,
) -> (
    Result<Vec<Value>, String>,
    Vec<crate::diagnostic::Diagnostic>,
) {
    let w = Withholding {
        inner: MockTree::roads(),
        dropped_nodes,
    };
    match crate::Query::parse(q, &w)
        .unwrap()
        .run(&w, &Default::default())
    {
        Ok(o) => (
            Ok(match o.result {
                QueryResult::Values(vs) => vs,
                QueryResult::Nodes(ns) => ns.into_iter().map(|_| Value::Null).collect(),
            }),
            o.diagnostics,
        ),
        Err(e) => (Err(e.to_string()), Vec::new()),
    }
}

const OMITTED_TEXT: &str = "some data is omitted due to insufficient permissions";

#[test]
fn withheld_data_reads_absent_with_one_warning() {
    let (vs, diags) = run_omitting("//a(->e)* @| collapse | ::salary", false);
    assert_eq!(
        vs.unwrap(),
        vec![Value::Int(10), Value::Int(20), Value::Null, Value::Null]
    );
    let omitted: Vec<_> = diags.iter().filter(|d| d.code == "OMITTED").collect();
    assert_eq!(omitted.len(), 1, "{diags:?}");
    assert_eq!(omitted[0].message, OMITTED_TEXT);
    assert_eq!(omitted[0].site, "source");
    assert_eq!(omitted[0].severity, crate::diagnostic::Severity::Warning);
    // two withheld reads, one warning; without a withheld read, none
    let (_, diags) = run_omitting(
        "//a(->e)* @| collapse | %(::salary; ::grade; s = ::salary)",
        false,
    );
    assert_eq!(diags.iter().filter(|d| d.code == "OMITTED").count(), 1);
    let (_, diags) = run_omitting("//a(->e)* @| collapse | ::grade", false);
    assert_eq!(diags.iter().filter(|d| d.code == "OMITTED").count(), 0);
    // whole nodes dropped: the same one warning, even beside a withheld read
    let (_, diags) = run_omitting("//a(->e)* @| collapse | ::grade", true);
    assert_eq!(diags.iter().filter(|d| d.code == "OMITTED").count(), 1);
    let (_, diags) = run_omitting("//a(->e)* @| collapse | ::salary", true);
    assert_eq!(diags.iter().filter(|d| d.code == "OMITTED").count(), 1);
    // a count reveals nothing and passes, with the warning
    let (vs, diags) = run_omitting("//a(->e)* @| collapse | ::salary @| count", false);
    assert_eq!(vs.unwrap(), vec![Value::Int(4)]);
    assert_eq!(diags.iter().filter(|d| d.code == "OMITTED").count(), 1);
}

#[test]
fn keying_on_a_withheld_property_refuses() {
    for q in [
        "//a(->e)*[::salary > 5]",
        "//a(->e)* @| collapse | [::salary > 5]",
        "//a(->e)* @| collapse | ::salary @| sum",
        "//a(->e)* @| collapse | ::salary @| sort",
        "//a(->e)* @| collapse | ::salary @| unique",
        "//a(->e)* @| collapse | %(s = ::salary; n = :name) @| top(1; :s)",
    ] {
        let (r, _) = run_omitting(q, false);
        let err = r.err().unwrap_or_else(|| panic!("{q} passed"));
        assert!(err.contains(OMITTED_TEXT), "{q}: {err}");
    }
    // a key on an ordinary property beside it passes
    assert_eq!(
        run_omitting("//a(->e)* @| collapse | [::grade = \"b\"] @| count", false)
            .0
            .unwrap(),
        vec![Value::Int(3)]
    );
}

// ── the projector after a pipe; round leaves what it cannot round
// (rulings 2026-11-01) ──────────────────────────────────────────────

#[test]
fn projector_after_a_pipe() {
    let t = MockTree::sample();
    let s = |q: &str| {
        vals(q, &t)
            .iter()
            .map(|v| v.to_string())
            .collect::<Vec<_>>()
            .join(" | ")
    };
    // `| #(:a; :b)` on a table keeps the columns named, in that order
    assert_eq!(
        s("#(@(a; b; c); %(1; 2; 3); %(4; 5; 6)) | #(:c; :a)"),
        s("#(@(c; a); %(3; 1); %(6; 4))")
    );
    // on a record `%` keeps the fields named; on a list of records,
    // each item
    assert_eq!(
        s("%(a = 1; b = 2; c = 3) | %(:a; :b)"),
        s("%(a = 1; b = 2)")
    );
    assert_eq!(
        s("@(%(a = 1; b = 2; c = 3); %(a = 4; b = 5; c = 6)) | %(:a; :b)"),
        s("@(%(a = 1; b = 2); %(a = 4; b = 5))")
    );
    // a constructor with a named item stays the constructor
    assert_eq!(
        s("%(a = 1; b = 2) | %(x = :a; b = 2)"),
        s("%(x = 1; b = 2)")
    );
    // the literal's rows still need rows
    assert!(parse(&lex("@(1) | #(:a; 2)").unwrap()).is_ok());
}

#[test]
fn round_leaves_what_it_cannot_round() {
    let t = MockTree::sample();
    let s = |q: &str| {
        vals(q, &t)
            .iter()
            .map(|v| v.to_string())
            .collect::<Vec<_>>()
            .join(" | ")
    };
    assert_eq!(
        s("%(a = \"x\"; b = 1.23456) | round(2)"),
        s("%(a = \"x\"; b = 1.23)")
    );
    assert_eq!(
        s("#(@(a; b); %(\"x\"; 1.23456); %(\"y\"; 2.5)) | round(2)"),
        s("#(@(a; b); %(\"x\"; 1.23); %(\"y\"; 2.5))")
    );
    assert_eq!(s("@(\"n/a\"; 2.5; null) | floor"), s("@(\"n/a\"; 2; null)"));
    assert_eq!(s("\"n/a\" | round(2)"), s("\"n/a\""));
    assert_eq!(s("@(-1; \"x\") | abs"), s("@(1; \"x\")"));
}