decl-lang 0.4.7

Decl — a declarative language for describing, generating, and validating structured data: the `decl` CLI (check / evaluate / validate / fmt) and the `decl-lsp` language server, implemented natively in Rust
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
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
//! Binding, evaluation, validation, and serialization — a port of the
//! reference implementation's engine.ts. Semantics are the spec's: lazy
//! slots with cycle detection, taint / root-cause diagnostics,
//! $referrers universe ordering, canonical JSON output.
use crate::ast::*;
#[cfg(feature = "runtime-diagnostics")]
use crate::evaluation_diagnostics::EventStage;
#[cfg(feature = "runtime-diagnostics")]
use crate::expression_diagnostics as expr_diag;
use crate::qengine::edits::Edits;
use crate::qengine::graph::{QueryId, QueryPool, ReadSet};
use crate::qengine::programs::{Programs, Schema};
use crate::qengine::revisions::Revisions;
use crate::qengine::rounds::RoundCache;
use crate::semantics::*;
use crate::subsume::subsumes;
use num_traits::Signed;
use rustc_hash::{FxHashMap, FxHashSet};
use std::borrow::Cow;
use std::cell::{Cell, RefCell};
use std::cmp::Ordering::{self, Equal, Greater, Less};
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::rc::{Rc, Weak};

/// a record instance, shared: the engine's unit of binding and forcing
pub type Inst = Rc<RefCell<RecInst>>;

#[cfg(test)]
#[path = "../tests/private/query_record_test.rs"]
mod query_record_tests;

#[cfg(test)]
#[path = "../tests/private/materialized_cache_test.rs"]
mod materialized_cache_tests;

#[cfg(test)]
#[path = "../tests/private/binding_path_test.rs"]
mod binding_path_tests;

#[cfg(test)]
#[path = "../tests/private/binding_input_test.rs"]
mod binding_input_tests;

#[cfg(test)]
#[path = "../tests/private/binding_lookup_test.rs"]
mod binding_lookup_tests;

#[cfg(test)]
#[path = "../tests/private/binding_key_test.rs"]
mod binding_key_tests;

#[cfg(test)]
#[path = "../tests/private/record_emission_test.rs"]
mod record_emission_tests;

// Immutable JSON containers remain owned by `raw` throughout binding. Clone
// only the item being visited; mutable and expanded inputs keep their eager
// snapshots and move each item out without an additional clone.
enum BindingInput<'a, T> {
    Borrowed(std::slice::Iter<'a, T>),
    Owned(std::vec::IntoIter<T>),
}

impl<T: Clone> Iterator for BindingInput<'_, T> {
    type Item = T;

    fn next(&mut self) -> Option<T> {
        match self {
            Self::Borrowed(items) => items.next().cloned(),
            Self::Owned(items) => items.next(),
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        match self {
            Self::Borrowed(items) => items.size_hint(),
            Self::Owned(items) => items.size_hint(),
        }
    }
}

impl<T: Clone> ExactSizeIterator for BindingInput<'_, T> {}

// Scratch lookup borrows the ordered input snapshot. Only the selected value
// gains an owner when its slot is constructed. Each reentrant bind owns its
// own scratch storage, while the immutable schema supplies stable indices.
enum RecordLookup<'a> {
    Direct(&'a [(String, Value)]),
    Named(HashMap<&'a str, &'a Value>),
    Indexed(IndexedInput<'a>),
}

impl<'a> RecordLookup<'a> {
    fn new(entries: &'a [(String, Value)], members: usize, schema: Option<&Schema>) -> Self {
        if entries.len() <= 1 || members <= 1 {
            return Self::Direct(entries);
        }
        if let Some(schema) = schema.filter(|s| s.names.len() == members) {
            let mut supplied = IndexedInput::Inline {
                entries: [None; 8],
                len: 0,
            };
            for (name, value) in entries {
                if let Some(&index) = schema.names.get(name.as_str()) {
                    supplied.insert(index, value, members);
                }
            }
            Self::Indexed(supplied)
        } else {
            // Bare engines and native duplicate schema names keep the name
            // lookup: each repeated member receives the same last input.
            let mut supplied = HashMap::new();
            for (name, value) in entries {
                supplied.insert(name.as_str(), value);
            }
            Self::Named(supplied)
        }
    }

    fn get(&self, index: usize, name: &str) -> Option<&'a Value> {
        match self {
            Self::Direct(entries) => entries
                .iter()
                .rev()
                .find_map(|(key, value)| (key == name).then_some(value)),
            Self::Named(entries) => entries.get(name).copied(),
            Self::Indexed(entries) => entries.get(index),
        }
    }
}

enum IndexedInput<'a> {
    // Eight distinct hits require no heap allocation, regardless of schema
    // width, unknown keys, or repeated occurrences of the same input key.
    Inline {
        entries: [Option<(usize, &'a Value)>; 8],
        len: usize,
    },
    Sparse(FxHashMap<usize, &'a Value>),
    Dense(Vec<Option<&'a Value>>),
}

impl<'a> IndexedInput<'a> {
    fn insert(&mut self, index: usize, value: &'a Value, members: usize) {
        match self {
            Self::Inline { entries, len } => {
                if let Some((_, previous)) = entries[..*len]
                    .iter_mut()
                    .flatten()
                    .find(|(key, _)| *key == index)
                {
                    *previous = value;
                    return;
                }
                if *len < entries.len() {
                    entries[*len] = Some((index, value));
                    *len += 1;
                    return;
                }
                // A dense cell is one pointer; a sparse pair is an index and
                // pointer. At half density, dense payload does not exceed the
                // distinct sparse pairs, before any hash-table overhead.
                if *len + 1 >= members.div_ceil(2) {
                    let mut dense = vec![None; members];
                    for &(key, value) in entries.iter().flatten() {
                        dense[key] = Some(value);
                    }
                    dense[index] = Some(value);
                    *self = Self::Dense(dense);
                } else {
                    let mut sparse = FxHashMap::default();
                    sparse.reserve(*len + 1);
                    for &(key, value) in entries.iter().flatten() {
                        sparse.insert(key, value);
                    }
                    sparse.insert(index, value);
                    *self = Self::Sparse(sparse);
                }
            }
            Self::Sparse(entries) => {
                if let Some(previous) = entries.get_mut(&index) {
                    *previous = value;
                } else if entries.len() + 1 >= members.div_ceil(2) {
                    let mut dense = vec![None; members];
                    for (&key, &value) in entries.iter() {
                        dense[key] = Some(value);
                    }
                    dense[index] = Some(value);
                    *self = Self::Dense(dense);
                } else {
                    entries.insert(index, value);
                }
            }
            Self::Dense(entries) => entries[index] = Some(value),
        }
    }

    fn get(&self, index: usize) -> Option<&'a Value> {
        match self {
            Self::Inline { entries, len } => entries[..*len]
                .iter()
                .flatten()
                .find_map(|&(key, value)| (key == index).then_some(value)),
            Self::Sparse(entries) => entries.get(&index).copied(),
            Self::Dense(entries) => entries[index],
        }
    }
}

/// the evaluator (§9): binds documents and expressions to types, forces slots
/// lazily with dependency tracking, validates, serializes
pub struct Engine {
    /// the environment the roots live in
    pub env: Rc<Env>,
    /// slots whose forcing was deferred to phase 2 (a `$referrers` read, a reference not yet bound)
    pub deferred_slots: RefCell<Vec<(Inst, String)>>,
    pub(crate) no_reg: Cell<u32>,
    pub(crate) phase: Cell<u8>,
    /// inputs whose fallback failed to bind: later demands are tainted, not re-reported
    pub failed_inputs: RefCell<HashSet<String>>,
    // ---- dependency tracking (Phase 6 foundations; docs/tooling/02_repl.md §6) ----
    // every evaluation step — a slot being computed (`path.member`), a root
    // being bound (`root:name`), an instance's asserts (`assert:path`) —
    // records what it read: slots, roots, and `$referrers` queries by type
    // (`referrers:Type`); diagnostics carry the step that produced them
    /// the dependency graph: the slot keys each computation read (the session's incremental step)
    pub(crate) reads: RefCell<FxHashMap<QueryId, ReadSet>>,
    /// Sessions and retained reference rounds enable dependency recording.
    /// Ordinary one-shot work avoids the per-slot graph allocation (F21).
    pub track: Cell<bool>,
    /// the slots being forced, innermost last: a key already here is a cycle (E5007)
    pub(crate) computing: RefCell<Vec<QueryId>>,
    /// every slot by its key, for the dependency graph
    pub(crate) slots_by_key: RefCell<FxHashMap<QueryId, (Inst, Rc<str>)>>,
    query_keys: Rc<QueryPool>,
    /// roots whose binding deferred through `$referrers` in phase 1: bound again after the deferred slots
    pub deferred_roots: RefCell<Vec<DeferredRoot>>,
    // ---- `$referrers` is answered in rounds (§7.6) ----
    // a round answers from a fixed snapshot — round 1 from what phase 1
    // materialized, every later round from the previous round's whole
    // universe, kept frozen in `prev` — never from what it creates itself;
    // rounds repeat until the queried edges stop changing (`Engine::evaluate`)
    /// the previous round, frozen
    pub prev: RefCell<Option<Rc<Engine>>>,
    /// this round's roots once frozen
    pub(crate) frozen_roots: RefCell<Option<Vec<(String, Value)>>>,
    /// this round's instances once frozen
    pub(crate) frozen_registry: RefCell<Option<Vec<Inst>>>,
    /// the frozen instances by address: what `force_slot` delegates to this round
    pub(crate) frozen_set: RefCell<FxHashSet<usize>>,
    /// a copied round's records by canonical path: where an answer is looked up
    pub(crate) frozen_index: RefCell<Option<FxHashMap<String, Inst>>>,
    /// the last round: a reference into the snapshot resolves live
    pub(crate) settled: Cell<bool>,
    /// the snapshot a round answers from
    pub(crate) snap: RefCell<Option<Snap>>,
    /// the edges `T|m` queried so far
    pub(crate) queried: RefCell<BTreeSet<String>>,
    /// an inverse index of each edge, `T|m` -> (target path -> its referrers'
    /// paths): built once from the edge so a `$referrers` query is a lookup,
    /// not a scan of every candidate's refs (§7.6). Fresh per round.
    pub(crate) ref_index: RefCell<FxHashMap<String, Rc<FxHashMap<String, Vec<SegPath>>>>>,
    /// the edges being computed: a query for one of them from inside its own
    /// computation is unanswerable in this round (the member is excluded)
    pub(crate) computing_edges: RefCell<HashSet<String>>,
    /// the depth of the forcing stack when each edge computation began: a
    /// slot forcing below that depth waits on the answer the edge serves
    pub(crate) edge_bases: RefCell<Vec<usize>>,
    /// the environments whose constants this engine forced
    pub(crate) const_envs: RefCell<Vec<Rc<Env>>>,
    /// the answers' references into the previous round, by identity
    pub(crate) snap_refs: RefCell<FxHashMap<usize, (Rc<SegPath>, Rc<Engine>)>>,
    /// An unmaterialized literal is materialized once by allocation identity.
    /// Weak raw owners pin that identity without retaining discarded captures;
    /// Results stay strong while raw literals can be reused. Expired raw
    /// identities are periodically retired without keeping their result graphs.
    mat_cache: RefCell<MaterializedCache>,
    materialized_sweep_at: Cell<usize>,
    /// Bounded weak sharing for typed-container paths; it owns no runtime values.
    path_pool: RefCell<PrefixPathPool>,
    map_shapes: RefCell<MapShapePool>,
    /// Shared executable programs, enabled by the query evaluator.
    pub programs: RefCell<Option<Rc<Programs>>>,
    /// Revision stamps for retained queries.
    pub revisions: RefCell<Option<Rc<Revisions>>>,
    /// Retained queries for document edits in a Session.
    pub edits: RefCell<Option<Rc<Edits>>>,
    verifying_depth: Cell<Option<usize>>,
    /// Reference-round reuse state, enabled by the query evaluator.
    pub round_cache: RefCell<Option<Rc<RoundCache>>>,
    pub(crate) round_roots: RefCell<Option<HashSet<String>>>,
    pub(crate) round_resets: RefCell<Vec<Rc<dyn Fn()>>>,
    pub(crate) round_refs: RefCell<FxHashMap<usize, Rc<SegPath>>>,
    pub(crate) inverse_refs: RefCell<FxHashMap<usize, Rc<SegPath>>>,
    // Must drop after every Engine field and every frozen Engine.
    _lifetime: lifetime::EngineGuard,
}

// Keep the Rc allocation identity pinned without retaining the raw literal's
// Vec contents and their captured scopes. A live raw owner must keep the same
// strong result even when every caller drops its returned handle: recomputing
// could repeat native callbacks or observe later mutable inputs.
// A Weak keeps its allocation address unavailable for reuse even after the
// last raw strong owner drops; array/object variants retain the correct type.
enum MaterializedLiteral {
    Array(Weak<Vec<(bool, Value)>>),
    Object(Weak<Vec<(String, Value)>>),
}
type MaterializedCache = FxHashMap<usize, (MaterializedLiteral, Value)>;
const MATERIALIZED_SWEEP_MIN: usize = 1024;
impl MaterializedLiteral {
    fn alive(&self) -> bool {
        match self {
            Self::Array(owner) => owner.strong_count() != 0,
            Self::Object(owner) => owner.strong_count() != 0,
        }
    }
    fn matches(&self, raw: &Value) -> bool {
        match (self, raw) {
            (Self::Array(owner), Value::PreArr(v)) => owner.as_ptr() == Rc::as_ptr(v),
            (Self::Object(owner), Value::PreObj(v)) => owner.as_ptr() == Rc::as_ptr(v),
            _ => false,
        }
    }
    fn of(raw: &Value) -> Self {
        match raw {
            Value::PreArr(v) => Self::Array(Rc::downgrade(v)),
            Value::PreObj(v) => Self::Object(Rc::downgrade(v)),
            _ => unreachable!("materialization cache only stores unbound literals"),
        }
    }
}

/// the values `std.array.sort` orders: one primitive kind per call (§13.2)
fn is_orderable(x: &Value) -> bool {
    matches!(x, Value::Int(_) | Value::Float(_) | Value::Str(_))
}
/// int and float by value, strings by code point (§4.5); a mix of kinds is a domain error
fn cmp_prim(x: &Value, y: &Value) -> R<Ordering> {
    match (x, y) {
        (Value::Str(a), Value::Str(b)) => Ok(a.chars().cmp(b.chars())),
        (Value::Int(a), Value::Int(b)) => Ok(a.cmp(b)),
        (Value::Float(a), Value::Float(b)) => Ok(a.partial_cmp(b).unwrap_or(Equal)),
        (Value::Int(a), Value::Float(b)) => {
            Ok(a.to_f64().unwrap_or(0.0).partial_cmp(b).unwrap_or(Equal))
        }
        (Value::Float(a), Value::Int(b)) => {
            Ok(a.partial_cmp(&b.to_f64().unwrap_or(0.0)).unwrap_or(Equal))
        }
        _ => err_code("std.array.sort: elements must be of one kind", "E5008"),
    }
}
/// a stable sort by key (equal keys keep their order)
fn sort_keyed(keyed: &mut [(Value, Value)]) -> R<()> {
    let mut failed: Option<Fail> = None;
    keyed.sort_by(|p, q| match cmp_prim(&p.0, &q.0) {
        Ok(o) => o,
        Err(e) => {
            if failed.is_none() {
                failed = Some(e);
            }
            Equal
        }
    });
    match failed {
        Some(e) => Err(e),
        None => Ok(()),
    }
}
/// one `$referrers` edge: every referrer's path (keyed by its text) with the places its member refers to
pub(crate) type Edge = BTreeMap<String, (SegPath, Vec<SegPath>)>;
/// the universe a round answers from
pub struct Snap {
    insts: HashMap<String, Vec<Inst>>,
    pub(crate) edges: HashMap<String, Edge>,
}
/// what one round found: whether the queried edges were stable, and what they are
pub struct Settled {
    /// no queried edge changed
    pub stable: bool,
    /// the queried edges over the round's universe
    pub edges: HashMap<String, Edge>,
    /// the edges that changed, sorted
    pub changed: Vec<String>,
}
/// the references under a value: arrays and maps are traversed, records are not (§7.6)
fn refs_in(v: &Value, out: &mut Vec<SegPath>) {
    match v {
        Value::Ref(p) => out.push((**p).clone()),
        Value::Arr(a) => {
            for x in &a.borrow().items {
                refs_in(x, out);
            }
        }
        Value::Map(m) => {
            for (_, x) in &m.borrow().entries {
                refs_in(x, out);
            }
        }
        _ => {}
    }
}
fn refs_key(refs: &[SegPath]) -> String {
    let mut ks: Vec<String> = refs.iter().map(|r| path_str(r, None)).collect();
    ks.sort();
    ks.join("\n")
}
// a fingerprint of the queried edges, for detecting a round that repeats a
// previous one (a non-settling cycle, §7.6)
fn edges_key(edges: &HashMap<String, Edge>) -> String {
    let mut keys: Vec<&String> = edges.keys().collect();
    keys.sort();
    keys.iter()
        .map(|k| {
            let e = &edges[*k];
            let inner: Vec<String> = e
                .iter()
                .map(|(pk, (_, refs))| format!("{pk}:{}", refs_key(refs)))
                .collect();
            format!("{k}={}", inner.join(";"))
        })
        .collect::<Vec<_>>()
        .join("|")
}
fn edge_eq(a: &Edge, b: &Edge) -> bool {
    a.len() == b.len()
        && a.iter()
            .all(|(k, (_, r))| b.get(k).is_some_and(|(_, q)| refs_key(r) == refs_key(q)))
}
/// the first referrer (canonical order) whose entry differs between two edges
fn edge_diff(a: &Edge, b: &Edge) -> String {
    let mut paths: Vec<&SegPath> = a
        .keys()
        .chain(b.keys())
        .collect::<BTreeSet<_>>()
        .into_iter()
        .map(|k| &a.get(k).or_else(|| b.get(k)).unwrap().0)
        .collect();
    paths.sort_by(|x, y| path_key_cmp(x, y));
    for p in paths {
        let k = path_str(p, None);
        match (a.get(&k), b.get(&k)) {
            (Some((_, r)), Some((_, q))) if refs_key(r) == refs_key(q) => {}
            _ => return k,
        }
    }
    String::new()
}
fn group_by_type(insts: &[Inst]) -> HashMap<String, Vec<Inst>> {
    let mut out: HashMap<String, Vec<Inst>> = HashMap::new();
    for inst in insts {
        if let Some(t) = inst.borrow().type_name.clone() {
            out.entry(t).or_default().push(inst.clone());
        }
    }
    out
}

/// a root binding kept for phase 2 (its source owned)
pub struct DeferredRoot {
    /// the root's name
    pub name: String,
    /// what it is bound from
    pub src: OwnedRootSrc,
    /// its declared type, resolved
    pub rt: RT,
    /// the scope it is bound in
    pub sc: Scope,
}
/// what a deferred root is bound from, owned
pub enum OwnedRootSrc {
    /// an output's expression
    Expr(Rc<Expr>),
    /// a document
    Doc(Value),
}

/// what an evaluation root is bound from: an output's expression, or an
/// input's document (bound as-is)
pub enum RootSrc<'a> {
    /// an output's expression
    Expr(&'a Rc<Expr>),
    /// a document
    Doc(Value),
}

pub(crate) fn num_cmp(a: &Value, b: &Value) -> Option<Ordering> {
    match (a, b) {
        (Value::Int(x), Value::Int(y)) => Some(x.cmp(y)),
        (Value::Float(x), Value::Float(y)) => x.partial_cmp(y),
        (Value::Int(x), Value::Float(y)) => x.to_f64()?.partial_cmp(y),
        (Value::Float(x), Value::Int(y)) => x.partial_cmp(&y.to_f64()?),
        (Value::Str(x), Value::Str(y)) => Some(x.cmp(y)),
        _ => None,
    }
}

fn exact_float(i: &Num) -> Option<f64> {
    let f = i.to_f64()?;
    if !f.is_finite() {
        return None;
    }
    if Num::from_f64(f).as_ref() == Some(i) {
        Some(f)
    } else {
        None
    }
}

fn num_s(v: &Value) -> String {
    match v {
        Value::Float(f) => js_num_str(*f),
        Value::Int(i) => i.to_string(),
        Value::Str(s) => s.to_string(),
        other => format!("{other:?}"),
    }
}

fn lit_display(v: &Value) -> String {
    match v {
        Value::Bool(b) => {
            if *b {
                "true".into()
            } else {
                "false".into()
            }
        }
        Value::Null => "null".into(),
        other => num_s(other),
    }
}

/// the trailing member of a slot key (`r.ports["a"].sel$` -> `sel$`)
fn member_of_key(key: &str) -> String {
    if let Some(rest) = key.strip_suffix(']') {
        if let Some(i) = rest.rfind("[\"") {
            return rest[i + 2..].to_string();
        }
    }
    match key.rfind('.') {
        Some(i) => key[i + 1..].to_string(),
        None => key.to_string(),
    }
}

pub(crate) fn to_index(v: &Value) -> R<i64> {
    match v {
        Value::Int(i) => i.to_i64().ok_or(()).or_else(|_| err("index out of range")),
        Value::Float(f) => Ok(*f as i64),
        _ => err("index must be an integer"),
    }
}

fn path_key_cmp(a: &[Seg], b: &[Seg]) -> Ordering {
    for (x, y) in a.iter().zip(b) {
        let o = match (x, y) {
            (Seg::Idx(i), Seg::Idx(j)) => i.cmp(j),
            (Seg::Idx(_), _) => Less,
            (_, Seg::Idx(_)) => Greater,
            _ => seg_text(x).cmp(&seg_text(y)),
        };
        if o != Equal {
            return o;
        }
    }
    a.len().cmp(&b.len())
}

fn arg<'a>(a: &'a [Value], i: usize, name: &str) -> R<&'a Value> {
    a.get(i)
        .ok_or(())
        .or_else(|_| err(format!("std.{name}: missing argument {i}")))
}

fn add_num(a: &Value, b: &Value) -> R<Value> {
    Ok(match (a, b) {
        (Value::Int(x), Value::Int(y)) => Value::Int(x + y),
        (Value::Float(x), Value::Float(y)) => Value::Float(x + y),
        (Value::Int(x), Value::Float(y)) => Value::Float(x.to_f64().unwrap_or(f64::INFINITY) + y),
        (Value::Float(x), Value::Int(y)) => Value::Float(x + y.to_f64().unwrap_or(f64::INFINITY)),
        _ => return err("bad operands for +"),
    })
}

fn structural_of(v: &Value) -> RT {
    match v {
        Value::Bool(_) => ty(RTk::Prim("bool".into())),
        Value::Int(_) => ty(RTk::Prim("int".into())),
        Value::Float(_) => ty(RTk::Prim("float".into())),
        Value::Str(_) => ty(RTk::Prim("string".into())),
        Value::Null => ty(RTk::Prim("null".into())),
        Value::Ref(_) => ty(RTk::Ref(ty(RTk::Any))),
        Value::Arr(a) => {
            let elem = a
                .borrow()
                .items
                .first()
                .map(structural_of)
                .unwrap_or_else(|| ty(RTk::Any));
            ty(RTk::Arr {
                elem,
                lo: None,
                hi: None,
            })
        }
        Value::Q(q) => ty(RTk::Quantity(q.dim.as_ref().clone())),
        _ => ty(RTk::Any),
    }
}

/// The canonical text of a float in a document (§10.4): the shortest round trip,
/// a `.0` on a whole number, JavaScript's exponent form.
pub fn fmt_f(n: f64) -> String {
    let s = js_num_str(n);
    if s.contains('.') || s.contains('e') || s.contains('E') {
        s
    } else {
        format!("{s}.0")
    }
}

/// Where the serializer's text goes: a `String` keeps all of it, [`Pieces`]
/// hands what is complete to a writer as it grows.
trait Emit {
    fn text(&mut self) -> &mut String;
    /// A container's entry is complete. All text is final here: a value that
    /// writes anything is never rolled back, and every enclosing container has
    /// written its opening bracket.
    fn entry_done(&mut self);
}

impl Emit for String {
    #[inline(always)]
    fn text(&mut self) -> &mut String {
        self
    }
    #[inline(always)]
    fn entry_done(&mut self) {}
}

/// Serialized text drained to a writer whenever a piece of it is complete.
/// The first write error is kept and the rest of the text discarded.
struct Pieces<'a> {
    text: String,
    to: &'a mut dyn std::io::Write,
    failed: Option<std::io::Error>,
}

impl<'a> Pieces<'a> {
    const PIECE: usize = 256 * 1024;

    fn new(to: &'a mut dyn std::io::Write) -> Self {
        Self {
            text: String::with_capacity(Self::PIECE + Self::PIECE / 4),
            to,
            failed: None,
        }
    }
    fn drain(&mut self) {
        if self.failed.is_none() {
            self.failed = self.to.write_all(self.text.as_bytes()).err();
        }
        self.text.clear();
    }
    fn finish(mut self) -> std::io::Result<()> {
        self.drain();
        self.failed.map_or(Ok(()), Err)
    }
}

impl Emit for Pieces<'_> {
    fn text(&mut self) -> &mut String {
        &mut self.text
    }
    fn entry_done(&mut self) {
        if self.text.len() >= Self::PIECE {
            self.drain();
        }
    }
}

/// The names a record was supplied with, asked once per member while the
/// record is emitted. A short list is scanned; only a long one is indexed, so
/// emitting a record allocates nothing unless it is wide.
struct Supplied<'a> {
    order: &'a [String],
    index: Option<FxHashSet<&'a str>>,
}

impl<'a> Supplied<'a> {
    const SCANNED: usize = 16;

    fn new(order: &'a [String]) -> Self {
        let index =
            (order.len() > Self::SCANNED).then(|| order.iter().map(String::as_str).collect());
        Self { order, index }
    }

    fn has(&self, name: &str) -> bool {
        match &self.index {
            Some(index) => index.contains(name),
            None => self.order.iter().any(|n| n == name),
        }
    }
}

// Whether binding `text` to a map's key type is known to succeed with no
// report, read or owner: `string` accepts any text and a pattern accepts what
// it matches, both by returning the value unchanged. Every other key type, and
// a pattern that does not match, answers false and takes the full bind, which
// reports exactly as before.
fn key_accepts_text(key: &RT, text: &str) -> bool {
    match &key.k {
        RTk::Prim(name) => name == "string",
        RTk::Pattern { re, .. } => re.is_match(text),
        _ => false,
    }
}

impl Engine {
    /// Number of retained unbound-literal materializations (a diagnostic counter).
    pub fn cached_literals(&self) -> usize {
        self.mat_cache.borrow().len()
    }

    /// Diagnostic cache table/root-handle counts; no entry or reachable-graph scan.
    #[cfg(feature = "runtime-diagnostics")]
    pub fn materialization_diagnostics(&self) -> serde_json::Value {
        let cache = self.mat_cache.borrow();
        serde_json::json!({
            "entries": cache.len(), "capacity_entries": cache.capacity(),
            "raw_identity_strength": "weak; allocation address pinned, raw Vec contents not retained by this owner",
            "strong_raw_root_handles": 0,
            "weak_raw_identity_handles": cache.len(),
            "strong_result_root_handles": cache.len(),
            "unique_raw_or_result_nodes": null,
            "meaning": "table-owned handles, not distinct retained nodes/heap bytes; no force, scan, callback or owner clone"
        })
    }

    /// Unbound literals may close over replaced records. Keep their auxiliary
    /// materializations within an edit; retained member values live in slots.
    pub(crate) fn clear_materialized(&self) {
        #[cfg(feature = "runtime-diagnostics")]
        crate::retention_diagnostics::cache_clear(self.mat_cache.borrow().len());
        let retired = std::mem::take(&mut *self.mat_cache.borrow_mut());
        self.materialized_sweep_at.set(MATERIALIZED_SWEEP_MIN);
        drop(retired);
    }

    /// A dead raw allocation cannot be materialized again. Remove its entry
    /// before releasing either identity or result, and run native destructors
    /// only after releasing the cache borrow. Survivors stay strong.
    fn prune_materialized(&self) {
        let mut retired = Vec::new();
        {
            let mut cache = self.mat_cache.borrow_mut();
            cache.retain(|_, (raw, result)| {
                if raw.alive() {
                    true
                } else {
                    retired.push(std::mem::replace(result, Value::Undef));
                    false
                }
            });
            let live = cache.len().max(MATERIALIZED_SWEEP_MIN);
            // retain scans capacity. Avoid repeatedly scanning a once-large
            // table after most raw owners expire, without shrinking on every
            // sweep or retaining an unbounded scratch buffer.
            if cache.capacity() > live.saturating_mul(4) {
                cache.shrink_to(live);
            }
            self.materialized_sweep_at
                .set(cache.len().saturating_mul(2).max(MATERIALIZED_SWEEP_MIN));
        }
        drop(retired);
    }

    /// Request syntax and literal materializations live only for that request.
    pub(crate) fn transient<T>(&self, f: impl FnOnce() -> T) -> T {
        struct Restore<'a> {
            engine: &'a Engine,
            programs: Option<Rc<Programs>>,
            materialized: MaterializedCache,
            materialized_sweep_at: usize,
        }
        impl Drop for Restore<'_> {
            fn drop(&mut self) {
                *self.engine.programs.borrow_mut() = self.programs.take();
                #[cfg(feature = "runtime-diagnostics")]
                crate::retention_diagnostics::cache_restore(
                    self.engine.mat_cache.borrow().len(),
                    self.materialized.len(),
                );
                let retired = std::mem::replace(
                    &mut *self.engine.mat_cache.borrow_mut(),
                    std::mem::take(&mut self.materialized),
                );
                self.engine
                    .materialized_sweep_at
                    .set(self.materialized_sweep_at);
                drop(retired);
            }
        }
        let programs = self.programs.borrow_mut().take();
        if programs.is_some() {
            *self.programs.borrow_mut() = Some(Rc::new(Programs::default()));
        }
        #[cfg(feature = "runtime-diagnostics")]
        crate::retention_diagnostics::cache_suspend(self.mat_cache.borrow().len());
        let _restore = Restore {
            engine: self,
            programs,
            materialized: std::mem::take(&mut *self.mat_cache.borrow_mut()),
            materialized_sweep_at: self.materialized_sweep_at.replace(MATERIALIZED_SWEEP_MIN),
        };
        f()
    }

    /// how many rounds a universe may take to settle (§7.6)
    pub const ROUNDS: u32 = 8;
    /// an engine without registering itself as the environment's evaluator
    pub fn bare(env: Rc<Env>) -> Rc<Engine> {
        Self::bare_with_queries(env, Rc::new(QueryPool::default()))
    }
    pub(crate) fn bare_with_queries(env: Rc<Env>, query_keys: Rc<QueryPool>) -> Rc<Engine> {
        let eng = Rc::new(Engine {
            _lifetime: lifetime::EngineGuard::new(),
            env: env.clone(),
            deferred_slots: RefCell::new(vec![]),
            no_reg: Cell::new(0),
            phase: Cell::new(1),
            failed_inputs: RefCell::new(HashSet::new()),
            reads: RefCell::new(FxHashMap::default()),
            track: Cell::new(false),
            computing: RefCell::new(vec![]),
            slots_by_key: RefCell::new(FxHashMap::default()),
            query_keys,
            deferred_roots: RefCell::new(vec![]),
            prev: RefCell::new(None),
            frozen_roots: RefCell::new(None),
            frozen_registry: RefCell::new(None),
            frozen_set: RefCell::new(FxHashSet::default()),
            frozen_index: RefCell::new(None),
            settled: Cell::new(false),
            snap: RefCell::new(None),
            queried: RefCell::new(BTreeSet::new()),
            ref_index: RefCell::new(FxHashMap::default()),
            computing_edges: RefCell::new(HashSet::new()),
            edge_bases: RefCell::new(vec![]),
            const_envs: RefCell::new(vec![]),
            snap_refs: RefCell::new(FxHashMap::default()),
            mat_cache: RefCell::new(FxHashMap::default()),
            materialized_sweep_at: Cell::new(MATERIALIZED_SWEEP_MIN),
            path_pool: RefCell::new(PrefixPathPool::default()),
            map_shapes: RefCell::new(MapShapePool::default()),
            programs: RefCell::new(None),
            revisions: RefCell::new(None),
            edits: RefCell::new(None),
            verifying_depth: Cell::new(None),
            round_cache: RefCell::new(None),
            round_roots: RefCell::new(None),
            round_resets: RefCell::new(Vec::new()),
            round_refs: RefCell::new(FxHashMap::default()),
            inverse_refs: RefCell::new(FxHashMap::default()),
        });
        let w = Rc::downgrade(&eng);
        *env.tagger.borrow_mut() = Some(Rc::new(move || {
            w.upgrade()
                .and_then(|e| e.computing.borrow().last().map(ToString::to_string))
        }));
        eng
    }
    /// Retain an immutable container path, sharing prefixes within this engine.
    /// The returned outer Rc is new even when its full prefix chain is shared.
    pub fn retained_path(&self, segments: &[Seg]) -> Rc<PrefixPath> {
        self.path_pool.borrow_mut().retain(segments)
    }

    /// Retain an inline container path, sharing immutable prefix nodes.
    /// Use this for `ArrV::path` and `MapV::path`; no outer Rc is allocated.
    pub fn container_path(&self, segments: &[Seg]) -> PrefixPath {
        self.path_pool.borrow_mut().retain_value(segments)
    }
    /// Explicit diagnostic scan of the bounded path pool, outside hot binding.
    pub fn retained_path_pool_stats(&self) -> PrefixPathPoolStats {
        self.path_pool.borrow().stats()
    }
    pub(crate) fn query_pool(&self) -> Rc<QueryPool> {
        self.query_keys.clone()
    }
    pub(crate) fn query_id(&self, key: &str) -> QueryId {
        self.query_keys.intern(key)
    }
    /// Find an indexed member by its textual query key.
    ///
    /// The returned instance is a shared live handle, not a copied record.
    /// Retaining it retains that value; the query index itself is not exposed.
    pub fn query_slot(&self, key: &str) -> Option<(Inst, String)> {
        let id = self.query_keys.lookup(key)?;
        self.query_slot_id(&id)
            .map(|(inst, name)| (inst, name.to_string()))
    }
    pub(crate) fn query_slot_shared(&self, key: &str) -> Option<(Inst, Rc<str>)> {
        let id = self.query_keys.lookup(key)?;
        self.query_slot_id(&id)
    }
    pub(crate) fn query_slot_id(&self, key: &QueryId) -> Option<(Inst, Rc<str>)> {
        self.slots_by_key.borrow().get(key).cloned()
    }
    pub(crate) fn register_query_slot(&self, key: &str, inst: Inst, member: Rc<str>) {
        self.register_query_slot_id(self.query_id(key), inst, member);
    }
    pub(crate) fn register_query_slot_id(&self, key: QueryId, inst: Inst, member: Rc<str>) {
        self.slots_by_key.borrow_mut().insert(key, (inst, member));
    }
    pub(crate) fn remove_query_slot(&self, key: &str) {
        if let Some(id) = self.query_keys.lookup(key) {
            self.slots_by_key.borrow_mut().remove(&id);
        }
    }
    pub(crate) fn query_reads(&self, key: &str) -> Option<ReadSet> {
        let id = self.query_keys.lookup(key)?;
        self.query_reads_id(&id)
    }
    pub(crate) fn query_reads_id(&self, key: &QueryId) -> Option<ReadSet> {
        self.reads.borrow().get(key).cloned()
    }
    pub(crate) fn replace_query_reads(&self, key: &str, reads: ReadSet) {
        let id = self.query_id(key);
        self.replace_query_reads_id(&id, reads);
    }
    // Writers pass an identity obtained from this Engine's evaluation lineage.
    pub(crate) fn replace_query_reads_id(&self, key: &QueryId, reads: ReadSet) {
        self.reads.borrow_mut().insert(key.clone(), reads);
    }
    pub(crate) fn remove_query_reads(&self, key: &str) {
        if let Some(id) = self.query_keys.lookup(key) {
            self.reads.borrow_mut().remove(&id);
        }
    }
    pub(crate) fn sweep_query_ids(&self) {
        self.query_keys.sweep();
    }
    pub(crate) fn maintain_query_ids(&self) {
        self.query_keys.maintain_transient();
    }
    /// Number of computations with a retained read set, including empty sets.
    pub fn dependency_queries(&self) -> usize {
        self.reads.borrow().len()
    }
    /// Number of registered member slots in the query index.
    pub fn indexed_slots(&self) -> usize {
        self.slots_by_key.borrow().len()
    }
    /// Export one computation's sorted dependencies without copying other owners.
    ///
    /// An absent owner returns `None`; a retained empty read set returns
    /// `Some(Vec::new())`. Changing the owned result does not change the graph.
    pub fn query_dependencies_for(&self, key: &str) -> Option<Vec<String>> {
        let deps = self.query_reads(key)?;
        let mut dependencies: Vec<_> = deps.iter().map(ToString::to_string).collect();
        dependencies.sort();
        Some(dependencies)
    }
    /// Export active computation keys, outermost first and innermost last.
    ///
    /// The owned snapshot preserves order and does not retain the live stack.
    pub fn query_stack(&self) -> Vec<String> {
        self.computing
            .borrow()
            .iter()
            .map(ToString::to_string)
            .collect()
    }
    /// Export a sorted textual dependency graph for explicit inspection.
    ///
    /// The returned owned snapshot does not mutate or retain the live graph.
    /// An owner with an empty list is distinct from an absent owner.
    pub fn query_dependencies(&self) -> Vec<(String, Vec<String>)> {
        let mut rows: Vec<_> = self
            .reads
            .borrow()
            .iter()
            .map(|(owner, deps)| {
                let mut dependencies: Vec<_> = deps.iter().map(ToString::to_string).collect();
                dependencies.sort();
                (owner.to_string(), dependencies)
            })
            .collect();
        rows.sort_by(|a, b| a.0.cmp(&b.0));
        rows
    }
    /// Export the sorted logical keys of registered slots for inspection.
    pub fn query_slot_keys(&self) -> Vec<String> {
        let mut keys: Vec<_> = self
            .slots_by_key
            .borrow()
            .keys()
            .map(ToString::to_string)
            .collect();
        keys.sort();
        keys
    }
    /// Inspect query representation storage without copying graph text.
    ///
    /// Pool counts cover the shared evaluation lineage, including identities
    /// held by old runs or snapshots. Read-set and index counts cover this
    /// engine. Capacities are usable entries and payload sizes exclude allocator
    /// metadata; these counters are not process RSS. This method does not prune.
    pub fn query_storage(&self) -> BTreeMap<&'static str, usize> {
        let pool = self.query_keys.census();
        let reads = self.reads.borrow();
        let slots = self.slots_by_key.borrow();
        let mut bodies = FxHashSet::default();
        let mut unique_edges = 0;
        let mut unique_capacity = 0;
        let mut shared_bodies = 0;
        let mut retained_handles = 0;
        for deps in reads.values() {
            if let Some(body) = deps.storage() {
                if bodies.insert(body.identity) {
                    unique_edges += body.len;
                    unique_capacity += body.capacity;
                    shared_bodies += usize::from(body.strong_count > 1);
                    retained_handles += body.strong_count;
                }
            }
        }
        BTreeMap::from([
            ("pool_entries", pool.entries),
            ("pool_live", pool.live),
            ("pool_dead", pool.dead),
            ("pool_text_bytes", pool.text_bytes),
            ("pool_live_text_bytes", pool.live_text_bytes),
            ("pool_dead_text_bytes", pool.dead_text_bytes),
            ("pool_capacity", pool.capacity),
            ("scratch_index_entries", pool.scratch_index_entries),
            ("scratch_index_capacity", pool.scratch_index_capacity),
            ("scratch_index_entry_bytes", pool.scratch_index_entry_bytes),
            ("query_id_bytes", pool.query_id_bytes),
            ("query_key_bytes", pool.query_key_bytes),
            ("text_handle_bytes", pool.text_handle_bytes),
            ("weak_key_bytes", pool.weak_key_bytes),
            ("pool_entry_bytes", pool.interner_entry_bytes),
            ("read_set_bytes", pool.read_set_bytes),
            ("dependency_set_bytes", pool.dependency_set_bytes),
            ("rc_header_bytes", pool.rc_header_bytes),
            ("read_queries", reads.len()),
            ("read_capacity", reads.capacity()),
            (
                "read_entry_bytes",
                std::mem::size_of::<(QueryId, ReadSet)>(),
            ),
            (
                "read_empty",
                reads.values().filter(|deps| deps.is_empty()).count(),
            ),
            ("read_logical_edges", reads.values().map(ReadSet::len).sum()),
            (
                "read_logical_text_bytes",
                reads
                    .values()
                    .flat_map(|deps| deps.iter())
                    .map(|id| id.len())
                    .sum(),
            ),
            ("read_unique_bodies", bodies.len()),
            ("read_unique_edges", unique_edges),
            ("read_unique_capacity", unique_capacity),
            ("read_shared_bodies", shared_bodies),
            ("read_body_strong_handles", retained_handles),
            ("indexed_slots", slots.len()),
            ("slot_index_capacity", slots.capacity()),
            (
                "slot_index_entry_bytes",
                std::mem::size_of::<(QueryId, (Inst, Rc<str>))>(),
            ),
            ("computing_depth", self.computing.borrow().len()),
        ])
    }
    /// The root's value as this engine's expressions read it: its own universe once frozen.
    pub fn root(&self, name: &str) -> Option<Value> {
        if let Some(roots) = self.frozen_roots.borrow().as_ref() {
            return roots
                .iter()
                .find(|(n, _)| n == name)
                .map(|(_, v)| v.clone());
        }
        self.env.root(name)
    }
    /// The key of a slot in the dependency graph: the instance's path and the member's name.
    pub fn slot_key(inst: &Inst, name: &str) -> String {
        // inst.path is immutable, so path_str is computed once per instance (F21)
        let b = inst.borrow();
        if b.ps.borrow().is_none() {
            let p = path_str(&b.path, None);
            *b.ps.borrow_mut() = Some(p);
        }
        let ps = b.ps.borrow();
        format!("{}.{name}", ps.as_ref().unwrap())
    }
    /// Record that the computation in progress read a slot (dependency tracking).
    pub fn record(&self, read: String) {
        if !self.track.get()
            || self
                .verifying_depth
                .get()
                .is_some_and(|d| self.computing.borrow().len() <= d)
        {
            return;
        }
        let computing = self.computing.borrow();
        if let Some(top) = computing.last() {
            let dependency = self.query_id(&read);
            self.reads
                .borrow_mut()
                .entry(top.clone())
                .or_default()
                .insert(dependency);
        }
    }
    // An actual tracked force can pass its parent's recorded identity on to
    // producer setup. Cached reads keep record's move-only insertion path.
    fn record_query(&self, read: &str) -> Option<QueryId> {
        if !self.track.get()
            || self
                .verifying_depth
                .get()
                .is_some_and(|d| self.computing.borrow().len() <= d)
        {
            return None;
        }
        let computing = self.computing.borrow();
        let top = computing.last()?;
        let dependency = self.query_id(read);
        self.reads
            .borrow_mut()
            .entry(top.clone())
            .or_default()
            .insert(dependency.clone());
        Some(dependency)
    }
    pub(crate) fn verify_reads<T>(&self, f: impl FnOnce() -> T) -> T {
        let previous = self
            .verifying_depth
            .replace(Some(self.computing.borrow().len()));
        let result = f();
        self.verifying_depth.set(previous);
        result
    }
    /// Run a computation as a step of the dependency graph, its reads recorded under `key`.
    pub fn step<T>(&self, key: &str, f: impl FnOnce() -> T) -> T {
        self.step_id(self.query_id(key), f)
    }
    pub(crate) fn step_id<T>(&self, id: QueryId, f: impl FnOnce() -> T) -> T {
        self.computing.borrow_mut().push(id.clone());
        if self.track.get() {
            if self.round_cache.borrow().is_some() {
                self.reads.borrow_mut().remove(&id);
            } else {
                self.reads.borrow_mut().insert(id, ReadSet::default());
            }
        }
        let r = f();
        self.computing.borrow_mut().pop();
        r
    }
    /// The evaluation phase: 1 while the roots bind, 2 while the deferred slots force (§9.3).
    pub fn phase(&self) -> u8 {
        self.phase.get()
    }
    /// An engine over an environment, wired in as its constant and expression evaluator.
    pub fn new(env: Rc<Env>) -> Rc<Engine> {
        let eng = Self::bare(env.clone());
        eng.install_hooks(&env, false);
        eng
    }
    /// §4.13 / unit factors: let the environment evaluate constants through this engine
    pub fn install_hooks(self: &Rc<Self>, env: &Rc<Env>, with_menv: bool) {
        let w = Rc::downgrade(self);
        let we: Weak<Env> = Rc::downgrade(env);
        *env.const_eval.borrow_mut() =
            Some(Rc::new(move |n: &str| match (w.upgrade(), we.upgrade()) {
                (Some(eng), Some(e)) => eng.force_const_in(&e, n, ""),
                _ => Ok(Value::Null),
            }));
        let w2 = Rc::downgrade(self);
        let we2: Weak<Env> = Rc::downgrade(env);
        *env.expr_eval.borrow_mut() = Some(Rc::new(move |x: &Rc<Expr>| match w2.upgrade() {
            Some(eng) => eng.ev(
                x,
                &Scope::new("", if with_menv { we2.upgrade() } else { None }),
            ),
            None => Ok(Value::Null),
        }));
    }

    // ---------- expression evaluation ----------
    /// Evaluate an expression in a scope (§4, §9).
    pub fn ev(&self, e: &Rc<Expr>, sc: &Scope) -> R<Value> {
        if let Expr::Lit(v) = &**e {
            return Ok(v.clone());
        }
        let programs = self.programs.borrow().clone();
        if let Some(p) = programs {
            return p.get(e)(self, sc);
        }
        match &**e {
            Expr::Lit(v) => Ok(v.clone()),
            Expr::Pattern(s) => Ok(Value::pattern(s.as_str())),
            Expr::UnitLit { num, unit } => {
                let (key, to_base) = self.env.unit_info(unit).or_else(err)?;
                Ok(Value::quantity(key, num * to_base))
            }
            Expr::Paren(x) => self.ev(x, sc),
            Expr::MapComp { key, val, clauses } => {
                let mut entries = vec![];
                let mut seen = KeysSeen::default();
                self.map_comp(
                    key,
                    val,
                    clauses,
                    0,
                    sc.locals.clone(),
                    sc,
                    &mut entries,
                    &mut seen,
                )?;
                Ok(Value::PreObj(Rc::new(entries)))
            }
            Expr::Template(parts) => Ok(Value::Str(self.render(parts, sc)?.into())),
            Expr::Name(name) => self.name_value(name, sc),
            Expr::Ctx(n) => self.context_value(n, sc),
            Expr::Referrers { ty, member } => self.referrers(ty, member, sc),
            Expr::Spread(_) => err("spread outside an object literal"),
            Expr::Obj(entries) => Ok(Value::PreObj(Rc::new(
                entries
                    .iter()
                    .map(|(k, v)| {
                        (
                            k.clone(),
                            Value::PreVal(Rc::new(PreValV {
                                expr: {
                                    #[cfg(feature = "runtime-diagnostics")]
                                    crate::retention_diagnostics::preval(0);
                                    v.clone()
                                },
                                scope: sc.clone(),
                            })),
                        )
                    })
                    .collect(),
            ))),
            Expr::Arr(items) => Ok(Value::PreArr(Rc::new(
                items
                    .iter()
                    .map(|(sp, v)| {
                        (
                            *sp,
                            Value::PreVal(Rc::new(PreValV {
                                expr: {
                                    #[cfg(feature = "runtime-diagnostics")]
                                    crate::retention_diagnostics::preval(1);
                                    v.clone()
                                },
                                scope: sc.clone(),
                            })),
                        )
                    })
                    .collect(),
            ))),
            Expr::Comp { head, clauses } => {
                #[cfg(feature = "runtime-diagnostics")]
                let mut attempt =
                    expr_diag::Attempt::begin(expr_diag::selected(e, false), self.phase.get());
                let evaluate = || {
                    let mut items = vec![];
                    self.comp(
                        head,
                        clauses,
                        0,
                        sc.locals.clone(),
                        sc,
                        &mut items,
                        #[cfg(feature = "runtime-diagnostics")]
                        attempt.handle(),
                    )?;
                    Ok(Value::PreArr(Rc::new(items)))
                };
                let result = evaluate();
                #[cfg(feature = "runtime-diagnostics")]
                attempt.finish(&result);
                result
            }
            Expr::If { c, t, f } => {
                if self.truthy(&self.ev(c, sc)?)? {
                    self.ev(t, sc)
                } else {
                    self.ev(f, sc)
                }
            }
            Expr::Match { subject, arms } => {
                let subj = self.deref(self.ev(subject, sc)?)?;
                let run = |arm: &MatchArm| {
                    let l2 = sc.locals.with(Rc::from(arm.v.as_str()), subj.clone());
                    self.ev(&arm.body, &sc.with_locals(l2))
                };
                let mut catch_all = None;
                for arm in arms {
                    let Some(t) = &arm.ty else {
                        catch_all = Some(arm);
                        continue;
                    };
                    let menv = sc.menv.clone().unwrap_or_else(|| self.env.clone());
                    let rt = menv.resolve(t, None).or_else(err)?;
                    if self.member_of(&subj, &rt, sc) {
                        return run(arm);
                    }
                }
                if let Some(arm) = catch_all {
                    return run(arm);
                }
                err("match: no arm matched")
            }
            Expr::Lambda { params, body } => Ok(Value::Clo(Rc::new(Closure {
                params: params.clone(),
                body: body.clone(),
                scope: sc.clone(),
            }))),
            Expr::Un { op, x } => {
                let x = self.ev(x, sc)?;
                match op.as_str() {
                    "!" => Ok(Value::Bool(!self.truthy(&x)?)),
                    "-" => match x {
                        Value::Absent => err("absent consumed"),
                        Value::Q(mut q) => {
                            q.value = -q.value;
                            Ok(Value::Q(q))
                        }
                        Value::Int(i) => Ok(Value::Int(-i)),
                        Value::Float(f) => Ok(Value::Float(-f)),
                        _ => err("bad operand for unary -"),
                    },
                    "~" => match x {
                        Value::Int(i) => Ok(Value::Int(&(-i) - 1)),
                        _ => err("bad operand for ~"),
                    },
                    _ => err("un"),
                }
            }
            Expr::Bin { op, l, r } => {
                if op == "|>" {
                    let call = match &**r {
                        Expr::Call { fun, args } => {
                            let mut a = vec![l.clone()];
                            a.extend(args.iter().cloned());
                            Expr::Call {
                                fun: fun.clone(),
                                args: a,
                            }
                        }
                        _ => Expr::Call {
                            fun: r.clone(),
                            args: vec![l.clone()],
                        },
                    };
                    return self.ev(&Rc::new(call), sc);
                }
                self.binop(op, l, r, sc)
            }
            Expr::Member { x, name, safe } => {
                let x0 = self.ev(x, sc)?;
                if let Value::NsRef(ns) = &x0 {
                    return self.ns_value(ns, name, sc);
                }
                if *safe && matches!(x0, Value::Null | Value::Absent) {
                    return Ok(Value::Absent);
                }
                let d = self.deref(x0)?;
                self.access(&d, name)
            }
            Expr::Index { x, i } => {
                // a literal (or document) operand is materialized before it is indexed
                let x = self.mat_val(self.ev(x, sc)?)?;
                let i = self.ev(i, sc)?;
                match &x {
                    Value::Arr(a) => {
                        let n = to_index(&i)?;
                        let a = a.borrow();
                        if n < 0 || n as usize >= a.items.len() {
                            return err_code(format!("index {n} out of bounds"), "E5005");
                        }
                        Ok(a.items[n as usize].clone())
                    }
                    Value::Map(m) => match &i {
                        Value::Str(k) => Ok(m.borrow().get(k).cloned().unwrap_or(Value::Absent)),
                        _ => Ok(Value::Absent),
                    },
                    Value::Rec(_) => match &i {
                        Value::Str(k) => self.access(&x, k),
                        _ => err("index on record needs a string"),
                    },
                    _ => err("index on non-collection"),
                }
            }
            Expr::Call { fun, args } => {
                let mut a = Vec::with_capacity(args.len());
                for x in args {
                    a.push(self.ev(x, sc)?);
                }
                let f = self.ev_callee(fun, sc)?;
                self.call(&f, a, sc)
            }
            Expr::With { base, patch } => self.with_expr(base, patch, sc),
        }
    }

    pub(crate) fn name_value(&self, name: &str, sc: &Scope) -> R<Value> {
        if let Some(v) = sc.locals.get(name) {
            return Ok(v.clone());
        }
        if let Some(inst) = &sc.inst {
            if let Some(v) = self.slot_lookup(inst, name)? {
                return Ok(v);
            }
        }
        let menv = sc.menv.clone().unwrap_or_else(|| self.env.clone());
        if let Some(v) = self.module_value(&menv, name, &sc.root_name)? {
            return Ok(v);
        }
        if name == "std" {
            return Ok(Value::Std(Rc::new(vec![])));
        }
        if let Some(v) = self.root(name) {
            self.record(format!("root:{name}"));
            return Ok(v);
        }
        if let Some(v) = self.demand_input(&menv, name)? {
            return Ok(v);
        }
        err(format!("unknown name {name}"))
    }

    pub(crate) fn context_value(&self, n: &str, sc: &Scope) -> R<Value> {
        // $this / $parent / $root are references (§7.3): each denotes an
        // instance that contains the current one, so a value reading would
        // be a self-containing value; $key and $path are plain values
        let inst = sc.inst.as_ref();
        match n {
            "$this" => match inst {
                Some(i) => Ok(Value::Ref(i.borrow().path.clone())),
                None => err_code("$this outside a record instance", "E4090"),
            },
            "$parent" => match inst.and_then(|i| i.borrow().parent.clone()) {
                Some(p) => Ok(Value::Ref(p.borrow().path.clone())),
                None => err_code("$parent: the evaluation root has no owner", "E4090"),
            },
            "$root" => {
                if sc.root_name.is_empty() || self.root(&sc.root_name).is_none() {
                    return err_code("$root outside an evaluation root", "E4090");
                }
                Ok(Value::Ref(Rc::new(vec![Seg::Name(sc.root_name.clone())])))
            }
            "$key" => {
                // the key or index under which $this sits in its parent's
                // collection: the last path segment, present only when the
                // instance is a collection element (not a direct member)
                let Some(i) = inst else {
                    return err_code("$key: the instance is not a collection element", "E4090");
                };
                let b = i.borrow();
                let Some(parent) = &b.parent else {
                    return err_code("$key: the instance is not a collection element", "E4090");
                };
                if b.path.len() < parent.borrow().path.len() + 2 {
                    return err_code("$key: the instance is not a collection element", "E4090");
                }
                Ok(match b.path.last() {
                    Some(Seg::Idx(k)) => Value::Int(Num::from(*k)),
                    Some(Seg::Name(k)) | Some(Seg::Key(k)) => {
                        Value::Str(SharedText::from_rc(k.clone()))
                    }
                    None => Value::Absent,
                })
            }
            "$path" => match inst {
                Some(i) => Ok(Value::Str(path_str(&i.borrow().path, None).into())),
                None => err_code("$path outside a record instance", "E4090"),
            },
            _ => err(format!("unsupported context var {n}")),
        }
    }

    fn render(&self, parts: &[TPart], sc: &Scope) -> R<String> {
        let mut s = String::new();
        for p in parts {
            match p {
                TPart::Text(t) => s.push_str(t),
                TPart::Expr(x) => s.push_str(&self.to_str(&self.ev(x, sc)?)?),
            }
        }
        Ok(s)
    }

    fn comp(
        &self,
        head: &Rc<Expr>,
        clauses: &[ForClause],
        ci: usize,
        locals: Locals,
        sc: &Scope,
        out: &mut Vec<(bool, Value)>,
        #[cfg(feature = "runtime-diagnostics")] trace: Option<expr_diag::Handle>,
    ) -> R<()> {
        if ci == clauses.len() {
            out.push((
                false,
                Value::PreVal(Rc::new(PreValV {
                    expr: {
                        #[cfg(feature = "runtime-diagnostics")]
                        crate::retention_diagnostics::preval(2);
                        head.clone()
                    },
                    scope: sc.with_locals(locals),
                })),
            ));
            #[cfg(feature = "runtime-diagnostics")]
            expr_diag::emitted(trace);
            return Ok(());
        }
        let cl = &clauses[ci];
        #[cfg(feature = "runtime-diagnostics")]
        expr_diag::clause(trace, ci, 0);
        let it = self.ev(&cl.iter, &sc.with_locals(locals.clone()))?;
        for el in self.iterate(&it)? {
            #[cfg(feature = "runtime-diagnostics")]
            expr_diag::clause(trace, ci, 1);
            let l2 = locals.with(Rc::from(cl.v.as_str()), el);
            let sc2 = sc.with_locals(l2.clone());
            let mut ok = true;
            for f in &cl.filters {
                #[cfg(feature = "runtime-diagnostics")]
                expr_diag::clause(trace, ci, 2);
                if !self.truthy(&self.ev(f, &sc2)?)? {
                    #[cfg(feature = "runtime-diagnostics")]
                    expr_diag::clause(trace, ci, 3);
                    ok = false;
                    break;
                }
            }
            if ok {
                #[cfg(feature = "runtime-diagnostics")]
                expr_diag::clause(trace, ci, 4);
                self.comp(
                    head,
                    clauses,
                    ci + 1,
                    l2,
                    sc,
                    out,
                    #[cfg(feature = "runtime-diagnostics")]
                    trace,
                )?;
            }
        }
        Ok(())
    }

    fn map_comp(
        &self,
        key: &Rc<Expr>,
        val: &Rc<Expr>,
        clauses: &[ForClause],
        ci: usize,
        locals: Locals,
        sc: &Scope,
        out: &mut Vec<(String, Value)>,
        seen: &mut KeysSeen,
    ) -> R<()> {
        if ci == clauses.len() {
            let sc2 = sc.with_locals(locals);
            let Value::Str(k) = self.ev(key, &sc2)? else {
                return err("map key must be string");
            };
            let k = k.to_string();
            if !seen.admits(out, &k) {
                return err_code(format!("duplicate key {k}"), "E5004");
            }
            let v = self.ev(val, &sc2)?;
            out.push((k, v));
            return Ok(());
        }
        let cl = &clauses[ci];
        let it = self.ev(&cl.iter, &sc.with_locals(locals.clone()))?;
        for el in self.iterate(&it)? {
            let l2 = locals.with(Rc::from(cl.v.as_str()), el);
            let sc2 = sc.with_locals(l2.clone());
            let mut ok = true;
            for f in &cl.filters {
                if !self.truthy(&self.ev(f, &sc2)?)? {
                    ok = false;
                    break;
                }
            }
            if ok {
                self.map_comp(key, val, clauses, ci + 1, l2, sc, out, seen)?;
            }
        }
        Ok(())
    }

    /// Whether a value belongs to a type, as `in` and `match` decide it (§4.9).
    pub fn member_of(&self, v: &Value, rt: &RT, sc: &Scope) -> bool {
        if let Value::Rec(r) = v {
            let vrt = r.borrow().rt.clone();
            return subsumes(&self.env, &vrt, rt);
        }
        let mark = self.env.diag_len();
        self.no_reg.set(self.no_reg.get() + 1);
        let ok = self
            .bind(v.clone(), rt, &[Seg::Name("<match>".into())], None, sc)
            .is_ok();
        self.no_reg.set(self.no_reg.get() - 1);
        self.env.diag_truncate(mark);
        ok
    }

    fn ev_callee(&self, e: &Rc<Expr>, sc: &Scope) -> R<Value> {
        let programs = self.programs.borrow().clone();
        if let Some(p) = programs {
            return p.callee(e)(self, sc);
        }
        if let Expr::Member { x, name, .. } = &**e {
            let x = self.ev_callee(x, sc)?;
            return match &x {
                Value::Std(p) => {
                    let mut p2 = (**p).clone();
                    p2.push(name.clone());
                    Ok(Value::Std(Rc::new(p2)))
                }
                Value::NsRef(ns) => self.ns_value(ns, name, sc),
                _ => {
                    let d = self.deref(x)?;
                    self.access(&d, name)
                }
            };
        }
        self.ev(e, sc)
    }

    pub(crate) fn module_value(
        &self,
        menv: &Rc<Env>,
        name: &str,
        root_name: &str,
    ) -> R<Option<Value>> {
        if menv.consts.borrow().contains_key(name) {
            return Ok(Some(self.force_const_in(menv, name, root_name)?));
        }
        let f = menv.funcs.borrow().get(name).cloned();
        if let Some(f) = f {
            return Ok(Some(Value::Clo(Rc::new(Closure {
                params: f.params.iter().map(|p| p.name.clone()).collect(),
                body: f.body.clone(),
                scope: Scope::new(root_name, Some(menv.clone())),
            }))));
        }
        let im = menv.imports.borrow().get(name).cloned();
        if let Some(im) = im {
            if let Some(v) = self.module_value(&im.env, &im.name, root_name)? {
                return Ok(Some(v));
            }
            if let Some(v) = self.root(&im.name) {
                self.record(format!("root:{}", im.name));
                return Ok(Some(v)); // imported output/input root
            }
            return self.demand_input(&im.env, &im.name);
        }
        let ns = menv.namespaces.borrow().get(name).cloned();
        if let Some((_, exports)) = ns {
            return Ok(Some(Value::NsRef(Rc::new(NsRefV { exports }))));
        }
        Ok(None)
    }

    pub(crate) fn ns_value(&self, ns: &NsRefV, name: &str, sc: &Scope) -> R<Value> {
        let ex = ns.exports.borrow().get(name).cloned();
        let Some(ex) = ex else {
            return err(format!("namespace has no export {name}"));
        };
        if let Some(v) = self.module_value(&ex.env, &ex.name, &sc.root_name)? {
            return Ok(v);
        }
        if let Some(v) = self.root(&ex.name) {
            self.record(format!("root:{}", ex.name));
            return Ok(v);
        }
        if let Some(v) = self.demand_input(&ex.env, &ex.name)? {
            return Ok(v);
        }
        err(format!("{name} is not a value"))
    }
    // an input demanded by evaluation (§5.6, §9.4): the bound document if
    // the tool bound one, else its fallback — bound on first demand and
    // memoized as a root; a fallback-less unbound input is E5006 at the
    // demanding path. Returns None when `name` is not an input.
    /// An input read by an output: the bound document, its fallback, or none (§5.6, §9.4).
    pub fn demand_input(&self, menv: &Rc<Env>, name: &str) -> R<Option<Value>> {
        let decl = menv.inputs.borrow().get(name).cloned();
        let Some((ty_ast, fallback)) = decl else {
            return Ok(None);
        };
        self.record(format!("root:{name}"));
        if let Some(v) = self.root(name) {
            return Ok(Some(v));
        }
        if self.failed_inputs.borrow().contains(name) {
            return Err(Fail::Taint);
        }
        let Some(fallback) = fallback else {
            return err_code(format!("input {name} is not bound"), "E5006");
        };
        let sc = Scope::new(name, Some(menv.clone()));
        let produce = || -> R<Value> {
            let v = self.ev(&fallback, &sc)?;
            let rt = menv.resolve(&ty_ast, None).or_else(err)?;
            self.bind(v, &rt, &[Seg::Name(Rc::from(name))], None, &sc)
        };
        let bound = self.step(&format!("root:{name}"), || {
            match self.edits.borrow().as_ref() {
                Some(edits) => edits.root(self, name, &RootSrc::Expr(&fallback), produce),
                None => produce(),
            }
        });
        match bound {
            Ok(v) => {
                self.env.set_root(name, v.clone());
                Ok(Some(v))
            }
            Err(e) => {
                if matches!(e, Fail::Taint) {
                    self.failed_inputs.borrow_mut().insert(name.to_string());
                }
                Err(e)
            }
        }
    }
    // bind an evaluation root (an output's expression, or an input's
    // document / fallback): a failing root is reported at its own path and
    // left unset — its demanders are tainted, nothing else is
    /// Bind a root — an output's expression or an input's document — to its declared type (§9.2).
    /// Whether this root needs binding in the retained round.
    pub fn should_bind_root(&self, name: &str) -> bool {
        self.round_roots
            .borrow()
            .as_ref()
            .is_none_or(|roots| roots.contains(name))
    }
    /// Bind a root, retaining its source when it must defer to phase two.
    pub fn bind_root(&self, name: &str, src: RootSrc, rt: &RT, sc: &Scope) {
        #[cfg(feature = "runtime-diagnostics")]
        use crate::root_binding_diagnostics::{Completion, Outcome, RootAttempt, SourceKind};
        // Declare diagnostic guards before runtime locals; their final boundary
        // includes local releases without extending any source/value lifetime.
        #[cfg(feature = "runtime-diagnostics")]
        let root_diagnostic = RootAttempt::new(
            name,
            self.phase.get(),
            match &src {
                RootSrc::Expr(_) => SourceKind::Expr,
                RootSrc::Doc(_) => SourceKind::Doc,
            },
        );
        if !self.should_bind_root(name) {
            #[cfg(feature = "runtime-diagnostics")]
            root_diagnostic.skipped();
            return;
        }
        let keep = match &src {
            RootSrc::Expr(e) => OwnedRootSrc::Expr((*e).clone()),
            RootSrc::Doc(v) => OwnedRootSrc::Doc(v.clone()),
        };
        let produce = || -> R<Value> {
            #[cfg(feature = "runtime-diagnostics")]
            root_diagnostic.source_started();
            let raw = match &src {
                RootSrc::Expr(e) => self.ev(e, sc)?,
                RootSrc::Doc(v) => v.clone(),
            };
            #[cfg(feature = "runtime-diagnostics")]
            root_diagnostic.source_evaluated();
            let result = self.bind(raw, rt, &[Seg::Name(Rc::from(name))], None, sc);
            #[cfg(feature = "runtime-diagnostics")]
            root_diagnostic.binding_returned();
            result
        };
        let bound = self.step(&format!("root:{name}"), || {
            match self.edits.borrow().as_ref() {
                Some(edits) => edits.root(self, name, &src, produce),
                None => produce(),
            }
        });
        #[cfg(feature = "runtime-diagnostics")]
        root_diagnostic.dispatch_returned(match &bound {
            Ok(_) => Outcome::Bound,
            Err(Fail::Defer) => Outcome::Defer,
            Err(Fail::Eval(_)) => Outcome::EvalError,
            Err(Fail::Taint) => Outcome::Taint,
        });
        match bound {
            Ok(v) => {
                self.env.set_root(name, v);
                #[cfg(feature = "runtime-diagnostics")]
                root_diagnostic.body_returned(Completion::Published);
            }
            Err(Fail::Eval(e)) => {
                self.env.report(Diag {
                    severity: "error".into(),
                    id: None,
                    message: e.msg,
                    path: name.to_string(),
                    code: e.code,
                    loc: None,
                    by: None,
                });
                #[cfg(feature = "runtime-diagnostics")]
                root_diagnostic.body_returned(Completion::EvalError);
            }
            Err(Fail::Defer) => {
                if self.phase.get() < 2 {
                    self.deferred_roots.borrow_mut().push(DeferredRoot {
                        name: name.to_string(),
                        src: keep,
                        rt: rt.clone(),
                        sc: sc.clone(),
                    });
                    #[cfg(feature = "runtime-diagnostics")]
                    root_diagnostic.body_returned(Completion::DeferredQueued);
                } else {
                    #[cfg(feature = "runtime-diagnostics")]
                    root_diagnostic.body_returned(Completion::DeferIgnored);
                }
            }
            Err(Fail::Taint) => {
                #[cfg(feature = "runtime-diagnostics")]
                root_diagnostic.body_returned(Completion::Taint);
            }
        }
    }
    /// phase 2: the roots that deferred are bound again (after the deferred slots)
    pub fn bind_deferred_roots(&self) {
        let pending: Vec<DeferredRoot> = self.deferred_roots.borrow_mut().drain(..).collect();
        for d in pending {
            match &d.src {
                OwnedRootSrc::Expr(e) => self.bind_root(&d.name, RootSrc::Expr(e), &d.rt, &d.sc),
                OwnedRootSrc::Doc(v) => {
                    self.bind_root(&d.name, RootSrc::Doc(v.clone()), &d.rt, &d.sc)
                }
            }
        }
    }

    pub(crate) fn q_arith(&self, op: &str, l: &Value, r: &Value) -> R<Value> {
        let dim_or_1 = |d: &str| {
            if d.is_empty() {
                "1".to_string()
            } else {
                d.to_string()
            }
        };
        match op {
            "+" | "-" => {
                let (Value::Q(lq), Value::Q(rq)) = (l, r) else {
                    return err(format!("`{op}` mixes quantity and plain number"));
                };
                let (ld, lv, rd, rv) = (&lq.dim, &lq.value, &rq.dim, &rq.value);
                if ld != rd {
                    return err(format!(
                        "quantity dimension mismatch: {} vs {}",
                        dim_or_1(ld.as_str()),
                        dim_or_1(rd.as_str())
                    ));
                }
                Ok(Value::Q(Box::new(QuantityValue {
                    dim: ld.clone(),
                    value: if op == "+" { lv + rv } else { lv - rv },
                })))
            }
            "<" | "<=" | ">" | ">=" => {
                let (Value::Q(lq), Value::Q(rq)) = (l, r) else {
                    return err("quantity dimension mismatch in comparison");
                };
                let (ld, lv, rd, rv) = (&lq.dim, &lq.value, &rq.dim, &rq.value);
                if ld != rd {
                    return err("quantity dimension mismatch in comparison");
                }
                Ok(Value::Bool(match op {
                    "<" => lv < rv,
                    "<=" => lv <= rv,
                    ">" => lv > rv,
                    _ => lv >= rv,
                }))
            }
            _ => {
                let mag = |v: &Value| -> Option<f64> {
                    match v {
                        Value::Q(q) => Some(q.value),
                        Value::Int(i) => Some(i.to_f64().unwrap_or(f64::INFINITY)),
                        Value::Float(f) => Some(*f),
                        _ => None,
                    }
                };
                let (Some(lm), Some(rm)) = (mag(l), mag(r)) else {
                    return err(format!("bad operands for {op}"));
                };
                if op == "/" && rm == 0.0 {
                    return err_code("division by zero", "E5001");
                }
                let dv = |v: &Value| match v {
                    Value::Q(q) => vec_of_key(q.dim.as_str()),
                    _ => DimVec::new(),
                };
                let vec = vec_combine(&dv(l), &dv(r), if op == "*" { 1 } else { -1 });
                let value = if op == "*" { lm * rm } else { lm / rm };
                if !value.is_finite() {
                    return err_code("non-finite", "E5002");
                }
                let key = key_of_vec(&vec);
                Ok(if key.is_empty() {
                    Value::Float(value)
                } else {
                    Value::quantity(key, value)
                })
            }
        }
    }

    /// the items of an array (or a range); an error for anything else
    pub fn iterate(&self, v: &Value) -> R<Vec<Value>> {
        match v {
            Value::PreArr(_) | Value::PreObj(_) => self.mat_arr(v),
            Value::Arr(a) => Ok(a.borrow().items.clone()),
            Value::Range(range) => {
                let (Value::Int(lo), Value::Int(hi)) = (&range.lo, &range.hi) else {
                    return err("range bounds must be integers");
                };
                let hi = if range.excl { hi.clone() } else { hi + 1 };
                let mut out = vec![];
                let mut i = lo.clone();
                while i < hi {
                    out.push(Value::Int(i.clone()));
                    i += 1;
                }
                Ok(out)
            }
            _ => err("not iterable"),
        }
    }

    pub(crate) fn truthy(&self, v: &Value) -> R<bool> {
        match v {
            Value::Bool(b) => Ok(*b),
            _ => err("non-bool condition"),
        }
    }

    fn binop(&self, op: &str, le: &Rc<Expr>, re: &Rc<Expr>, sc: &Scope) -> R<Value> {
        match op {
            "&&" => {
                return if self.truthy(&self.ev(le, sc)?)? {
                    Ok(Value::Bool(self.truthy(&self.ev(re, sc)?)?))
                } else {
                    Ok(Value::Bool(false))
                };
            }
            "||" => {
                return if self.truthy(&self.ev(le, sc)?)? {
                    Ok(Value::Bool(true))
                } else {
                    Ok(Value::Bool(self.truthy(&self.ev(re, sc)?)?))
                };
            }
            "??" => {
                let l = self.ev(le, sc)?;
                return if matches!(l, Value::Absent | Value::Null) {
                    self.ev(re, sc)
                } else {
                    Ok(l)
                };
            }
            _ => {}
        }
        self.apply_bin(op, self.ev(le, sc)?, self.ev(re, sc)?)
    }

    fn equal_values(&self, a: &Value, b: &Value) -> bool {
        fn observe(eng: &Engine, v: &Value) {
            match v {
                Value::Rec(inst) => {
                    eng.record(format!("value:{}", path_str(&inst.borrow().path, None)))
                }
                Value::Arr(a) => {
                    for v in &a.borrow().items {
                        observe(eng, v);
                    }
                }
                Value::Map(m) => {
                    for v in m.borrow().entries.values() {
                        observe(eng, v);
                    }
                }
                _ => {}
            }
        }
        if self.edits.borrow().is_some()
            && self.track.get()
            && !self.computing.borrow().is_empty()
            && matches!(
                (a, b),
                (Value::Rec(_), Value::Rec(_))
                    | (Value::Arr(_), Value::Arr(_))
                    | (Value::Map(_), Value::Map(_))
            )
        {
            observe(self, a);
            observe(self, b);
        }
        value_eq(a, b)
    }
    pub(crate) fn apply_bin(&self, op: &str, l: Value, mut r: Value) -> R<Value> {
        match op {
            ".." | "..<" => return Ok(Value::range(l, r, op == "..<")),
            "matches" => {
                let (Value::Str(s), Value::Pat(p)) = (&l, &r) else {
                    return err("matches needs a string and a pattern");
                };
                if let Some(bad) = pattern_error(p.as_ref()) {
                    return err_code(format!("malformed pattern /{p}/: {bad}"), "E4119");
                }
                let re = compile_pattern(p.as_ref()).or_else(err)?;
                return Ok(Value::Bool(re.is_match(s)));
            }
            // a literal operand is materialized: equality is structural over values (§4.5)
            "==" => {
                return Ok(Value::Bool(
                    self.equal_values(&self.mat_val(l)?, &self.mat_val(r)?),
                ))
            }
            "!=" => {
                return Ok(Value::Bool(
                    !self.equal_values(&self.mat_val(l)?, &self.mat_val(r)?),
                ))
            }
            "in" => {
                if matches!(r, Value::Ref(_)) {
                    r = self.deref(r)?; // the container may be reached through a reference ($this, $parent)
                }
                return match &r {
                    Value::Range(range) => {
                        let ge = matches!(num_cmp(&l, &range.lo), Some(Greater | Equal));
                        let hi_ok = if range.excl {
                            num_cmp(&l, &range.hi) == Some(Less)
                        } else {
                            matches!(num_cmp(&l, &range.hi), Some(Less | Equal))
                        };
                        Ok(Value::Bool(ge && hi_ok))
                    }
                    Value::PreArr(_) | Value::PreObj(_) => Ok(Value::Bool(
                        self.mat_arr(&r)?.iter().any(|x| self.equal_values(&l, x)),
                    )),
                    Value::Arr(a) => Ok(Value::Bool(
                        a.borrow().items.iter().any(|x| self.equal_values(&l, x)),
                    )),
                    Value::Map(m) => {
                        let Value::Str(k) = &l else {
                            return Ok(Value::Bool(false));
                        };
                        Ok(Value::Bool(m.borrow().has(k)))
                    }
                    Value::Rec(rec) => {
                        let Value::Str(k) = &l else {
                            return Ok(Value::Bool(false));
                        };
                        let has = rec.borrow().has_slot(k);
                        Ok(Value::Bool(
                            has && self.force_state(rec, k) != SlotState::Absent,
                        ))
                    }
                    _ => err("in: bad container"),
                };
            }
            _ => {}
        }
        if l.is_absent() || r.is_absent() {
            return err("absent consumed");
        }
        if (matches!(l, Value::Q(_)) || matches!(r, Value::Q(_)))
            && ["+", "-", "*", "/", "<", "<=", ">", ">="].contains(&op)
        {
            return self.q_arith(op, &l, &r);
        }
        let both_i = matches!((&l, &r), (Value::Int(_), Value::Int(_)));
        let both_f = matches!((&l, &r), (Value::Float(_), Value::Float(_)));
        let both_s = matches!((&l, &r), (Value::Str(_), Value::Str(_)));
        match (op, &l, &r) {
            ("+", Value::Str(a), Value::Str(b)) => Ok(Value::Str(format!("{a}{b}").into())),
            ("+", Value::Int(a), Value::Int(b)) => Ok(Value::Int(a + b)),
            ("+", Value::Float(a), Value::Float(b)) => Ok(Value::Float(a + b)),
            ("-", Value::Int(a), Value::Int(b)) => Ok(Value::Int(a - b)),
            ("-", Value::Float(a), Value::Float(b)) => Ok(Value::Float(a - b)),
            ("*", Value::Int(a), Value::Int(b)) => Ok(Value::Int(a * b)),
            ("*", Value::Float(a), Value::Float(b)) => Ok(Value::Float(a * b)),
            ("/", Value::Int(a), Value::Int(b)) => {
                if b.is_zero() {
                    return err_code("division by zero", "E5001");
                }
                Ok(Value::Int(a / b))
            }
            ("/", Value::Float(a), Value::Float(b)) => {
                if *b == 0.0 {
                    return err_code("division by zero", "E5001");
                }
                let q = a / b;
                if !q.is_finite() {
                    return err_code("non-finite", "E5002");
                }
                Ok(Value::Float(q))
            }
            ("%", Value::Int(a), Value::Int(b)) => {
                if b.is_zero() {
                    return err_code("mod zero", "E5001");
                }
                Ok(Value::Int(a % b))
            }
            ("<" | "<=" | ">" | ">=", _, _) if both_i || both_f || both_s => {
                let o = num_cmp(&l, &r);
                Ok(Value::Bool(matches!(
                    (op, o),
                    ("<", Some(Less))
                        | ("<=", Some(Less | Equal))
                        | (">", Some(Greater))
                        | (">=", Some(Greater | Equal))
                )))
            }
            ("&", Value::Int(a), Value::Int(b)) => Ok(Value::Int(a & b)),
            ("|", Value::Int(a), Value::Int(b)) => Ok(Value::Int(a | b)),
            ("^", Value::Int(a), Value::Int(b)) => Ok(Value::Int(a ^ b)),
            ("<<" | ">>", Value::Int(a), Value::Int(b)) => {
                if b.is_negative() {
                    return err_code("negative shift count", "E5003");
                }
                let n = b
                    .to_usize()
                    .ok_or(())
                    .or_else(|_| err("shift count too large"))?;
                Ok(Value::Int(if op == "<<" { a << n } else { a >> n }))
            }
            _ => err(format!("bad operands for {op}")),
        }
    }

    pub(crate) fn to_str(&self, v: &Value) -> R<String> {
        match v {
            Value::Str(s) => Ok(s.to_string()),
            Value::Bool(b) => Ok(if *b { "true".into() } else { "false".into() }),
            Value::Int(i) => Ok(i.to_string()),
            Value::Float(f) => Ok(js_num_str(*f)),
            _ => err("template: non-convertible"),
        }
    }

    // A frozen member may return references into an even older snapshot.
    // Carry their owners into the caller before it navigates those values.
    fn inherit_snapshot_refs(&self, value: &Value, owner: &Engine) {
        match value {
            Value::Ref(p) => {
                let key = Rc::as_ptr(p) as usize;
                if let Some(entry) = owner.snap_refs.borrow().get(&key) {
                    self.snap_refs.borrow_mut().insert(key, entry.clone());
                }
                if let Some(path) = owner.inverse_refs.borrow().get(&key) {
                    self.inverse_refs.borrow_mut().insert(key, path.clone());
                }
            }
            Value::Arr(a) => {
                for v in &a.borrow().items {
                    self.inherit_snapshot_refs(v, owner);
                }
            }
            Value::Map(m) => {
                for (_, v) in m.borrow().entries.iter() {
                    self.inherit_snapshot_refs(v, owner);
                }
            }
            _ => {}
        }
    }

    /// Read through a reference to the value it names (§7.4).
    pub fn deref(&self, v: Value) -> R<Value> {
        if let Value::Ref(p) = &v {
            let key = Rc::as_ptr(p) as usize;
            if self.round_cache.borrow().is_some()
                && (self.inverse_refs.borrow().contains_key(&key)
                    || self.snap_refs.borrow().contains_key(&key))
            {
                self.record("round:reference".into());
                if self.inverse_refs.borrow().contains_key(&key)
                    && !self.round_refs.borrow().contains_key(&key)
                {
                    self.record("round:nested".into());
                }
            }
            let snap = if self.settled.get() {
                None
            } else {
                self.snap_refs
                    .borrow()
                    .get(&(Rc::as_ptr(p) as usize))
                    .map(|(_, e)| e.clone())
            };
            let target = match snap {
                Some(e) => e.muted(|| e.resolve_segs(p))?,
                None => self.resolve_segs(p)?,
            };
            if target.is_undef() {
                return err_code(format!("dangling reference {}", path_str(p, None)), "E6002");
            }
            return Ok(target);
        }
        Ok(v)
    }

    // the value at a place; Undef when there is none (an absent optional
    // member counts as none — §7.5). Lenient about segment kinds: engine-built
    // paths are canonical by construction
    /// The value at a canonical path from a root (§7.2), forcing what the path crosses.
    pub fn resolve_segs(&self, segs: &[Seg]) -> R<Value> {
        // A copied round holds the records an answer can name, by path.
        if let Some(index) = self.frozen_index.borrow().as_ref() {
            return Ok(index
                .get(&path_str(segs, None))
                .map_or(Value::Undef, |r| Value::Rec(r.clone())));
        }
        if let Some(Seg::Name(name)) = segs.first() {
            self.record(format!("root:{name}"));
        }
        let mut cur = match segs.first() {
            Some(Seg::Name(n)) => self.root(n).unwrap_or(Value::Undef),
            _ => Value::Undef,
        };
        for s in segs.iter().skip(1) {
            if cur.is_undef() {
                break;
            }
            cur = match (&cur, s) {
                (Value::Rec(r), Seg::Name(n) | Seg::Key(n)) => {
                    if r.borrow().slot(n).is_some() {
                        self.force_slot(r, n)?
                    } else {
                        Value::Undef
                    }
                }
                (Value::Arr(a), Seg::Idx(i)) => {
                    a.borrow().items.get(*i).cloned().unwrap_or(Value::Undef)
                }
                (Value::Map(m), Seg::Name(n) | Seg::Key(n)) => {
                    m.borrow().get(n).cloned().unwrap_or(Value::Undef)
                }
                _ => Value::Undef,
            };
            if cur.is_absent() {
                cur = Value::Undef;
            }
            if let Value::Ref(_) = cur {
                cur = self.deref(cur)?;
            }
        }
        Ok(cur)
    }
    // a path from a document must be canonical (§7.2, §7.5): a map key
    // bracketed, a record member dotted when the dot can spell it and
    // bracketed otherwise, an array index numeric — any other spelling does
    // not resolve
    /// The value at a canonical path as a document's reference string names it (§7.5).
    pub fn resolve_canonical(&self, segs: &[Seg]) -> R<Value> {
        let mut cur = match segs.first() {
            Some(Seg::Name(n)) => self.root(n).unwrap_or(Value::Undef),
            _ => Value::Undef,
        };
        for s in segs.iter().skip(1) {
            if cur.is_undef() {
                break;
            }
            cur = match (&cur, s) {
                (Value::Rec(r), Seg::Name(n)) if dot_spellable(n) => {
                    if r.borrow().slot(n).is_some() {
                        self.force_slot(r, n)?
                    } else {
                        Value::Undef
                    }
                }
                (Value::Rec(r), Seg::Key(n)) if !dot_spellable(n) => {
                    if r.borrow().slot(n).is_some() {
                        self.force_slot(r, n)?
                    } else {
                        Value::Undef
                    }
                }
                (Value::Arr(a), Seg::Idx(i)) => {
                    a.borrow().items.get(*i).cloned().unwrap_or(Value::Undef)
                }
                (Value::Map(m), Seg::Key(n)) => m.borrow().get(n).cloned().unwrap_or(Value::Undef),
                _ => Value::Undef,
            };
            if cur.is_absent() {
                cur = Value::Undef;
            }
            if let Value::Ref(_) = cur {
                cur = self.deref(cur)?;
            }
        }
        Ok(cur)
    }

    /// a member of a record (or an unbound literal) by name; ABSENT when absent
    pub fn access(&self, x: &Value, name: &str) -> R<Value> {
        match x {
            Value::Rec(r) => {
                let (has, is_extra) = {
                    let b = r.borrow();
                    (b.has_slot(name), b.extra(name).is_some())
                };
                if has {
                    return self.force_slot(r, name); // Absent when the member is absent
                }
                if is_extra {
                    return err(format!("opaque field {name} accessed"));
                }
                // a member the record's type does not declare: the checker admitted the
                // read against a bound that declares it optional, so it is absent (§4.10)
                Ok(Value::Absent)
            }
            Value::PreObj(es) => {
                for (k, v) in self.entries_of(es)? {
                    if k == name {
                        return match v {
                            Value::PreVal(pv) => self.ev(&pv.expr, &pv.scope),
                            other => Ok(other),
                        };
                    }
                }
                Ok(Value::Absent)
            }
            // a literal that no record type claimed is a map at evaluation time
            // while the checker typed its members by name; the name reads the entry
            Value::Map(m) => Ok(m.borrow().get(name).cloned().unwrap_or(Value::Absent)),
            Value::Null => err("member access on null"),
            Value::Absent => Ok(Value::Absent),
            _ => err(format!("member access on non-record ({name})")),
        }
    }

    fn slot_lookup(&self, inst: &Inst, name: &str) -> R<Option<Value>> {
        let mut cur = Some(inst.clone());
        while let Some(c) = cur {
            if c.borrow().has_slot(name) {
                return Ok(Some(self.force_slot(&c, name)?)); // Absent when the member is absent
            }
            cur = c.borrow().parent.clone();
        }
        Ok(None)
    }

    /// Apply a function value — a closure, a native, a standard-library function — to arguments (§4.8).
    pub fn call(&self, f: &Value, args: Vec<Value>, sc: &Scope) -> R<Value> {
        match f {
            Value::Clo(c) => {
                let mut locals = c.scope.locals.clone();
                for (p, a) in c.params.iter().zip(args) {
                    locals = locals.with(Rc::from(p.as_str()), a);
                }
                self.ev(&c.body, &c.scope.with_locals(locals))
            }
            Value::Nat(f) => f(&args),
            Value::Std(p) => self.std(&p.join("."), args, sc),
            _ => err("call of non-function"),
        }
    }

    fn std(&self, name: &str, a: Vec<Value>, sc: &Scope) -> R<Value> {
        #[cfg(feature = "runtime-diagnostics")]
        if name == "map.values" {
            expr_diag::values_attempt();
        }
        let domain = |msg: String| -> Fail {
            Fail::Eval(EvalErr {
                msg: format!("std.{name}: {msg}"),
                code: Some("E5008".into()),
            })
        };
        let arr = |path: Vec<Value>| {
            #[cfg(feature = "runtime-diagnostics")]
            if name == "map.values" {
                expr_diag::values_return(path.len(), path.capacity());
            }
            #[cfg(feature = "runtime-diagnostics")]
            crate::retention_diagnostics::standard_array(name, path.len(), path.capacity());
            Value::Arr(Rc::new(RefCell::new(ArrV {
                items: path,
                path: self.container_path(&[]),
            })))
        };
        let s = |v: &Value| -> R<String> {
            match v {
                Value::Str(s) => Ok(s.to_string()),
                _ => err(format!("std.{name}: expected string")),
            }
        };
        match name {
            "array.count" => Ok(Value::Int(Num::from(
                self.mat_arr_ref(arg(&a, 0, name)?)?.borrow().items.len(),
            ))),
            "array.all" => {
                // iterate by index, cloning one item at a time, so a predicate
                // over a freshly built array does not copy the whole vector
                // first (F21: the hot path in an O(n^2) model comprehension)
                let items = self.mat_arr_ref(arg(&a, 0, name)?)?;
                let n = items.borrow().items.len();
                for i in 0..n {
                    let x = items.borrow().items[i].clone();
                    if !self.truthy(&self.call(arg(&a, 1, name)?, vec![x], sc)?)? {
                        return Ok(Value::Bool(false));
                    }
                }
                Ok(Value::Bool(true))
            }
            "array.any" => {
                let items = self.mat_arr_ref(arg(&a, 0, name)?)?;
                let n = items.borrow().items.len();
                for i in 0..n {
                    let x = items.borrow().items[i].clone();
                    if self.truthy(&self.call(arg(&a, 1, name)?, vec![x], sc)?)? {
                        return Ok(Value::Bool(true));
                    }
                }
                Ok(Value::Bool(false))
            }
            "array.filter" => {
                let items = self.mat_arr_ref(arg(&a, 0, name)?)?;
                let n = items.borrow().items.len();
                let mut out = vec![];
                for i in 0..n {
                    let x = items.borrow().items[i].clone();
                    if self.truthy(&self.call(arg(&a, 1, name)?, vec![x.clone()], sc)?)? {
                        out.push(x);
                    }
                }
                Ok(arr(out))
            }
            "array.all_distinct" => {
                let items = self.mat_arr(arg(&a, 0, name)?)?;
                for i in 0..items.len() {
                    for j in i + 1..items.len() {
                        if self.equal_values(&items[i], &items[j]) {
                            return Ok(Value::Bool(false));
                        }
                    }
                }
                Ok(Value::Bool(true))
            }
            "array.sum" => {
                let items = self.mat_arr(arg(&a, 0, name)?)?;
                let Some(first) = items.first() else {
                    return Ok(Value::Int(Num::zero()));
                };
                let mut acc = if matches!(first, Value::Float(_)) {
                    Value::Float(0.0)
                } else {
                    Value::Int(Num::zero())
                };
                for x in &items {
                    acc = add_num(&acc, x)?;
                }
                Ok(acc)
            }
            "array.fold" => {
                let items = self.mat_arr_ref(arg(&a, 0, name)?)?;
                let n = items.borrow().items.len();
                let mut acc = arg(&a, 1, name)?.clone();
                for i in 0..n {
                    let x = items.borrow().items[i].clone();
                    acc = self.call(arg(&a, 2, name)?, vec![acc, x], sc)?;
                }
                Ok(acc)
            }
            "array.sort" => {
                let mut items = vec![];
                for x in self.mat_arr(arg(&a, 0, name)?)? {
                    items.push(self.mat_val(x)?);
                }
                if items.iter().any(|x| !is_orderable(x)) {
                    return Err(domain("elements must be int, float, or string".into()));
                }
                let mut keyed: Vec<(Value, Value)> =
                    items.into_iter().map(|x| (x.clone(), x)).collect();
                sort_keyed(&mut keyed)?;
                Ok(arr(keyed.into_iter().map(|(_, x)| x).collect()))
            }
            "array.sort_by" => {
                let mut keyed = vec![];
                for x in self.mat_arr(arg(&a, 0, name)?)? {
                    let k = self.mat_val(self.call(arg(&a, 1, name)?, vec![x.clone()], sc)?)?;
                    if !is_orderable(&k) {
                        return Err(domain("keys must be int, float, or string".into()));
                    }
                    keyed.push((k, x));
                }
                sort_keyed(&mut keyed)?;
                Ok(arr(keyed.into_iter().map(|(_, x)| x).collect()))
            }
            "array.unique" => {
                let mut out: Vec<Value> = vec![];
                for x in self.mat_arr(arg(&a, 0, name)?)? {
                    if !out.iter().any(|y| self.equal_values(y, &x)) {
                        out.push(x);
                    }
                }
                Ok(arr(out))
            }
            "array.reverse" => {
                let mut items = self.mat_arr(arg(&a, 0, name)?)?;
                items.reverse();
                Ok(arr(items))
            }
            "map.keys" => Ok(arr(self
                .mat_map(arg(&a, 0, name)?)?
                .borrow()
                .entries
                .iter()
                .map(|(k, _)| Value::Str(k.clone().into()))
                .collect())),
            "map.values" => Ok(arr(self
                .mat_map(arg(&a, 0, name)?)?
                .borrow()
                .entries
                .iter()
                .map(|(_, v)| v.clone())
                .collect())),
            "map.entries" => Ok(arr(self
                .mat_map(arg(&a, 0, name)?)?
                .borrow()
                .entries
                .iter()
                .map(|(k, v)| {
                    Value::PreObj(Rc::new(vec![
                        ("key".into(), Value::Str(k.clone().into())),
                        ("value".into(), v.clone()),
                    ]))
                })
                .collect())),
            "string.length" => Ok(Value::Int(Num::from(s(arg(&a, 0, name)?)?.chars().count()))),
            "string.of" => Ok(Value::Str(self.to_str(arg(&a, 0, name)?)?.into())),
            "string.join" => {
                let sep = s(arg(&a, 1, name)?)?;
                let parts: Vec<String> = self
                    .mat_arr(arg(&a, 0, name)?)?
                    .iter()
                    .map(s)
                    .collect::<R<_>>()?;
                Ok(Value::Str(parts.join(&sep).into()))
            }
            "string.starts_with" => Ok(Value::Bool(
                s(arg(&a, 0, name)?)?.starts_with(&s(arg(&a, 1, name)?)?),
            )),
            "string.ends_with" => Ok(Value::Bool(
                s(arg(&a, 0, name)?)?.ends_with(&s(arg(&a, 1, name)?)?),
            )),
            "string.contains" => Ok(Value::Bool(
                s(arg(&a, 0, name)?)?.contains(&s(arg(&a, 1, name)?)?),
            )),
            "string.split" => {
                let sep = s(arg(&a, 1, name)?)?;
                if sep.is_empty() {
                    return Err(domain("separator must be non-empty".into()));
                }
                Ok(arr(s(arg(&a, 0, name)?)?
                    .split(&sep)
                    .map(|p| Value::Str(p.to_string().into()))
                    .collect()))
            }
            "ref.path" => match arg(&a, 0, name)? {
                Value::Ref(p) => Ok(Value::Str(path_str(p, None).into())),
                _ => err("ref.path on non-reference"),
            },
            "math.abs" => match arg(&a, 0, name)? {
                Value::Int(i) => Ok(Value::Int(i.abs())),
                Value::Float(f) => Ok(Value::Float(f.abs())),
                _ => err("std.math.abs: bad operand"),
            },
            "math.min" | "math.max" => {
                let (x, y) = (arg(&a, 0, name)?, arg(&a, 1, name)?);
                let Some(o) = num_cmp(x, y) else {
                    return err(format!("std.{name}: bad operands"));
                };
                let pick_x = if name == "math.min" {
                    o == Less
                } else {
                    o == Greater
                };
                Ok(if pick_x { x.clone() } else { y.clone() })
            }
            "math.clog2" => {
                let n = arg(&a, 0, name)?;
                let Value::Int(i) = n else {
                    return Err(domain(format!("n >= 1 required, got {}", num_s(n))));
                };
                if i < &Num::from(1) {
                    return Err(domain(format!("n >= 1 required, got {i}")));
                }
                Ok(Value::Int(Num::from((i - 1).bits())))
            }
            "math.floor" | "math.ceil" => match arg(&a, 0, name)? {
                Value::Float(f) => {
                    let r = if name == "math.floor" {
                        f.floor()
                    } else {
                        f.ceil()
                    };
                    Num::from_f64(r)
                        .map(Value::Int)
                        .ok_or(())
                        .or_else(|_| err(format!("std.{name}: non-finite")))
                }
                Value::Int(i) => Ok(Value::Int(i.clone())),
                _ => err(format!("std.{name}: bad operand")),
            },
            "math.round" => match arg(&a, 0, name)? {
                Value::Float(x) => {
                    let f = x.floor();
                    let frac = x - f;
                    let r = if frac > 0.5 {
                        f + 1.0
                    } else if frac < 0.5 || f % 2.0 == 0.0 {
                        f
                    } else {
                        f + 1.0
                    };
                    Num::from_f64(r)
                        .map(Value::Int)
                        .ok_or(())
                        .or_else(|_| err("std.math.round: non-finite"))
                }
                Value::Int(i) => Ok(Value::Int(i.clone())),
                _ => err("std.math.round: bad operand"),
            },
            "int.of" => match arg(&a, 0, name)? {
                Value::Float(x) if x.fract() == 0.0 && x.is_finite() => {
                    Ok(Value::Int(Num::from_f64(*x).unwrap()))
                }
                other => Err(domain(format!(
                    "no fractional part allowed, got {}",
                    num_s(other)
                ))),
            },
            "int.at_least" | "int.at_most" => {
                let n = arg(&a, 0, name)?.clone();
                let least = name == "int.at_least";
                Ok(Value::native(move |args: &[Value]| {
                    let Some(x) = args.first() else {
                        return err("missing argument");
                    };
                    match num_cmp(x, &n) {
                        Some(o) => Ok(Value::Bool(if least { o != Less } else { o != Greater })),
                        None => err("bad operands"),
                    }
                }))
            }
            "float.of" => {
                let v = match arg(&a, 0, name)? {
                    Value::Int(i) => i.to_f64().unwrap_or(f64::INFINITY),
                    Value::Float(f) => *f,
                    Value::Str(s) => s
                        .parse::<f64>()
                        .or_else(|_| err("std.float.of: bad operand"))?,
                    _ => return err("std.float.of: bad operand"),
                };
                if !v.is_finite() {
                    return Err(domain("magnitude outside binary64 range".into()));
                }
                Ok(Value::Float(v))
            }
            "object.merge" => self.deep_merge(arg(&a, 0, name)?, arg(&a, 1, name)?),
            _ => err(format!("std.{name} does not exist")),
        }
    }

    fn deep_merge(&self, base0: &Value, patch0: &Value) -> R<Value> {
        let base = self.mat_rec(base0)?;
        let patch = self.mat_rec(patch0)?;
        let val = |r: &Inst, n: &str| -> R<Option<Value>> {
            {
                let b = r.borrow();
                if let Some(v) = b.extra(n) {
                    return Ok(Some(v.clone()));
                }
                match b.slot(n) {
                    None => return Ok(None),
                    Some(s) if s.kind == MKind::Der => return Ok(None),
                    _ => {}
                }
            }
            let v = self.force_slot(r, n)?;
            if r.borrow().slot(n).map(|s| s.state) == Some(SlotState::Absent) {
                return Ok(None);
            }
            Ok(Some(v))
        };
        let mut names: Vec<String> = vec![];
        let mut push = |n: &str| {
            if !names.iter().any(|x| x == n) {
                names.push(n.to_string());
            }
        };
        for r in [&base, &patch] {
            let b = r.borrow();
            for n in b.entry_order.iter() {
                push(n);
            }
            for m in rec_members(&b.rt).iter() {
                if m.kind == MKind::Dflt {
                    push(&m.name);
                }
            }
        }
        let mut entries = vec![];
        for n in &names {
            let is_der = |r: &Inst| {
                r.borrow()
                    .slot(n)
                    .map(|s| s.kind == MKind::Der)
                    .unwrap_or(false)
            };
            if is_der(&base) || is_der(&patch) {
                continue;
            }
            let bv = val(&base, n)?;
            let pv = val(&patch, n)?;
            match (bv, pv) {
                (Some(bv), Some(pv)) => {
                    let bd = self.deref(bv.clone())?;
                    let pd = self.deref(pv.clone())?;
                    if matches!(bd, Value::Rec(_)) && matches!(pd, Value::Rec(_)) {
                        entries.push((n.clone(), self.deep_merge(&bv, &pv)?));
                    } else {
                        entries.push((n.clone(), pv));
                    }
                }
                (_, Some(pv)) => entries.push((n.clone(), pv)),
                (Some(bv), None) => entries.push((n.clone(), bv)),
                (None, None) => {}
            }
        }
        Ok(Value::PreObj(Rc::new(entries)))
    }

    /// A value with its literal (or document) form materialized.
    pub fn mat_val(&self, v: Value) -> R<Value> {
        let d = self.deref(v)?;
        if matches!(d, Value::PreObj(_) | Value::PreArr(_)) {
            return self.mat_pre(d);
        }
        if matches!(d, Value::JObj(_)) {
            return self.materialize(d, &[]);
        }
        Ok(d)
    }
    /// An unmaterialized literal materialized once (see `mat_cache`).
    fn mat_pre(&self, d: Value) -> R<Value> {
        let key = match &d {
            Value::PreArr(rc) => Rc::as_ptr(rc) as usize,
            Value::PreObj(rc) => Rc::as_ptr(rc) as usize,
            _ => return self.materialize(d, &[]),
        };
        #[cfg(feature = "runtime-diagnostics")]
        let diagnostic_cache =
            crate::retention_diagnostics::CacheAttempt::start(if matches!(d, Value::PreArr(_)) {
                0
            } else {
                1
            });
        if let Some((identity, m)) = self.mat_cache.borrow().get(&key) {
            debug_assert!(identity.matches(&d), "cached literal allocation identity");
            #[cfg(feature = "runtime-diagnostics")]
            diagnostic_cache.hit();
            return Ok(m.clone());
        }
        #[cfg(feature = "runtime-diagnostics")]
        diagnostic_cache.miss();
        let identity = MaterializedLiteral::of(&d);
        let m = self.materialize(d.clone(), &[])?;
        #[cfg(feature = "runtime-diagnostics")]
        let diagnostic_before = self.mat_cache.borrow().len();
        self.mat_cache
            .borrow_mut()
            .insert(key, (identity, m.clone()));
        #[cfg(feature = "runtime-diagnostics")]
        {
            let cache = self.mat_cache.borrow();
            diagnostic_cache.inserted(diagnostic_before, cache.len(), cache.capacity());
        }
        let sweep = self.mat_cache.borrow().len() >= self.materialized_sweep_at.get();
        if sweep {
            self.prune_materialized();
        }
        Ok(m)
    }
    /// The entries of an unbound object literal with its spreads (§4.2)
    /// expanded in place: a spread copies the entries of an object-valued
    /// operand — a record's value members (hidden ones are not entries), a
    /// map's entries, or another literal's — and a key produced twice is
    /// E5004. Spread operands evaluate in the literal's own scope.
    pub fn entries_of(&self, es: &[(String, Value)]) -> R<Vec<(String, Value)>> {
        let is_spread =
            |v: &Value| matches!(v, Value::PreVal(pv) if matches!(&*pv.expr, Expr::Spread(_)));
        if !es.iter().any(|(_, v)| is_spread(v)) {
            return Ok(es.to_vec());
        }
        let mut out: Vec<(String, Value)> = vec![];
        let mut seen = KeysSeen::default();
        let mut put = |k: String, v: Value| -> R<()> {
            if !seen.admits(&out, &k) {
                return err_code(format!("duplicate key {k}"), "E5004");
            }
            out.push((k, v));
            Ok(())
        };
        for (k, v) in es {
            if !is_spread(v) {
                put(k.clone(), v.clone())?;
                continue;
            }
            let Value::PreVal(pv) = v else { unreachable!() };
            let Expr::Spread(inner) = &*pv.expr else {
                unreachable!()
            };
            let s = self.deref(self.ev(inner, &pv.scope)?)?;
            for (k2, v2) in self.spread_entries(s)? {
                put(k2, v2)?;
            }
        }
        Ok(out)
    }
    pub(crate) fn spread_entries(&self, s: Value) -> R<Vec<(String, Value)>> {
        match s {
            Value::PreObj(es) => self.entries_of(&es),
            Value::JObj(es) => Ok((*es).clone()),
            Value::Map(m) => Ok(m
                .borrow()
                .entries
                .iter()
                .map(|(k, v)| (k.clone(), v.clone()))
                .collect()),
            Value::Rec(r) => {
                // the value's entries in serialization order (§10.3): supplied
                // members in document order, then the members evaluation
                // materialized, in declaration order — every value member,
                // hidden ones never
                let (order, names) = {
                    let b = r.borrow();
                    (
                        b.entry_order.clone(),
                        rec_members(&b.rt)
                            .iter()
                            .map(|m| m.name.clone())
                            .collect::<Vec<_>>(),
                    )
                };
                let mut entries: Vec<(String, Value)> = vec![];
                let mut seen: Vec<String> = vec![];
                for n in order.iter().cloned().chain(names) {
                    if seen.contains(&n) {
                        continue;
                    }
                    seen.push(n.clone());
                    let (extra, hidden, has) = {
                        let b = r.borrow();
                        (
                            b.extra(&n).cloned(),
                            b.slots.iter().any(|(s, sl)| s.as_ref() == n && sl.hidden),
                            b.has_slot(&n),
                        )
                    };
                    if let Some(x) = extra {
                        entries.push((n, x));
                        continue;
                    }
                    if !has || hidden {
                        continue;
                    }
                    let v = self.force_slot(&r, &n)?;
                    if r.borrow().slot(&n).map(|s| s.state) == Some(SlotState::Absent) {
                        continue;
                    }
                    entries.push((n, v));
                }
                Ok(entries)
            }
            _ => err("spread of a non-object value"),
        }
    }
    fn mat_rec(&self, v: &Value) -> R<Inst> {
        let mut d = self.deref(v.clone())?;
        if matches!(d, Value::PreObj(_) | Value::PreArr(_)) {
            d = self.mat_pre(d)?; // materialize once, cached (F21)
        } else if matches!(d, Value::JObj(_)) {
            d = self.materialize(d, &[])?;
        }
        match d {
            Value::Rec(r) => Ok(r),
            _ => err_code("std.object.merge: expected records", "E5008"),
        }
    }
    fn mat_arr(&self, v: &Value) -> R<Vec<Value>> {
        Ok(self.mat_arr_ref(v)?.borrow().items.clone())
    }
    /// the materialized array without copying its items: for callers that only
    /// read (a length, an index) and never call back into user code while the
    /// borrow is held — `mat_arr` clones because iterating callbacks would else
    /// double-borrow this cell (F21: `count` was cloning the whole vector)
    fn mat_arr_ref(&self, v: &Value) -> R<Rc<RefCell<ArrV>>> {
        let mut d = self.deref(v.clone())?;
        if matches!(d, Value::PreObj(_) | Value::PreArr(_)) {
            d = self.mat_pre(d)?;
        }
        match d {
            Value::Arr(a) => Ok(a),
            _ => err("expected array"),
        }
    }
    fn mat_map(&self, v: &Value) -> R<Rc<RefCell<MapV>>> {
        let mut d = self.deref(v.clone())?;
        if matches!(d, Value::PreObj(_) | Value::PreArr(_)) {
            d = self.mat_pre(d)?;
        }
        match d {
            Value::Map(m) => Ok(m),
            // a record reads as the map of its value entries (§3.17)
            Value::Rec(r) => {
                let path = self.container_path(&r.borrow().path);
                let entries = self.spread_entries(Value::Rec(r))?;
                Ok(Rc::new(RefCell::new(MapV {
                    entries: entries.into_iter().collect(),
                    path,
                })))
            }
            _ => err("expected map"),
        }
    }

    // ---------- referrers ----------
    pub(crate) fn referrers(&self, type_name: &str, member: &str, sc: &Scope) -> R<Value> {
        if self.phase.get() < 2 {
            return Err(Fail::Defer);
        }

        let Some(self_inst) = &sc.inst else {
            return err("$referrers outside a record");
        };
        let target = self_inst.borrow().path.clone();
        self.record(if self.round_cache.borrow().is_some() {
            format!("edge:{type_name}|{member}|{}", path_str(&target, None))
        } else {
            format!("referrers:{type_name}")
        });
        let key = format!("{type_name}|{member}");
        let inv = {
            let cached = self.ref_index.borrow().get(&key).cloned();
            match cached {
                Some(i) => i,
                None => {
                    // The inverse belongs to the frozen round. Reacquiring
                    // its edge on a cache hit would deep-clone every referrer
                    // for every target, turning indexed lookup quadratic.
                    let edge = self.snap_edge(type_name, member)?;
                    // one pass over the edge inverts it: each referrer is filed
                    // under every distinct place its member refers to
                    let mut inv: FxHashMap<String, Vec<SegPath>> = FxHashMap::default();
                    for (rp, refs) in edge.values() {
                        let mut seen: FxHashSet<String> = FxHashSet::default();
                        for r in refs {
                            let tk = path_str(r, None);
                            if seen.insert(tk.clone()) {
                                inv.entry(tk).or_default().push(rp.clone());
                            }
                        }
                    }
                    let rc = Rc::new(inv);
                    self.ref_index.borrow_mut().insert(key, rc.clone());
                    rc
                }
            }
        };
        let mut out: Vec<SegPath> = inv
            .get(&path_str(&target, None))
            .cloned()
            .unwrap_or_default();
        out.sort_by(|a, b| path_key_cmp(a, b));
        let prev = self.prev.borrow().clone();
        let items: Vec<Value> = out
            .into_iter()
            .map(|p| {
                let rc = Rc::new(p);
                if self.round_cache.borrow().is_some() {
                    self.round_refs
                        .borrow_mut()
                        .insert(Rc::as_ptr(&rc) as usize, rc.clone());
                    self.inverse_refs
                        .borrow_mut()
                        .insert(Rc::as_ptr(&rc) as usize, rc.clone());
                }
                if let Some(e) = &prev {
                    self.snap_refs
                        .borrow_mut()
                        .insert(Rc::as_ptr(&rc) as usize, (rc.clone(), e.clone()));
                }
                Value::Ref(rc)
            })
            .collect();
        #[cfg(feature = "runtime-diagnostics")]
        crate::retention_diagnostics::array(
            crate::retention_diagnostics::ArraySite::Referrers,
            items.len(),
            items.capacity(),
        );
        Ok(Value::Arr(Rc::new(RefCell::new(ArrV {
            items,
            path: self.container_path(&[]),
        }))))
    }
    /// the edge `T|m` of the snapshot: computed from its instances on first demand
    fn snap_edge(&self, type_name: &str, member: &str) -> R<Edge> {
        if self.snap.borrow().is_none() {
            self.take_snapshot(HashMap::new()); // a lazy session: what is materialized
        }
        let key = format!("{type_name}|{member}");
        self.queried.borrow_mut().insert(key.clone());
        if let Some(e) = self.snap.borrow().as_ref().unwrap().edges.get(&key) {
            return Ok(e.clone());
        }
        if self.computing_edges.borrow().contains(&key) {
            return Err(Fail::Defer);
        }
        self.computing_edges.borrow_mut().insert(key.clone());
        let insts = self
            .snap
            .borrow()
            .as_ref()
            .unwrap()
            .insts
            .get(type_name)
            .cloned()
            .unwrap_or_default();
        self.edge_bases
            .borrow_mut()
            .push(self.computing.borrow().len());
        let edge = self.edge_of(&insts, member);
        self.edge_bases.borrow_mut().pop();
        self.computing_edges.borrow_mut().remove(&key);
        self.snap
            .borrow_mut()
            .as_mut()
            .unwrap()
            .edges
            .insert(key, edge.clone());
        Ok(edge)
    }
    /// the snapshot's instances: the previous round's universe, else what is materialized now
    pub(crate) fn take_snapshot(&self, edges: HashMap<String, Edge>) {
        self.ref_index.borrow_mut().clear();
        let prev = self.prev.borrow().clone();
        let insts = match &prev {
            Some(p) => p.frozen_registry.borrow().clone().unwrap_or_default(),
            None => self.env.registry_snapshot(),
        };
        *self.snap.borrow_mut() = Some(Snap {
            insts: group_by_type(&insts),
            edges,
        });
    }
    /// every candidate's path with the places its member refers to (an invalid member: excluded silently, §6.6)
    fn edge_of(&self, insts: &[Inst], member: &str) -> Edge {
        let mut out = Edge::new();
        for cand in insts {
            let state = cand.borrow().slot(member).map(|s| s.state);
            match state {
                None | Some(SlotState::Forcing) => continue, // in computation: needs this very edge
                _ => {}
            }
            let Ok(v) = self.force_slot(cand, member) else {
                continue;
            };
            let mut refs = vec![];
            refs_in(&v, &mut refs);
            let path = cand.borrow().path.to_vec();
            out.insert(path_str(&path, None), (path, refs));
        }
        out
    }
    /// the queried edges over this round's universe, answered from its snapshot
    fn live_edges(&self) -> HashMap<String, Edge> {
        let mut out: HashMap<String, Edge> = HashMap::new();
        loop {
            let todo: Vec<String> = self
                .queried
                .borrow()
                .iter()
                .filter(|k| !out.contains_key(*k))
                .cloned()
                .collect();
            if todo.is_empty() {
                return out;
            }
            let insts = group_by_type(&self.env.registry_snapshot());
            for key in todo {
                let (t, m) = key.split_once('|').unwrap();
                let e = self.edge_of(insts.get(t).map(|v| v.as_slice()).unwrap_or(&[]), m);
                out.insert(key.clone(), e);
            } // forcing may have materialized more, and queried more
        }
    }
    /// Phase 2, one round: the deferred slots and roots, then everything; stable when the queried edges did not change.
    pub fn settle(&self, env: &Env, edges: HashMap<String, Edge>) -> Settled {
        #[cfg(feature = "runtime-diagnostics")]
        let mut timings = crate::evaluation_diagnostics::Span::new("settle", 0);
        #[cfg(feature = "runtime-diagnostics")]
        timings.enter(EventStage::SettleTakeSnapshot);
        self.phase.set(2);
        self.take_snapshot(edges);
        #[cfg(feature = "runtime-diagnostics")]
        timings.mark("take_snapshot");
        #[cfg(feature = "runtime-diagnostics")]
        timings.enter(EventStage::SettleDeferredSnapshot);
        let deferred: Vec<(Inst, String)> = self.deferred_slots.borrow_mut().drain(..).collect();

        #[cfg(feature = "runtime-diagnostics")]
        timings.mark("deferred_snapshot");
        #[cfg(feature = "runtime-diagnostics")]
        timings.enter(EventStage::SettleForceDeferredSlots);
        for (inst, name) in &deferred {
            self.force_slot_safe(inst, name);
        }

        #[cfg(feature = "runtime-diagnostics")]
        timings.mark("force_deferred_slots");
        #[cfg(feature = "runtime-diagnostics")]
        timings.enter(EventStage::SettleBindDeferredRoots);
        self.bind_deferred_roots();
        #[cfg(feature = "runtime-diagnostics")]
        timings.mark("bind_deferred_roots");
        #[cfg(feature = "runtime-diagnostics")]
        timings.enter(EventStage::SettleForceRoots);
        self.force_roots(env);
        #[cfg(feature = "runtime-diagnostics")]
        timings.mark("force_roots");
        #[cfg(feature = "runtime-diagnostics")]
        timings.enter(EventStage::SettleLiveEdges);
        let live = self.live_edges();
        #[cfg(feature = "runtime-diagnostics")]
        timings.mark("live_edges");
        #[cfg(feature = "runtime-diagnostics")]
        timings.enter(EventStage::SettleCompareEdges);
        let snap = self.snap.borrow();
        let snap_edges = &snap.as_ref().unwrap().edges;
        let mut changed: Vec<String> = live
            .iter()
            .filter(|(k, e)| !snap_edges.get(*k).is_some_and(|f| edge_eq(e, f)))
            .map(|(k, _)| k.clone())
            .collect();
        changed.sort();
        drop(snap);
        #[cfg(feature = "runtime-diagnostics")]
        timings.mark("compare_edges");
        #[cfg(feature = "runtime-diagnostics")]
        timings.finish();
        Settled {
            stable: changed.is_empty(),
            edges: live,
            changed,
        }
    }
    /// this round's universe, kept as the next round's snapshot
    fn freeze(&self) {
        let registry = self.env.registry_snapshot();
        *self.frozen_set.borrow_mut() = registry.iter().map(|i| Rc::as_ptr(i) as usize).collect();
        *self.frozen_roots.borrow_mut() = Some(self.env.roots_vec());
        *self.frozen_registry.borrow_mut() = Some(registry);
    }
    /// the frozen round that owns an instance, if it is not this engine's
    pub(crate) fn owner_of(&self, inst: &Inst) -> Option<Rc<Engine>> {
        let prev = self.prev.borrow().clone()?;
        if prev
            .frozen_set
            .borrow()
            .contains(&(Rc::as_ptr(inst) as usize))
        {
            return Some(prev);
        }
        prev.owner_of(inst)
    }
    /// Run inside a frozen round: what it reports is not this evaluation's.
    pub fn muted<T>(&self, f: impl FnOnce() -> T) -> T {
        self.env.muted.set(self.env.muted.get() + 1);
        let r = f();
        self.env.muted.set(self.env.muted.get() - 1);
        r
    }
    /// Evaluate a universe (§7.6, §9.3): `bind` binds every root on a fresh
    /// engine; the rounds repeat, each answering `$referrers` from the previous
    /// round, until the queried edges are stable — the settled engine is the
    /// result. A universe still changing after `ROUNDS` rounds is E5009.
    pub fn evaluate(env: &Rc<Env>, bind: &dyn Fn(&Rc<Engine>), track: bool) -> Rc<Engine> {
        Self::evaluate_rounds(env, bind, track, false, None)
    }
    /// Evaluate with retained member, structure and reference dependencies.
    pub fn evaluate_query(env: &Rc<Env>, bind: &dyn Fn(&Rc<Engine>)) -> Rc<Engine> {
        Self::evaluate_rounds(env, bind, false, true, None)
    }
    /// Evaluate a Session, reusing its engine after an edited materialization.
    pub fn evaluate_session(
        env: &Rc<Env>,
        bind: &dyn Fn(&Rc<Engine>),
        initial: Option<Rc<Engine>>,
    ) -> Rc<Engine> {
        Self::evaluate_rounds(env, bind, true, true, initial)
    }
    fn evaluate_rounds(
        env: &Rc<Env>,
        bind: &dyn Fn(&Rc<Engine>),
        track: bool,
        incremental: bool,
        initial: Option<Rc<Engine>>,
    ) -> Rc<Engine> {
        #[cfg(feature = "runtime-diagnostics")]
        let mut timings = crate::evaluation_diagnostics::Span::new("evaluate_setup", 0);
        #[cfg(feature = "runtime-diagnostics")]
        timings.enter(EventStage::EvaluateSetup);
        let mut prev: Option<Rc<Engine>> = None;
        let mut edges: HashMap<String, Edge> = HashMap::new();
        // the queried edges each round have been seen before (rounds are
        // deterministic, so a repeat is a cycle that never settles — report at
        // once, not after the full round budget; §7.6)
        let mut seen: HashSet<String> = HashSet::new();
        let mut round = 0;
        let programs = initial
            .as_ref()
            .and_then(|e| e.programs.borrow().clone())
            .or_else(|| incremental.then(|| Rc::new(Programs::default())));
        let query_keys = initial
            .as_ref()
            .map(|eng| eng.query_pool())
            .unwrap_or_default();
        let mut retained = initial;
        let mut cache = incremental
            .then(|| RoundCache::of(env))
            .flatten()
            .map(Rc::new);
        let mut incremental = cache.is_some();

        #[cfg(feature = "runtime-diagnostics")]
        timings.mark("setup");
        #[cfg(feature = "runtime-diagnostics")]
        timings.finish();
        loop {
            round += 1;
            #[cfg(feature = "runtime-diagnostics")]
            let mut timings = crate::evaluation_diagnostics::Span::new("round", round as usize);
            #[cfg(feature = "runtime-diagnostics")]
            timings.enter(EventStage::RoundEngineSetup);
            let reusing = retained.is_some();
            let eng = retained.take().unwrap_or_else(|| {
                let eng = Self::bare_with_queries(env.clone(), query_keys.clone());
                eng.install_hooks(env, false);
                eng
            });
            *eng.programs.borrow_mut() = programs.clone();
            *eng.round_cache.borrow_mut() = cache.clone();
            *eng.revisions.borrow_mut() = cache
                .as_ref()
                .filter(|c| c.revisions.revision.get() > 0)
                .map(|c| c.revisions.clone());
            eng.track.set(track || (incremental && reusing));
            *eng.prev.borrow_mut() = prev.clone();
            let mark = env.diag_len();

            #[cfg(feature = "runtime-diagnostics")]
            timings.mark("engine_setup");
            #[cfg(feature = "runtime-diagnostics")]
            timings.enter(EventStage::RoundBind);
            bind(&eng);
            #[cfg(feature = "runtime-diagnostics")]
            timings.mark("bind");
            #[cfg(feature = "runtime-diagnostics")]
            timings.enter(EventStage::RoundForceRootsInitial);
            eng.force_roots(env);
            #[cfg(feature = "runtime-diagnostics")]
            timings.mark("force_roots_initial");
            #[cfg(feature = "runtime-diagnostics")]
            timings.enter(EventStage::RoundSettle);
            eng.track.set(eng.track.get() || incremental);
            let r = eng.settle(env, edges);
            #[cfg(feature = "runtime-diagnostics")]
            timings.mark("settle");
            #[cfg(feature = "runtime-diagnostics")]
            timings.enter(EventStage::RoundEditsFinish);
            if let Some(edits) = eng.edits.borrow().as_ref() {
                edits.finish(&eng);
            }

            #[cfg(feature = "runtime-diagnostics")]
            timings.mark("edits_finish");
            #[cfg(feature = "runtime-diagnostics")]
            timings.enter(EventStage::RoundEdgeKeyAndCycle);
            let ekey = edges_key(&r.edges);
            let cycled = !r.stable && seen.contains(&ekey);

            #[cfg(feature = "runtime-diagnostics")]
            timings.mark("edge_key_and_cycle");
            if r.stable || cycled || round == Engine::ROUNDS {
                #[cfg(feature = "runtime-diagnostics")]
                timings.enter(EventStage::RoundCompleteDropPrevious);
                if !r.stable {
                    let snap = eng.snap.borrow();
                    let snap_edges = &snap.as_ref().unwrap().edges;
                    for key in &r.changed {
                        let (t, m) = key.split_once('|').unwrap();
                        let empty = Edge::new();
                        env.report(Diag::error(
                            format!(
                                "$referrers({t}, \"{m}\") does not stabilize after {} rounds",
                                Engine::ROUNDS
                            ),
                            edge_diff(&r.edges[key], snap_edges.get(key).unwrap_or(&empty)),
                            Some("E5009"),
                        ));
                    }
                }
                eng.settled.set(true);
                *eng.prev.borrow_mut() = None;
                drop(prev);
                if let Some(cache) = &cache {
                    cache.release_rebased();
                }
                eng.sweep_query_ids();

                #[cfg(feature = "runtime-diagnostics")]
                timings.mark("complete_drop_previous_and_identity_sweep");
                #[cfg(feature = "runtime-diagnostics")]
                timings.finish();
                return eng;
            }
            // the round is the next one's snapshot; the universe starts over
            #[cfg(feature = "runtime-diagnostics")]
            timings.enter(EventStage::RoundAdvance);
            let snapshot = cache.as_ref().and_then(|c| c.advance(&eng, &r.edges));
            #[cfg(feature = "runtime-diagnostics")]
            timings.mark("advance");
            if let Some(snapshot) = snapshot {
                #[cfg(feature = "runtime-diagnostics")]
                timings.enter(EventStage::RoundRetainedTransfer);
                seen.insert(ekey);
                prev = Some(snapshot);
                edges = r.edges;
                retained = Some(eng);

                #[cfg(feature = "runtime-diagnostics")]
                timings.mark("retained_round_transfer");
                #[cfg(feature = "runtime-diagnostics")]
                timings.finish();
                continue;
            }
            #[cfg(feature = "runtime-diagnostics")]
            timings.enter(EventStage::RoundFallbackFreezeReset);
            cache = None;
            incremental = false;
            eng.freeze();
            env.roots_clear();
            env.registry_clear();
            env.diag_truncate(mark);
            for e in eng.const_envs.borrow().iter() {
                for c in e.consts.borrow().values() {
                    c.state.set(false);
                    *c.value.borrow_mut() = Value::Undef;
                }
            }
            seen.insert(ekey);
            prev = Some(eng);
            edges = r.edges;
            #[cfg(feature = "runtime-diagnostics")]
            timings.mark("fallback_freeze_reset");
            #[cfg(feature = "runtime-diagnostics")]
            timings.finish();
        }
    }

    // ---------- binding / checking ----------
    /// Bind a raw value to a type at a path (§9.2): a record instance with its slots,
    /// an array, a map, or a scalar checked against the type.
    pub fn bind(
        &self,
        raw: Value,
        rt: &RT,
        path: &[Seg],
        parent: Option<&Inst>,
        sc: &Scope,
    ) -> R<Value> {
        if let Value::PreVal(pv) = &raw {
            let inst = parent.cloned().or_else(|| pv.scope.inst.clone());
            let sc2 = pv.scope.with_inst(inst);
            if let RTk::Ref(_) = rt.k {
                return match self.eval_place(&pv.expr, &sc2)? {
                    Some(p) => {
                        // reference integrity (§7.5): the place must hold a value
                        if self.resolve_segs(&p)?.is_undef() {
                            self.env.report(Diag::error(
                                format!("dangling reference {}", path_str(&p, None)),
                                path_str(path, None),
                                Some("E6002"),
                            ));
                            return Err(Fail::Taint);
                        }
                        Ok(Value::Ref(Rc::new(p)))
                    }
                    None => err("not a place in ref position"),
                };
            }
            let v = self.ev(&pv.expr, &sc2)?;
            return self.bind(v, rt, path, parent, sc);
        }
        let fail = |msg: String, code: Option<&str>| -> Fail {
            let tail = rt.tail.borrow();
            match &*tail {
                Some(Tail::Inline { template, .. }) => {
                    let text: String = template
                        .iter()
                        .filter_map(|p| {
                            if let TPart::Text(t) = p {
                                Some(t.as_str())
                            } else {
                                None
                            }
                        })
                        .collect();
                    self.env.report(Diag {
                        severity: "error".into(),
                        id: rt.name.borrow().clone(),
                        message: text,
                        path: path_str(path, None),
                        code: Some("E4001".into()),
                        loc: None,
                        by: None,
                    });
                }
                _ => self.env.report(Diag::error(
                    msg,
                    path_str(path, None),
                    Some(code.unwrap_or("E4001")),
                )),
            }
            Fail::Taint
        };
        match &rt.k {
            RTk::Prim(n) => match (n.as_str(), &raw) {
                ("int", Value::Int(_))
                | ("float", Value::Float(_))
                | ("bool", Value::Bool(_))
                | ("string", Value::Str(_))
                | ("null", Value::Null) => Ok(raw),
                ("float", Value::Int(i)) => match exact_float(i) {
                    Some(f) => Ok(Value::Float(f)),
                    None => Err(fail(format!("expected {n}"), None)),
                },
                _ => Err(fail(format!("expected {n}"), None)),
            },
            RTk::Lit(v) => {
                if value_eq(&raw, v) {
                    Ok(raw)
                } else {
                    Err(fail(
                        format!("expected {}", json_str(&lit_display(v))),
                        None,
                    ))
                }
            }
            RTk::Range { lo, hi, excl, base } => {
                let raw = match (&raw, base.as_str()) {
                    (Value::Int(i), "float") => match exact_float(i) {
                        Some(f) => Value::Float(f),
                        None => raw,
                    },
                    _ => raw,
                };
                let ok = if base == "int" {
                    matches!(raw, Value::Int(_))
                } else {
                    matches!(raw, Value::Float(_))
                };
                if !ok {
                    return Err(fail(format!("expected {base} in range"), None));
                }
                let hi_ok = if *excl {
                    num_cmp(&raw, hi) == Some(Less)
                } else {
                    matches!(num_cmp(&raw, hi), Some(Less | Equal))
                };
                if matches!(num_cmp(&raw, lo), Some(Greater | Equal)) && hi_ok {
                    return Ok(raw);
                }
                Err(fail(
                    format!(
                        "out of range {}..{}{}",
                        num_s(lo),
                        if *excl { "<" } else { "" },
                        num_s(hi)
                    ),
                    None,
                ))
            }
            RTk::Pattern { src, re } => match &raw {
                Value::Str(s) if re.is_match(s) => Ok(raw),
                _ => Err(fail(format!("does not match /{src}/"), None)),
            },
            RTk::Quantity(dim) => {
                if let Value::Q(q) = &raw {
                    if q.dim.as_str() == dim.as_str() {
                        return Ok(raw);
                    }
                }
                if let Value::JObj(es) = &raw {
                    if es.len() == 2 {
                        let v = es.iter().find(|(k, _)| k == "value").map(|(_, v)| v);
                        let u = es.iter().find(|(k, _)| k == "unit").map(|(_, v)| v);
                        if let (Some(v), Some(Value::Str(u))) = (v, u) {
                            let Ok((key, to_base)) = self.env.unit_info(u) else {
                                return Err(fail(format!("unknown unit {u}"), Some("E4073")));
                            };
                            if key != *dim {
                                return Err(fail("unit of wrong dimension".into(), Some("E4073")));
                            }
                            let f = match v {
                                Value::Int(i) => i.to_f64().unwrap_or(f64::INFINITY),
                                Value::Float(f) => *f,
                                _ => return Err(fail("expected quantity".into(), None)),
                            };
                            return Ok(Value::quantity(dim.clone(), f * to_base));
                        }
                    }
                }
                Err(fail("expected quantity".into(), None))
            }
            RTk::Ref(_) => match &raw {
                Value::Ref(_) => Ok(raw),
                Value::Str(s) => {
                    let segs = parse_path(s, &sc.root_name)?;
                    if self.resolve_canonical(&segs)?.is_undef() {
                        return Err(fail(format!("dangling reference {s}"), Some("E6002")));
                    }
                    Ok(Value::Ref(Rc::new(segs)))
                }
                Value::Rec(_) | Value::Arr(_) | Value::Map(_) => {
                    Ok(Value::Ref(Rc::new(raw.place().unwrap())))
                }
                _ => Err(fail("expected reference path".into(), None)),
            },
            RTk::Arr { elem, lo, hi } => {
                let items = match &raw {
                    Value::PreArr(pa) => {
                        let mut items = vec![];
                        for (spread, v) in pa.iter() {
                            if *spread {
                                let s = match v {
                                    Value::PreVal(pv) => {
                                        self.deref(self.ev(&pv.expr, &pv.scope)?)?
                                    }
                                    other => self.deref(other.clone())?,
                                };
                                items.extend(self.mat_arr(&s)?);
                            } else {
                                items.push(v.clone());
                            }
                        }
                        BindingInput::Owned(items.into_iter())
                    }
                    Value::JArr(a) => BindingInput::Borrowed(a.iter()),
                    Value::Arr(a) => BindingInput::Owned(a.borrow().items.clone().into_iter()),
                    _ => return Err(fail("expected array".into(), None)),
                };
                if let Some(lo) = lo {
                    let n = items.len() as i64;
                    let h = hi.unwrap_or(i64::MAX);
                    if n < *lo || n > h {
                        return Err(fail(format!("array size {n} outside {lo}..{h}"), None));
                    }
                }
                #[cfg(feature = "runtime-diagnostics")]
                let diagnostic_array = crate::retention_diagnostics::ArrayAttempt::start(
                    crate::retention_diagnostics::ArraySite::Bind,
                    Some(items.len()),
                );
                let arr = Rc::new(RefCell::new(ArrV {
                    items: Vec::with_capacity(items.len()),
                    path: self.container_path(path),
                }));
                // Bound containers own their paths. Reuse only this call's
                // temporary flat buffer, allocating it at the first child.
                let mut child_path = None;
                for (i, it) in items.enumerate() {
                    let p = child_path.get_or_insert_with(|| {
                        let mut p = Vec::with_capacity(path.len() + 1);
                        p.extend_from_slice(path);
                        p
                    });
                    p.push(Seg::Idx(i));
                    let bound = self.bind(it, elem, p, parent, sc);
                    p.pop();
                    match bound {
                        Ok(v) => arr.borrow_mut().items.push(v),
                        Err(Fail::Taint) => arr.borrow_mut().items.push(Value::Absent),
                        Err(e) => return Err(e),
                    }
                }
                #[cfg(feature = "runtime-diagnostics")]
                {
                    let a = arr.borrow();
                    diagnostic_array.finish(a.items.len(), a.items.capacity());
                }
                Ok(Value::Arr(arr))
            }
            RTk::Map { key, val } => {
                let es = match &raw {
                    Value::JObj(e) => BindingInput::Borrowed(e.iter()),
                    Value::PreObj(e) => BindingInput::Owned(self.entries_of(e)?.into_iter()),
                    Value::Map(m) => BindingInput::Owned(
                        m.borrow()
                            .entries
                            .iter()
                            .map(|(k, v)| (k.clone(), v.clone()))
                            .collect::<Vec<_>>()
                            .into_iter(),
                    ),
                    // a record binds to a map as its value entries (§3.18)
                    Value::Rec(_) => {
                        BindingInput::Owned(self.spread_entries(raw.clone())?.into_iter())
                    }
                    _ => return Err(fail("expected map".into(), None)),
                };
                let m = Rc::new(RefCell::new(MapV {
                    entries: MapEntries::building(),
                    path: self.container_path(path),
                }));
                let mut child_path = None;
                for (k, v) in es {
                    // Only a key that may be rejected is given a text value to
                    // bind; an accepted `string` or pattern key binds to itself
                    // with no report, and that result was always discarded.
                    if !key_accepts_text(key, &k) {
                        match self.bind(
                            Value::Str(SharedText::from_rc(Rc::from(k.as_str()))),
                            key,
                            path,
                            parent,
                            sc,
                        ) {
                            Ok(_) => {}
                            Err(Fail::Taint) => continue,
                            Err(e) => return Err(e),
                        }
                    }
                    // Rejected keys need no child path. Remove each accepted
                    // key before validating the next one, including on taint.
                    let p = child_path.get_or_insert_with(|| {
                        let mut p = Vec::with_capacity(path.len() + 1);
                        p.extend_from_slice(path);
                        p
                    });
                    p.push(Seg::Key(Rc::from(k.as_str())));
                    let bound = self.bind(v, val, p, parent, sc);
                    p.pop();
                    match bound {
                        Ok(bv) => m.borrow_mut().set(k, bv),
                        Err(Fail::Taint) => {}
                        Err(e) => return Err(e),
                    }
                }
                self.map_shapes
                    .borrow_mut()
                    .seal(&mut m.borrow_mut().entries);
                Ok(Value::Map(m))
            }
            RTk::Union(arms) => {
                // a literal's entry: its value decides the arm
                let raw = match raw {
                    Value::PreVal(pv) => self.ev(&pv.expr, &pv.scope)?,
                    other => other,
                };
                let arms = arms.borrow();
                let leaves: Vec<RT> = arms.iter().flat_map(leaf_recs).collect();
                if matches!(
                    raw,
                    Value::JObj(_) | Value::PreObj(_) | Value::Rec(_) | Value::Map(_)
                ) && !leaves.is_empty()
                {
                    // record arms discriminate hierarchically (§3.12): the union
                    // is flattened to its leaf records (a union arm contributes
                    // its own leaves — unions are associative), and the value is
                    // routed to a unique leaf, one discriminant member at a time
                    fn lit_set(m: Option<&Member>) -> Option<Vec<Value>> {
                        m.and_then(|x| x.ty.clone()).and_then(|t| match &t.k {
                            RTk::Lit(v) => Some(vec![v.clone()]),
                            RTk::Union(a) => {
                                let a = a.borrow();
                                if a.iter().all(|x| matches!(&x.k, RTk::Lit(_))) {
                                    Some(
                                        a.iter()
                                            .filter_map(|x| match &x.k {
                                                RTk::Lit(v) => Some(v.clone()),
                                                _ => None,
                                            })
                                            .collect(),
                                    )
                                } else {
                                    None
                                }
                            }
                            _ => None,
                        })
                    }
                    let set_of = |leaf: &RT, dn: &str| -> Option<Vec<Value>> {
                        lit_set(rec_members(leaf).iter().find(|x| x.name == dn))
                    };
                    // route: a discriminant the value supplies narrows the
                    // candidates; a leaf whose set holds the value stays, and a
                    // member the value omits (it has a default) is skipped
                    let mut cands: Vec<RT> = leaves.clone();
                    while cands.len() > 1 {
                        let names: Vec<String> = rec_members(&cands[0])
                            .iter()
                            .map(|m| m.name.clone())
                            .filter(|n| cands.iter().all(|l| set_of(l, n).is_some()))
                            .collect();
                        let mut narrowed = false;
                        for n in &names {
                            if let Some(mv) = self.raw_entry(&raw, n)? {
                                let lv = self.raw_lit(&mv)?;
                                let kept: Vec<RT> = cands
                                    .iter()
                                    .filter(|l| {
                                        set_of(l, n)
                                            .unwrap_or_default()
                                            .iter()
                                            .any(|v| value_eq(&lv, v))
                                    })
                                    .cloned()
                                    .collect();
                                if !kept.is_empty() && kept.len() < cands.len() {
                                    cands = kept;
                                    narrowed = true;
                                    break;
                                }
                            }
                        }
                        if !narrowed {
                            break;
                        }
                    }
                    if cands.len() == 1 {
                        return self.bind(raw, &cands[0], path, parent, sc);
                    }
                    return Err(fail("no union arm matches discriminant".into(), None));
                }
                for arm in arms.iter() {
                    if self.kind_matches(&raw, arm)? {
                        return self.bind(raw, arm, path, parent, sc);
                    }
                }
                Err(fail("no union arm matches".into(), None))
            }
            RTk::Rec(_) => self.bind_record(raw, rt, path, parent, sc),
            RTk::Pred { base, preds } => {
                let v = self.bind(raw, base, path, parent, sc)?;
                for p in preds {
                    let f = self.ev(p, &Scope::new(&sc.root_name, sc.menv.clone()))?;
                    let ok = matches!(self.call(&f, vec![v.clone()], sc), Ok(Value::Bool(true)));
                    if !ok {
                        return Err(fail(
                            format!("predicate {} not satisfied", json_str(&expr_name(p))),
                            None,
                        ));
                    }
                }
                Ok(v)
            }
            RTk::IsectN(arms) => {
                let mut v = raw.clone();
                for arm in arms {
                    v = self.bind(raw.clone(), arm, path, parent, sc)?;
                }
                Ok(v)
            }
            RTk::Any => Ok(raw),
            RTk::Func { .. } => match &raw {
                Value::Clo(_) | Value::Nat(_) | Value::Std(_) => Ok(raw),
                _ => Err(fail("expected function".into(), None)),
            },
        }
    }

    fn raw_entry(&self, raw: &Value, name: &str) -> R<Option<Value>> {
        match raw {
            Value::JObj(es) => Ok(es.iter().find(|(k, _)| k == name).map(|(_, v)| v.clone())),
            Value::PreObj(es) => Ok(self
                .entries_of(es)?
                .into_iter()
                .find(|(k, _)| k == name)
                .map(|(_, v)| v)),
            Value::Map(m) => Ok(m.borrow().get(name).cloned()),
            Value::Rec(r) => {
                if r.borrow().has_slot(name) {
                    Ok(Some(self.force_slot(r, name)?))
                } else {
                    Ok(None)
                }
            }
            _ => Ok(None),
        }
    }

    fn raw_lit(&self, v: &Value) -> R<Value> {
        match v {
            Value::PreVal(pv) => self.ev(&pv.expr, &pv.scope),
            other => Ok(other.clone()),
        }
    }

    fn kind_matches(&self, raw: &Value, rt: &RT) -> R<bool> {
        Ok(match &rt.k {
            RTk::Prim(n) => matches!(
                (n.as_str(), raw),
                ("int", Value::Int(_))
                    | ("float", Value::Float(_))
                    | ("bool", Value::Bool(_))
                    | ("string", Value::Str(_))
                    | ("null", Value::Null)
            ),
            RTk::Lit(v) => value_eq(&self.raw_lit(raw)?, v),
            RTk::Range { base, .. } => {
                if base == "int" {
                    matches!(raw, Value::Int(_))
                } else {
                    matches!(raw, Value::Float(_))
                }
            }
            RTk::Pattern { .. } => matches!(raw, Value::Str(_)),
            RTk::Arr { .. } => matches!(raw, Value::JArr(_) | Value::PreArr(_) | Value::Arr(_)),
            _ => true,
        })
    }

    /// Evaluate an expression as a place — a canonical path — where a reference is
    /// expected (§7.4); none when it names no place.
    pub fn eval_place(&self, e: &Rc<Expr>, sc: &Scope) -> R<Option<SegPath>> {
        let v = self.ev_nav(e, sc)?;
        Ok(match &v {
            Value::Segs(p) => Some((**p).clone()),
            Value::Ref(p) => Some((**p).clone()), // $this / $parent / $root, or a reference read through
            Value::Rec(_) | Value::Arr(_) | Value::Map(_) => v.place(),
            _ => None,
        })
    }

    fn ev_nav(&self, e: &Rc<Expr>, sc: &Scope) -> R<Value> {
        let programs = self.programs.borrow().clone();
        if let Some(p) = programs {
            return p.nav(e)(self, sc);
        }
        match &**e {
            // a conditional in a ref position chooses between places (§7.4):
            // only the taken branch is navigated
            Expr::If { c, t, f } => {
                if self.truthy(&self.ev(c, sc)?)? {
                    self.ev_nav(t, sc)
                } else {
                    self.ev_nav(f, sc)
                }
            }
            Expr::Paren(x) => self.ev_nav(x, sc),
            // a step past a missing place (an absent optional member, a key or
            // index that is not there) is still a place: the chain keeps naming
            // the location, and reference integrity (§7.5) judges it when the
            // reference is bound. `?.` is an ordinary step here — a navigation in
            // a ref position denotes the place regardless of maybe-absent steps
            Expr::Member { x, name, .. } => {
                let x0 = self.ev_nav(x, sc)?;
                if let Value::Segs(p) = &x0 {
                    let mut p = (**p).clone();
                    p.push(Seg::Name(Rc::from(name.as_str())));
                    return Ok(Value::Segs(Rc::new(p)));
                }
                let x = self.deref(x0)?;
                let v = self.access(&x, name)?;
                if v.is_absent() {
                    if let Value::Rec(r) = &x {
                        let mut p = r.borrow().path.to_vec();
                        p.push(Seg::Name(Rc::from(name.as_str())));
                        return Ok(Value::Segs(Rc::new(p)));
                    }
                }
                Ok(v)
            }
            Expr::Index { x, i } => {
                let x0 = self.ev_nav(x, sc)?;
                let i = self.ev(i, sc)?;
                if let Value::Segs(p) = &x0 {
                    let mut p = (**p).clone();
                    // past a missing place a string index can only be a map key (bracket
                    // access to a dot-spellable member is a compile error, §4.3)
                    match &i {
                        Value::Str(k) => p.push(Seg::Key(k.to_rc())),
                        _ => p.push(Seg::Idx(to_index(&i)?.max(0) as usize)),
                    }
                    return Ok(Value::Segs(Rc::new(p)));
                }
                let x = self.deref(x0)?;
                match &x {
                    Value::Arr(a) => {
                        let n = to_index(&i)?;
                        let b = a.borrow();
                        if n >= 0 && (n as usize) < b.items.len() {
                            Ok(b.items[n as usize].clone())
                        } else {
                            let mut p = b.path.to_vec();
                            p.push(Seg::Idx(n.max(0) as usize));
                            Ok(Value::Segs(Rc::new(p)))
                        }
                    }
                    Value::Map(m) => {
                        let Value::Str(k) = &i else {
                            return err("map index needs a string");
                        };
                        let b = m.borrow();
                        match b.get(k) {
                            Some(v) => Ok(v.clone()),
                            None => {
                                let mut p = b.path.to_vec();
                                p.push(Seg::Key(k.to_rc()));
                                Ok(Value::Segs(Rc::new(p)))
                            }
                        }
                    }
                    Value::Rec(r) => {
                        let Value::Str(k) = &i else {
                            return err("index on record needs a string");
                        };
                        let v = self.access(&x, k)?;
                        if v.is_absent() {
                            let mut p = r.borrow().path.to_vec();
                            p.push(Seg::Name(k.to_rc()));
                            Ok(Value::Segs(Rc::new(p)))
                        } else {
                            Ok(v)
                        }
                    }
                    _ => self.ev(e, sc),
                }
            }
            _ => self.ev(e, sc),
        }
    }

    fn bind_record(
        &self,
        raw: Value,
        rt: &RT,
        path: &[Seg],
        parent: Option<&Inst>,
        sc: &Scope,
    ) -> R<Value> {
        let RTk::Rec(rec) = &rt.k else {
            return err("bind_record on non-record type");
        };
        // Record binding revisits this ordered sequence for reuse, slots and
        // extras. Immutable input stays owned by `raw`; other inputs retain
        // their eager snapshots across diagnostic callbacks and reentry.
        let entries: Cow<'_, [(String, Value)]> = match &raw {
            Value::JObj(e) => Cow::Borrowed(e.as_slice()),
            Value::PreObj(e) => Cow::Owned(self.entries_of(e)?),
            // a literal no record type claimed became a map; its entries bind like a document's
            Value::Map(m) => Cow::Owned(
                m.borrow()
                    .entries
                    .iter()
                    .map(|(k, v)| (k.clone(), v.clone()))
                    .collect(),
            ),
            Value::Rec(r) => {
                let (order, extras, ders) = {
                    let b = r.borrow();
                    (
                        b.entry_order.clone(),
                        b.extras.clone(),
                        b.slots
                            .iter()
                            .filter(|(_, s)| s.kind == MKind::Der)
                            .map(|(n, _)| n.clone())
                            .collect::<Vec<_>>(),
                    )
                };
                let mut out = vec![];
                for n in order.iter().cloned() {
                    if ders.iter().any(|name| name.as_ref() == n) {
                        continue;
                    }
                    if let Some((_, v)) = extras.iter().find(|(k, _)| *k == n) {
                        out.push((n, v.clone()));
                    } else {
                        let v = self.force_slot(r, &n)?;
                        out.push((n, v));
                    }
                }
                Cow::Owned(out)
            }
            _ => {
                self.env.report(Diag::error(
                    "expected record",
                    path_str(path, None),
                    Some("E4001"),
                ));
                return Err(Fail::Taint);
            }
        };
        let members = rec.members.borrow().clone();
        let edits = self.edits.borrow().clone();
        let previous = edits
            .as_ref()
            .filter(|_| self.no_reg.get() == 0)
            .and_then(|e| e.record(rt, path, parent));
        if let (Some(previous), Some(edits)) = (&previous, &edits) {
            if edits.unchanged(previous, &entries) {
                edits.activate(self, &Value::Rec(previous.clone()));
                return Ok(Value::Rec(previous.clone()));
            }
        }
        // A literal's undeclared members on an open record are values like any
        // other (§3.11): evaluated and materialized before the instance exists,
        // so a failing one fails the binding and leaves nothing half-bound. A
        // document's are values already and pass through as they are; so does
        // whatever a native caller put in one, which stays as lazy as it came.
        let mut literal_extras: Vec<(&String, Value)> = vec![];
        if rec.open.get() && matches!(raw, Value::PreObj(_)) {
            for (k, v) in entries.iter() {
                let Value::PreVal(pv) = v else { continue };
                if members.iter().any(|m| m.name == *k) {
                    continue;
                }
                let value = self
                    .ev(&pv.expr, &pv.scope)
                    .and_then(|value| self.mat_val(value));
                match value {
                    Ok(value) => literal_extras.push((k, value)),
                    // reported where a declared member's failure is: at the member
                    Err(Fail::Eval(e)) => {
                        let mut p = path.to_vec();
                        p.push(Seg::Name(Rc::from(k.as_str())));
                        self.env.report(Diag {
                            severity: "error".into(),
                            id: None,
                            message: e.msg,
                            path: path_str(&p, None),
                            code: e.code,
                            loc: None,
                            by: None,
                        });
                        return Err(Fail::Taint);
                    }
                    Err(other) => return Err(other),
                }
            }
        }
        // This captures only ordered key text, never input Values. Looking up an
        // already compiled schema does not move compilation across registration
        // callbacks or change the captured member sequence.
        let entry_order = self
            .programs
            .borrow()
            .as_ref()
            .map(|programs| programs.entry_order(rt, &entries))
            .unwrap_or_else(|| Rc::new(entries.iter().map(|(key, _)| key.clone()).collect()));
        let old_slots = previous
            .as_ref()
            .map(|i| std::mem::take(&mut i.borrow_mut().slots))
            .unwrap_or_default();
        let inst = previous.unwrap_or_else(|| {
            record_instance(RecInst {
                ps: RefCell::new(None),
                type_name: rt.name.borrow().clone(),
                rt: rt.clone(),
                path: Rc::new(path.to_vec()),
                parent: parent.cloned(),
                slots: vec![],
                entry_order: entry_order.clone(),
                extras: vec![],
                menv: sc.menv.clone(),
            })
        });
        {
            let mut b = inst.borrow_mut();
            b.slots.clear();
            // Every schema member contributes one slot, including absent and
            // invalid members. Rebinding took the old vector for Edits::bound.
            b.slots.reserve_exact(members.len());
            b.extras.clear();
            b.entry_order = entry_order;
            b.menv = sc.menv.clone();
        }
        if self.no_reg.get() == 0 {
            if let Some(edits) = edits.as_ref().filter(|e| e.active.get()) {
                edits.register(self, &inst);
            } else {
                self.env.registry_push(inst.clone());
            }
        }
        let schema = self.programs.borrow().as_ref().map(|p| p.schema(rt));
        let supplied = RecordLookup::new(&entries, members.len(), schema.as_deref());
        for (index, m) in members.iter().enumerate() {
            let plan = schema.as_ref().map(|s| &s.members[index]);
            let name = plan
                .map(|p| p.name.clone())
                .unwrap_or_else(|| Rc::from(m.name.as_str()));
            let types = plan.map(|p| p.types.clone()).unwrap_or_else(|| {
                Rc::new(
                    m.conj
                        .clone()
                        .unwrap_or_else(|| m.ty.iter().cloned().collect()),
                )
            });
            let menv = m.menv.clone().or_else(|| sc.menv.clone());
            let root_name = sc.root_name.clone();
            let has = supplied.get(index, name.as_ref()).cloned();
            let mut push_deferred = false;
            // a hidden member (D34) is never part of the value: a document or
            // literal that supplies it is in error — there is nothing to restate
            if m.kind == MKind::Der && m.hidden && has.is_some() {
                let mut p = path.to_vec();
                p.push(Seg::Name(name.clone()));
                self.env.report(Diag::error(
                    format!("hidden member {name} supplied"),
                    path_str(&p, None),
                    Some("E4006"),
                ));
                inst.borrow_mut().slots.push((
                    name.clone(),
                    Slot {
                        kind: MKind::Der,
                        hidden: true,
                        state: SlotState::Invalid,
                        value: Value::Undef,
                        compute: None,
                    },
                ));
                continue;
            }
            let slot = match (m.kind, has) {
                (MKind::Der, has) => {
                    let expr = m
                        .expr
                        .clone()
                        .unwrap_or_else(|| Rc::new(Expr::Lit(Value::Null)));
                    // $referrers needs the whole universe: schedule for phase 2 up front
                    push_deferred = plan
                        .map(|p| p.deferred)
                        .unwrap_or_else(|| mentions_referrers(&expr));
                    let reusable = plan.filter(|_| has.is_none());
                    let create = |root_name, menv| Compute::Derived {
                        expr,
                        op: plan.and_then(|p| p.expression.clone()),
                        ty: m.ty.clone(),
                        supplied: has,
                        name: name.clone(),
                        root_name,
                        menv,
                    };
                    let compute = match reusable {
                        Some(plan) => plan.reusable_compute(MKind::Der, root_name, menv, create),
                        None => Rc::new(create(root_name, menv)),
                    };
                    Slot {
                        kind: MKind::Der,
                        hidden: m.hidden,
                        state: SlotState::Unforced,
                        value: Value::Undef,
                        compute: Some(compute),
                    }
                }
                (kind, Some(raw_v)) => Slot {
                    kind,
                    hidden: false,
                    state: SlotState::Unforced,
                    value: Value::Undef,
                    compute: Some(Rc::new(Compute::Check {
                        raw: raw_v,
                        types,
                        name: name.clone(),
                        root_name,
                        menv,
                    })),
                },
                (MKind::Dflt, None) => {
                    let expr = m
                        .dflt
                        .clone()
                        .unwrap_or_else(|| Rc::new(Expr::Lit(Value::Null)));
                    let create = |root_name, menv| Compute::Default {
                        expr,
                        op: plan.and_then(|p| p.fallback.clone()),
                        types,
                        name: name.clone(),
                        root_name,
                        menv,
                    };
                    let compute = match plan {
                        Some(plan) => plan.reusable_compute(MKind::Dflt, root_name, menv, create),
                        None => Rc::new(create(root_name, menv)),
                    };
                    Slot {
                        kind: MKind::Dflt,
                        hidden: false,
                        state: SlotState::Unforced,
                        value: Value::Undef,
                        compute: Some(compute),
                    }
                }
                (MKind::Opt, None) => Slot {
                    kind: MKind::Opt,
                    hidden: false,
                    state: SlotState::Absent,
                    value: Value::Undef,
                    compute: None,
                },
                (MKind::Req, None) => {
                    let mut p = path.to_vec();
                    p.push(Seg::Name(name.clone()));
                    self.env.report(Diag::error(
                        format!("required member {name} missing"),
                        path_str(&p, None),
                        Some("E4002"),
                    ));
                    Slot {
                        kind: MKind::Req,
                        hidden: false,
                        state: SlotState::Invalid,
                        value: Value::Undef,
                        compute: None,
                    }
                }
            };
            inst.borrow_mut().slots.push((name.clone(), slot));
            if push_deferred {
                self.deferred_slots
                    .borrow_mut()
                    .push((inst.clone(), name.to_string()));
            }
        }
        for (k, v) in entries.iter() {
            if schema
                .as_ref()
                .map(|s| s.names.contains_key(k.as_str()))
                .unwrap_or_else(|| members.iter().any(|m| m.name == *k))
            {
                continue;
            }
            if rec.open.get() {
                let value = literal_extras
                    .iter()
                    .find(|(name, _)| *name == k)
                    .map_or_else(|| v.clone(), |(_, value)| value.clone());
                inst.borrow_mut().set_extra(k, value);
            } else {
                let nm = rt
                    .name
                    .borrow()
                    .as_ref()
                    .map(|n| format!(" {n}"))
                    .unwrap_or_default();
                let mut p = path.to_vec();
                p.push(Seg::Name(Rc::from(k.as_str())));
                self.env.report(Diag::error(
                    format!("undeclared member {k} on closed record{nm}"),
                    path_str(&p, None),
                    Some("E4003"),
                ));
            }
        }
        if self.no_reg.get() == 0 {
            if let Some(edits) = &edits {
                edits.bound(self, &inst, &entries, old_slots);
            }
        }
        Ok(Value::Rec(inst))
    }

    fn run_compute(&self, inst: &Inst, c: &Compute) -> R<Value> {
        let path = inst.borrow().path.clone();
        let scope_for = |root_name: &Rc<str>, menv: &Option<Rc<Env>>| Scope {
            inst: Some(inst.clone()),
            locals: Locals::new(),
            root_name: root_name.clone(),
            menv: menv.clone(),
        };
        let member_path = |name: &str| {
            let mut p = path.to_vec();
            p.push(Seg::Name(Rc::from(name)));
            p
        };
        match c {
            Compute::Check {
                raw,
                types,
                name,
                root_name,
                menv,
            } => {
                let isc = scope_for(root_name, menv);
                let mp = member_path(name);
                let mut v = Value::Null;
                for t in types.iter() {
                    v = self.bind(raw.clone(), t, &mp, Some(inst), &isc)?;
                }
                Ok(v)
            }
            Compute::Default {
                expr,
                op,
                types,
                name,
                root_name,
                menv,
            } => {
                let isc = scope_for(root_name, menv);
                let mp = member_path(name);
                if types.len() == 1 && matches!(types[0].k, RTk::Ref(_)) {
                    let pv = Value::PreVal(Rc::new(PreValV {
                        expr: {
                            #[cfg(feature = "runtime-diagnostics")]
                            crate::retention_diagnostics::preval(3);
                            expr.clone()
                        },
                        scope: isc.clone(),
                    }));
                    return self.bind(pv, &types[0], &mp, Some(inst), &isc);
                }
                let v = match op {
                    Some(op) => op(self, &isc)?,
                    None => self.ev(expr, &isc)?,
                };
                let mut out = Value::Null;
                for t in types.iter() {
                    out = self.bind(v.clone(), t, &mp, Some(inst), &isc)?;
                }
                Ok(out)
            }
            Compute::Derived {
                expr,
                op,
                ty: t,
                supplied,
                name,
                root_name,
                menv,
            } => {
                let isc = scope_for(root_name, menv);
                let mp = member_path(name);
                // a member declared `ref<T>` holds a navigation (§7.4): the
                // expression names a place, and is bound as one
                let mut v = match t {
                    Some(t) if matches!(t.k, RTk::Ref(_)) => {
                        let pv = Value::PreVal(Rc::new(PreValV {
                            expr: {
                                #[cfg(feature = "runtime-diagnostics")]
                                crate::retention_diagnostics::preval(4);
                                expr.clone()
                            },
                            scope: isc.clone(),
                        }));
                        self.bind(pv, t, &mp, Some(inst), &isc)?
                    }
                    _ => match op {
                        Some(op) => op(self, &isc)?,
                        None => self.ev(expr, &isc)?,
                    },
                };
                if let Some(t) = t {
                    if !matches!(t.k, RTk::Ref(_)) {
                        v = self.bind(v, t, &mp, Some(inst), &isc)?;
                    }
                } else if matches!(v, Value::PreObj(_) | Value::PreArr(_) | Value::JObj(_)) {
                    v = self.materialize(v, &mp)?;
                }
                if let Some(sv) = supplied {
                    let against = t.clone().unwrap_or_else(|| structural_of(&v));
                    self.no_reg.set(self.no_reg.get() + 1);
                    let restated = self.bind(sv.clone(), &against, &mp, Some(inst), &isc);
                    self.no_reg.set(self.no_reg.get() - 1);
                    let restated = restated?;
                    if !self.equal_values(&v, &restated) {
                        self.env.report(Diag::error(
                            format!("derived member {name} restated with a differing value"),
                            path_str(&mp, None),
                            Some("E4005"),
                        ));
                        return Err(Fail::Taint);
                    }
                }
                Ok(v)
            }
            Compute::Bridge(f) => f(),
        }
    }

    /// Force a value whole, recursively, so it can be serialized or compared.
    pub fn materialize(&self, v: Value, path: &[Seg]) -> R<Value> {
        match v {
            Value::PreArr(items) => {
                // collect the flat items iteratively: a spread of an
                // unmaterialized array is walked with an explicit stack, not
                // host recursion, so a fold-with-spread chain of any depth
                // flattens without exhausting the stack (§4.2, §9.4)
                let mut raw: Vec<Value> = vec![];
                let mut stack: Vec<(Rc<Vec<(bool, Value)>>, usize)> = vec![(items, 0)];
                while !stack.is_empty() {
                    let last = stack.len() - 1;
                    let entry = {
                        let (fitems, idx) = &mut stack[last];
                        if *idx >= fitems.len() {
                            None
                        } else {
                            let e = fitems[*idx].clone();
                            *idx += 1;
                            Some(e)
                        }
                    };
                    let Some((spread, it)) = entry else {
                        stack.pop();
                        continue;
                    };
                    let x = match &it {
                        Value::PreVal(pv) => self.ev(&pv.expr, &pv.scope)?,
                        other => other.clone(),
                    };
                    if spread {
                        let d = self.deref(x)?;
                        if let Value::PreArr(inner) = d {
                            stack.push((inner, 0));
                        } else {
                            for y in self.mat_arr(&d)? {
                                raw.push(y);
                            }
                        }
                    } else {
                        raw.push(x);
                    }
                }
                #[cfg(feature = "runtime-diagnostics")]
                let diagnostic_array = crate::retention_diagnostics::ArrayAttempt::start(
                    crate::retention_diagnostics::ArraySite::Materialize,
                    Some(raw.len()),
                );
                let arr = Rc::new(RefCell::new(ArrV {
                    items: Vec::with_capacity(raw.len()),
                    path: self.container_path(path),
                }));
                for (i, y) in raw.into_iter().enumerate() {
                    let mut p = path.to_vec();
                    p.push(Seg::Idx(i));
                    let m = self.materialize(y, &p)?;
                    arr.borrow_mut().items.push(m);
                }
                #[cfg(feature = "runtime-diagnostics")]
                {
                    let a = arr.borrow();
                    diagnostic_array.finish(a.items.len(), a.items.capacity());
                }
                Ok(Value::Arr(arr))
            }
            Value::PreObj(entries) => {
                let m = Rc::new(RefCell::new(MapV {
                    entries: MapEntries::building(),
                    path: self.container_path(path),
                }));
                for (k, pv) in self.entries_of(&entries)?.iter() {
                    let x = match pv {
                        Value::PreVal(pv) => self.ev(&pv.expr, &pv.scope)?,
                        other => other.clone(),
                    };
                    let mut p = path.to_vec();
                    p.push(Seg::Key(Rc::from(k.as_str())));
                    let mv = self.materialize(x, &p)?;
                    m.borrow_mut().set(k.clone(), mv);
                }
                self.map_shapes
                    .borrow_mut()
                    .seal(&mut m.borrow_mut().entries);
                Ok(Value::Map(m))
            }
            other => Ok(other),
        }
    }

    fn with_expr(&self, base: &Rc<Expr>, patch: &Rc<Expr>, sc: &Scope) -> R<Value> {
        let base = self.deref(self.ev(base, sc)?)?;
        if !matches!(base, Value::PreObj(_) | Value::Map(_) | Value::Rec(_)) {
            return err("with on non-record");
        }
        self.with_value(base, self.ev(patch, sc)?)
    }

    pub(crate) fn with_value(&self, base: Value, p: Value) -> R<Value> {
        let merge = |entries: &mut Vec<(String, Value)>, patch: Value| -> R<()> {
            let Value::PreObj(pes) = patch else {
                return err("with: patch must be an object");
            };
            for (pk, pv) in self.entries_of(&pes)? {
                if let Some(e) = entries.iter_mut().find(|(n, _)| *n == pk) {
                    e.1 = pv;
                } else {
                    entries.push((pk, pv));
                }
            }
            Ok(())
        };
        if let Value::PreObj(bes) = &base {
            let mut entries = self.entries_of(bes)?;
            merge(&mut entries, p)?;
            return Ok(Value::PreObj(Rc::new(entries)));
        }
        if let Value::Map(m) = &base {
            // a literal no record type claimed: its entries, updated, still unbound
            let mut entries = m
                .borrow()
                .entries
                .iter()
                .map(|(k, v)| (k.clone(), v.clone()))
                .collect();
            merge(&mut entries, p)?;
            return Ok(Value::PreObj(Rc::new(entries)));
        }
        let Value::Rec(r) = &base else {
            return err("with on non-record");
        };
        let (order, members) = {
            let b = r.borrow();
            (b.entry_order.clone(), rec_members(&b.rt))
        };
        let mut entries: Vec<(String, Value)> = vec![];
        for n in order.iter().cloned() {
            let (extra, skip) = {
                let b = r.borrow();
                match b.extra(&n) {
                    Some(v) => (Some(v.clone()), false),
                    None => (
                        None,
                        b.slot(&n)
                            .map(|s| s.kind == MKind::Der || s.state == SlotState::Absent)
                            .unwrap_or(true),
                    ),
                }
            };
            if let Some(v) = extra {
                entries.push((n, v));
                continue;
            }
            if skip {
                continue;
            }
            let v = self.force_slot(r, &n)?;
            entries.push((n, v));
        }
        for m in members.iter() {
            if m.kind != MKind::Dflt || entries.iter().any(|(k, _)| *k == m.name) {
                continue;
            }
            let present = r
                .borrow()
                .slot(&m.name)
                .map(|s| s.state != SlotState::Absent)
                .unwrap_or(false);
            if present {
                let v = self.force_slot(r, &m.name)?;
                entries.push((m.name.clone(), v));
            }
        }
        merge(&mut entries, p)?;
        Ok(Value::PreObj(Rc::new(entries)))
    }

    // ---------- slots ----------
    /// Force a slot and tell how it ended: ok, invalid, absent.
    pub fn force_state(&self, inst: &Inst, name: &str) -> SlotState {
        self.force_slot_safe(inst, name);
        inst.borrow()
            .slot(name)
            .map(|s| s.state)
            .unwrap_or(SlotState::Invalid)
    }

    /// Force a slot, a failure recorded as its state rather than raised.
    pub fn force_slot_safe(&self, inst: &Inst, name: &str) {
        let _ = self.force_slot(inst, name);
    }

    /// the cycle as the dependency graph records it: the slots forced between
    /// the re-entered one and now, each shown by its member, closing the loop
    fn cycle_path(&self, key: &str) -> String {
        let c = self.computing.borrow();
        let from = c.iter().position(|k| k.as_str() == key).unwrap_or(0);
        let mut chain: Vec<String> = c[from..].iter().map(|k| member_of_key(k)).collect();
        chain.push(member_of_key(key));
        chain.join(" -> ")
    }
    /// Force a slot — its check, default, or derived expression — once, with
    /// dependency tracking (§9.3).
    pub fn force_slot(&self, inst: &Inst, name: &str) -> R<Value> {
        if let Some(owner) = self.owner_of(inst) {
            self.record(format!("snapshot:{}", Self::slot_key(inst, name)));
            if self.round_cache.borrow().is_some()
                && self
                    .prev
                    .borrow()
                    .as_ref()
                    .is_none_or(|p| !Rc::ptr_eq(p, &owner))
            {
                self.record("round:nested".into());
            }
            let value = owner.muted(|| owner.force_slot(inst, name))?;
            self.inherit_snapshot_refs(&value, &owner);
            return Ok(value);
        }
        let state = {
            let b = inst.borrow();
            let Some(s) = b.slot(name) else {
                return err(format!("no member {name}"));
            };
            s.state
        };
        // the slot key is a per-force string allocation; a one-shot evaluate
        // never reads the dependency graph, so build it only when tracking or
        // when the slot is actually forced (past the cached early returns) (F21)
        let mut recorded = None;
        if self.track.get() && !self.computing.borrow().is_empty() {
            let key = Engine::slot_key(inst, name);
            if state == SlotState::Unforced {
                let id = self.record_query(&key);
                recorded = Some((key, id));
            } else {
                self.record(key);
            }
        }
        match state {
            SlotState::Ok => {
                let v = inst.borrow().slot(name).unwrap().value.clone();
                return Ok(match self.round_cache.borrow().as_ref() {
                    Some(c) => c.value(&v, self),
                    None => v,
                });
            }
            SlotState::Absent => {
                if let Some(edits) = self.edits.borrow().as_ref().filter(|e| e.active.get()) {
                    edits
                        .revisions
                        .accept(self, &Self::slot_key(inst, name), &Value::Absent);
                }
                return Ok(Value::Absent);
            }
            SlotState::Invalid => return Err(Fail::Taint),
            _ => {}
        }
        let (key, recorded_id) = recorded.unwrap_or_else(|| (Engine::slot_key(inst, name), None));
        // Only failures need a diagnostic path. Retain its pre-force value:
        // a native computation may replace or mutate the instance's path.
        let path = inst.borrow().path.clone();
        let diagnostic_path = || {
            path_str_iter(
                path.iter()
                    .chain(std::iter::once(&Seg::Name(Rc::from(name)))),
                None,
            )
        };
        if state == SlotState::Deferred {
            if self.phase.get() < 2 {
                return Err(Fail::Defer); // known to wait for phase 2: not attempted again
            }
            inst.borrow_mut().slot_mut(name).unwrap().state = SlotState::Unforced;
        }
        if state == SlotState::Forcing {
            // re-entered from inside an edge computation it was waiting on: the
            // candidate reading it is unanswerable in this round, not a cycle
            if let Some(&base) = self.edge_bases.borrow().last() {
                let at = self
                    .computing
                    .borrow()
                    .iter()
                    .position(|k| k.as_str() == key);
                if at.is_none_or(|i| i < base) {
                    return Err(Fail::Defer);
                }
            }
            self.env.report(Diag::error(
                format!("dependency cycle: {}", self.cycle_path(&key)),
                diagnostic_path(),
                Some("E5007"),
            ));
            inst.borrow_mut().slot_mut(name).unwrap().state = SlotState::Invalid;
            return Err(Fail::Taint);
        }
        // Cached, deferred and cyclic reads do not execute the descriptor.
        // Retain immutable binding-time metadata across the force without
        // cloning its names, supplied value, or captured owner handles.
        let (compute, member_name) = {
            let mut b = inst.borrow_mut();
            let (member_name, s) = b
                .slots
                .iter_mut()
                .find(|(n, _)| n.as_ref() == name)
                .unwrap();
            let compute = s.compute.clone();
            s.state = SlotState::Forcing;
            (compute, member_name.clone())
        };
        let id = recorded_id.unwrap_or_else(|| self.query_id(&key));
        self.register_query_slot_id(id.clone(), inst.clone(), member_name);
        let res = match &compute {
            Some(c) => self.step_id(id.clone(), || {
                let edits = self.edits.borrow().clone();
                let produce = || {
                    if let Some(edits) = &edits {
                        edits.slot_computes.set(edits.slot_computes.get() + 1);
                    }
                    self.run_compute(inst, c)
                };
                if let Some(edits) = edits.as_ref().filter(|e| e.active.get()) {
                    return edits.compute_id(self, &id, produce);
                }
                let revisions = self.revisions.borrow().clone();
                match revisions {
                    Some(revisions) => revisions.compute_id(self, &id, produce),
                    None => produce(),
                }
            }),
            None => Ok(Value::Null),
        };
        match res {
            Ok(v) => {
                let mut b = inst.borrow_mut();
                let s = b.slot_mut(name).unwrap();
                s.state = SlotState::Ok;
                s.value = v.clone();
                Ok(v)
            }
            Err(Fail::Defer) => {
                inst.borrow_mut().slot_mut(name).unwrap().state = SlotState::Deferred;
                self.deferred_slots
                    .borrow_mut()
                    .push((inst.clone(), name.to_string()));
                Err(Fail::Defer)
            }
            Err(Fail::Eval(e)) => {
                {
                    let mut b = inst.borrow_mut();
                    let s = b.slot_mut(name).unwrap();
                    if s.state == SlotState::Forcing {
                        s.state = SlotState::Invalid;
                    }
                }
                self.env.report(Diag {
                    severity: "error".into(),
                    id: None,
                    message: e.msg,
                    path: diagnostic_path(),
                    code: e.code,
                    loc: None,
                    by: None,
                });
                Err(Fail::Taint)
            }
            Err(Fail::Taint) => {
                let mut b = inst.borrow_mut();
                let s = b.slot_mut(name).unwrap();
                if s.state == SlotState::Forcing {
                    s.state = SlotState::Invalid;
                }
                Err(Fail::Taint)
            }
        }
    }

    /// The value of a module-level constant, evaluated once in its module's environment.
    pub fn force_const_in(&self, env: &Rc<Env>, name: &str, root_name: &str) -> R<Value> {
        if !self.const_envs.borrow().iter().any(|e| Rc::ptr_eq(e, env)) {
            self.const_envs.borrow_mut().push(env.clone());
        }
        let key = (self.round_cache.borrow().is_some() || self.track.get()).then(|| {
            let index = self
                .const_envs
                .borrow()
                .iter()
                .position(|e| Rc::ptr_eq(e, env))
                .unwrap();
            format!("const:{index}|{name}")
        });
        if let Some(key) = &key {
            self.record(key.clone());
        }
        let c = env.consts.borrow().get(name).cloned();
        let Some(c) = c else {
            return err(format!("unknown constant {name}"));
        };
        if c.state.get() {
            let v = c.value.borrow().clone();
            if let Some(edits) = self.edits.borrow().as_ref() {
                edits.activate(self, &v);
            }
            return Ok(v);
        }
        let produce = || {
            c.state.set(true);
            let sc = Scope::new(root_name, Some(env.clone()));
            let mut v = self.ev(&c.expr, &sc)?;
            if matches!(v, Value::PreObj(_) | Value::PreArr(_) | Value::JObj(_)) {
                v = match &c.ty {
                    Some(t) => {
                        let rt = env.resolve(t, None).or_else(err)?;
                        self.bind(v, &rt, &[Seg::Name(Rc::from(name))], None, &sc)?
                    }
                    None => self.materialize(v, &[Seg::Name(Rc::from(name))])?,
                };
            }
            *c.value.borrow_mut() = v.clone();
            Ok(v)
        };
        let v = match key {
            Some(key) => self.step(&key, || {
                match self.edits.borrow().as_ref().filter(|e| e.active.get()) {
                    Some(edits) => edits.compute(self, &key, produce),
                    None => produce(),
                }
            }),
            None => produce(),
        }?;
        c.state.set(true);
        *c.value.borrow_mut() = v.clone();
        Ok(v)
    }

    // ---------- driving ----------
    /// Force every slot under a value, recursively.
    pub fn force_all(&self, v: &Value) {
        match v {
            Value::Rec(r) => {
                if self
                    .round_cache
                    .borrow()
                    .as_ref()
                    .is_some_and(|c| c.clean(r))
                {
                    return;
                }
                let names: Vec<_> = r.borrow().slots.iter().map(|(n, _)| n.clone()).collect();
                for n in names {
                    self.force_slot_safe(r, &n);
                    let child = {
                        let b = r.borrow();
                        b.slot(&n)
                            .filter(|s| s.state == SlotState::Ok)
                            .map(|s| s.value.clone())
                    };
                    if let Some(c) = child {
                        self.force_all(&c);
                    }
                }
            }
            Value::Arr(a) => {
                let items = a.borrow().items.clone();
                for x in &items {
                    self.force_all(x);
                }
            }
            Value::Map(m) => {
                let vals: Vec<Value> = m.borrow().entries.iter().map(|(_, v)| v.clone()).collect();
                for x in &vals {
                    self.force_all(x);
                }
            }
            _ => {}
        }
    }

    /// the evaluation phase: 1 materialization, 2 universe complete ($referrers answers)
    pub fn set_phase(&self, p: u8) {
        self.phase.set(p);
    }

    /// force every root, run the $referrers phase, then the assertion pass
    /// force every root, the roots demanded on the way included (an input
    /// bound through its fallback while another root is forced becomes a
    /// root too, and is forced in the same pass — the reference walks the
    /// live root map)
    pub fn force_roots(&self, env: &Env) {
        let mut i = 0;
        loop {
            let v = {
                let rc = env.roots.borrow().clone();
                let roots = rc.borrow();
                if i >= roots.len() {
                    break;
                }
                roots[i].1.clone()
            };
            self.force_all(&v);
            i += 1;
        }
    }
    /// Run every assertion of every instance, reporting under the root's name (§6).
    pub fn validate_all(&self, root_name: &str) {
        for inst in self.env.registry_snapshot() {
            self.validate_inst(&inst, root_name);
        }
    }
    /// Run one instance's assertions, invalidating it on an error-severity failure (§6.6).
    pub fn validate_inst(&self, inst: &Inst, root_name: &str) {
        let asserts = match &inst.borrow().rt.k {
            RTk::Rec(r) => r.asserts.borrow().clone(),
            _ => vec![],
        };
        // An empty body cannot read anything or report a diagnostic. Preserve
        // step's graph reset semantics without creating a temporary query or
        // constructing an assertion scope for every assertion-free record.
        if asserts.is_empty() && !self.track.get() {
            return;
        }
        let key = format!("assert:{}", path_str(&inst.borrow().path, None));
        if asserts.is_empty() {
            if self.round_cache.borrow().is_some() {
                self.remove_query_reads(&key);
            } else {
                self.replace_query_reads(&key, ReadSet::default());
            }
            return;
        }
        self.step(&key, || self.run_asserts(inst, &asserts, root_name));
    }
    /// reset a computed slot so that it is computed again (dependency tracking)
    pub fn reset_slot(&self, key: &str) -> bool {
        let entry = self.query_slot_shared(key);
        let Some((inst, name)) = entry else {
            return false;
        };
        let mut b = inst.borrow_mut();
        let Some(s) = b.slot_mut(&name) else {
            return false;
        };
        if s.compute.is_none() {
            return false;
        }
        if s.state == SlotState::Ok || s.state == SlotState::Invalid {
            s.state = SlotState::Unforced;
            s.value = Value::Null;
        }
        true
    }

    fn run_asserts(&self, inst: &Inst, asserts: &[AssertItem], root_name: &str) {
        let (menv0, ipath, type_name) = {
            let b = inst.borrow();
            (b.menv.clone(), path_str(&b.path, None), b.type_name.clone())
        };
        let sc0 = Scope {
            inst: Some(inst.clone()),
            locals: Locals::new(),
            root_name: Rc::from(root_name),
            menv: menv0.clone(),
        };
        for a in asserts {
            let sc = if a.menv.is_some() {
                sc0.with_menv(a.menv.clone())
            } else {
                sc0.clone()
            };
            if a.when {
                let Ok(cond) = self.ev(&a.cond, &sc) else {
                    continue;
                };
                if matches!(cond, Value::Bool(true)) {
                    let inner: Vec<AssertItem> = a
                        .body
                        .iter()
                        .filter_map(|b| match b {
                            MemberAst::Assert {
                                name, cond, tail, ..
                            } => Some(AssertItem {
                                when: false,
                                name: name.clone(),
                                cond: cond.clone(),
                                tail: tail.clone(),
                                body: vec![],
                                origin: a.origin.clone(),
                                menv: a.menv.clone(),
                            }),
                            MemberAst::When { cond, body, .. } => Some(AssertItem {
                                when: true,
                                name: String::new(),
                                cond: cond.clone(),
                                tail: None,
                                body: body.clone(),
                                origin: a.origin.clone(),
                                menv: a.menv.clone(),
                            }),
                            _ => None,
                        })
                        .collect();
                    self.run_asserts(inst, &inner, root_name);
                }
                continue;
            }
            let ok = match self.ev(&a.cond, &sc) {
                Ok(v) => v,
                Err(Fail::Eval(e)) => {
                    self.env.report(Diag {
                        severity: "error".into(),
                        id: None,
                        message: format!("{}: {}", a.name, e.msg),
                        path: ipath.clone(),
                        code: e.code,
                        loc: None,
                        by: None,
                    });
                    continue;
                }
                Err(_) => continue,
            };
            if matches!(ok, Value::Bool(true)) {
                continue;
            }
            let id = format!(
                "{}.{}",
                a.origin
                    .clone()
                    .or_else(|| type_name.clone())
                    .unwrap_or_default(),
                a.name
            );
            match &a.tail {
                None => self.env.report(Diag {
                    severity: "error".into(),
                    id: Some(id),
                    message: format!("assert {} failed", a.name),
                    path: ipath.clone(),
                    code: Some("E6001".into()),
                    loc: None,
                    by: None,
                }),
                Some(Tail::Inline { severity, template }) => {
                    let msg = self.render_lenient(template, &sc);
                    let code = match severity.as_str() {
                        "error" => "E6001",
                        "warn" => "W6001",
                        _ => "I6001",
                    };
                    self.env.report(Diag {
                        severity: severity.clone(),
                        id: Some(id),
                        message: msg,
                        path: ipath.clone(),
                        code: Some(code.into()),
                        loc: None,
                        by: None,
                    });
                }
                Some(Tail::Ref { name, args }) => {
                    let d = menv0
                        .as_ref()
                        .and_then(|e| e.diags.borrow().get(name).cloned())
                        .or_else(|| self.env.diags.borrow().get(name).cloned());
                    let Some(d) = d else {
                        self.env.report(Diag::error(
                            format!("unknown diagnostic {name}"),
                            ipath.clone(),
                            None,
                        ));
                        continue;
                    };
                    let argv: Vec<Value> = args
                        .iter()
                        .map(|x| self.ev(x, &sc).unwrap_or(Value::Absent))
                        .collect();
                    let mut locals = Locals::new();
                    for (i, p) in d.params.iter().enumerate() {
                        locals = locals.with(
                            Rc::from(p.name.as_str()),
                            argv.get(i).cloned().unwrap_or(Value::Absent),
                        );
                    }
                    let psc = Scope {
                        inst: None,
                        locals,
                        root_name: Rc::from(root_name),
                        menv: menv0.clone(),
                    };
                    let msg = self.render_lenient(&d.template, &psc);
                    let code = if d.severity == "error" {
                        "E6001"
                    } else {
                        "W6001"
                    };
                    self.env.report(Diag {
                        severity: d.severity.clone(),
                        id: Some(id),
                        message: msg,
                        path: ipath.clone(),
                        code: Some(code.into()),
                        loc: None,
                        by: None,
                    });
                }
            }
        }
    }

    fn render_lenient(&self, template: &[TPart], sc: &Scope) -> String {
        let mut s = String::new();
        for p in template {
            match p {
                TPart::Text(t) => s.push_str(t),
                TPart::Expr(x) => {
                    if let Ok(v) = self.ev(x, sc) {
                        if let Ok(t) = self.to_str(&v) {
                            s.push_str(&t);
                        }
                    }
                }
            }
        }
        s
    }

    // ---------- serialization ----------
    /// canonical JSON of a value (§10.4, D29): derived members included,
    /// hidden never; `settable_only` is the tool option D29 provides — the
    /// settable projection (required, optional, defaulted members) that a
    /// document for the same type would carry
    pub fn serialize(&self, v: &Value, root_name: &str, settable_only: bool) -> String {
        let mut out = String::new();
        self.go(v, root_name, settable_only, &mut out);
        out
    }

    /// The same text handed to a writer in pieces as it grows, so a large
    /// document is never held whole. `Ok(false)`: the value has no text and
    /// nothing was written.
    pub(crate) fn serialize_to(
        &self,
        v: &Value,
        root_name: &str,
        settable_only: bool,
        to: &mut dyn std::io::Write,
    ) -> std::io::Result<bool> {
        let mut out = Pieces::new(to);
        let written = self.go(v, root_name, settable_only, &mut out);
        out.finish()?;
        Ok(written)
    }

    // Append one typed value. An unsupported/absent value appends nothing and
    // returns false, allowing its container to omit the member or array item.
    fn go<O: Emit>(&self, x: &Value, root: &str, settable_only: bool, out: &mut O) -> bool {
        use std::fmt::Write;

        match x {
            Value::Absent | Value::Undef => return false,
            Value::Null => out.text().push_str("null"),
            Value::Bool(b) => out.text().push_str(if *b { "true" } else { "false" }),
            Value::Int(i) => write!(out.text(), "{i}").expect("writing to String"),
            Value::Float(f) => out.text().push_str(&fmt_f(*f)),
            Value::Str(s) => write_json_str(out.text(), s),
            Value::Q(q) => {
                let unit = self
                    .env
                    .base_unit_of
                    .borrow()
                    .get(q.dim.as_str())
                    .cloned()
                    .unwrap_or_else(|| q.dim.as_ref().clone());
                out.text().push_str("{\"value\":");
                out.text().push_str(&fmt_f(q.value));
                out.text().push_str(",\"unit\":");
                write_json_str(out.text(), &unit);
                out.text().push('}');
            }
            Value::Ref(p) => write_json_str(out.text(), &path_str(p, Some(root))),
            Value::Arr(a) => {
                out.text().push('[');
                let mut comma = false;
                for item in &a.borrow().items {
                    let start = out.text().len();
                    if comma {
                        out.text().push(',');
                    }
                    if self.go(item, root, settable_only, out) {
                        comma = true;
                        out.entry_done();
                    } else {
                        out.text().truncate(start);
                    }
                }
                out.text().push(']');
            }
            Value::Map(m) => {
                out.text().push('{');
                let mut comma = false;
                for (key, value) in &m.borrow().entries {
                    let start = out.text().len();
                    if comma {
                        out.text().push(',');
                    }
                    write_json_str(out.text(), key);
                    out.text().push(':');
                    if self.go(value, root, settable_only, out) {
                        comma = true;
                        out.entry_done();
                    } else {
                        out.text().truncate(start);
                    }
                }
                out.text().push('}');
            }
            Value::Rec(r) => {
                let b = r.borrow();
                out.text().push('{');
                let mut comma = false;
                let members = rec_members(&b.rt);
                // Binding pushes one slot per member, in member order. A record
                // that holds to that is walked by position; any other (caught
                // half-bound, or wider than the position set) is walked by name.
                let aligned = members.len() <= 64
                    && b.slots.len() == members.len()
                    && b.slots
                        .iter()
                        .zip(members.iter())
                        .all(|((name, _), m)| name.as_ref() == m.name.as_str());
                let done = (!aligned).then(|| Supplied::new(&b.entry_order));
                let (mut supplied, mut cursor) = (0u64, 0usize);
                for n in b.entry_order.iter() {
                    // Supplied names mostly follow the member order: try the
                    // next position before searching.
                    let position = if aligned {
                        let hit = (cursor < b.slots.len()
                            && b.slots[cursor].0.as_ref() == n.as_str())
                        .then_some(cursor)
                        .or_else(|| b.slots.iter().position(|(k, _)| k.as_ref() == n.as_str()));
                        if let Some(i) = hit {
                            supplied |= 1 << i;
                            cursor = i + 1;
                        }
                        hit
                    } else {
                        None
                    };
                    if let Some(v) = b.extra(n) {
                        if comma {
                            out.text().push(',');
                        }
                        write_json_str(out.text(), n);
                        out.text().push(':');
                        self.raw_json(v, root, out);
                        comma = true;
                        out.entry_done();
                        continue;
                    }
                    let slot = if aligned {
                        position.map(|i| &b.slots[i].1)
                    } else {
                        b.slot(n)
                    };
                    let Some(s) = slot else { continue };
                    if matches!(s.state, SlotState::Invalid | SlotState::Absent)
                        || s.kind == MKind::Der
                    {
                        continue;
                    }
                    let start = out.text().len();
                    if comma {
                        out.text().push(',');
                    }
                    write_json_str(out.text(), n);
                    out.text().push(':');
                    if self.go(&s.value, root, settable_only, out) {
                        comma = true;
                        out.entry_done();
                    } else {
                        out.text().truncate(start);
                    }
                }
                for (i, m) in members.iter().enumerate() {
                    let was_supplied = match &done {
                        Some(done) => done.has(m.name.as_str()),
                        None => supplied & (1 << i) != 0,
                    };
                    if was_supplied && m.kind != MKind::Der {
                        continue;
                    }
                    if settable_only && m.kind == MKind::Der {
                        continue;
                    }
                    let slot = if aligned {
                        Some(&b.slots[i].1)
                    } else {
                        b.slot(&m.name)
                    };
                    let Some(s) = slot else { continue };
                    if s.hidden
                        || matches!(
                            s.state,
                            SlotState::Invalid
                                | SlotState::Absent
                                | SlotState::Unforced
                                | SlotState::Deferred
                        )
                    {
                        continue;
                    }
                    let start = out.text().len();
                    if comma {
                        out.text().push(',');
                    }
                    write_json_str(out.text(), &m.name);
                    out.text().push(':');
                    if self.go(&s.value, root, settable_only, out) {
                        comma = true;
                        out.entry_done();
                    } else {
                        out.text().truncate(start);
                    }
                }
                out.text().push('}');
            }
            Value::JObj(_) | Value::JArr(_) => self.raw_json(x, root, out),
            _ => return false,
        }
        true
    }

    // Raw documents retain every position. Non-document values and failed or
    // unsupported PreVal results become null, unlike omitted typed children.
    fn raw_json<O: Emit>(&self, v: &Value, root: &str, out: &mut O) {
        match v {
            Value::JArr(items) => {
                out.text().push('[');
                for (index, item) in items.iter().enumerate() {
                    if index != 0 {
                        out.text().push(',');
                    }
                    self.raw_json(item, root, out);
                    out.entry_done();
                }
                out.text().push(']');
            }
            Value::JObj(entries) => {
                out.text().push('{');
                for (index, (key, value)) in entries.iter().enumerate() {
                    if index != 0 {
                        out.text().push(',');
                    }
                    write_json_str(out.text(), key);
                    out.text().push(':');
                    self.raw_json(value, root, out);
                    out.entry_done();
                }
                out.text().push('}');
            }
            Value::PreVal(pv) => match self.ev(&pv.expr, &pv.scope) {
                Ok(v) => {
                    if !self.go(&v, root, false, out) {
                        out.text().push_str("null");
                    }
                }
                Err(_) => out.text().push_str("null"),
            },
            other => {
                if !self.go(other, root, false, out) {
                    out.text().push_str("null");
                }
            }
        }
    }
}