omgbase-mutate 3.5.1

omgbase mutation kernel: the working block tree, the six ops (insert/update/move/remove/split/merge) with placement addressing and CAS, the splice renderer's dirty rules, changeset placeholders, the whole-document lowering and the opset — Rust implementation
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
//! Effects and plans (`spec/mutate/README.md` §11, mutate 2.3; ADR-021):
//! the public intentional-write vocabulary — nine effects over document,
//! block, node and section targets — as a **planner tier** over the six
//! kernel ops. Everything here is pure: the effect and plan shapes with their
//! JSON forms, the `$new.<n>` symbols a plan uses for identities it creates,
//! the shape validator (§11.1), the focus bookkeeping the conflict rules run
//! on ([`ConflictTracker`], §11.3), the canonical JSON the plan digest is
//! computed over (§11.5), and the [`Plan`] with its digest. The store
//! resolves targets, lowers under a symbolic minter, pins the preconditions
//! and commits a plan (`omgbase-store`'s `effects_plan`).
//!
//! **Canonical JSON** (§11.5): no whitespace; object members sorted by the
//! UTF-8 bytes of their keys; a `null` value stays `null` (optional keys are
//! absent, never `null`, by construction); strings escaped as JSON requires
//! and no further (`"`, `\`, U+0000–U+001F as `\b \f \n \r \t` else
//! `\u00xx` lower-case — `serde_json`'s own rules — everything else literal
//! UTF-8); a number integral with |v| < 2^53 as a plain integer (`-0` → `0`),
//! any other finite number as ECMAScript `Number::toString` prints it
//! (shortest round-trip digits; exponential outside `1e-7 ≤ |x| < 1e21`).
//!
//! `plan_id = hex(sha256(canonical({ version, planner_v, effects, opset,
//! preconditions, new_ids, selection? })))` — `selection` (3.1, §11.8) is
//! the seventh core member when the plan was derived from an OQX selector,
//! absent otherwise.

use std::collections::{BTreeMap, HashMap};

use omgbase_format::hash::{hex, sha256};
use serde_json::{Map, Value, json};

use crate::changeset::Op;
use crate::error::{ErrorCode, MutationError, Result};
use crate::ops::{At, Expect, OpResult, Parent, To};
use crate::opset::{OpsetSummary, PlanDisposition};

/// The plan schema version this crate reads and writes.
pub const PLAN_VERSION: u64 = 1;
/// The lowering + conflict rules version pinned in `spec/mutate` §11 (the
/// `matcher_v` precedent): `p2` since mutate 3.0 — a `create` is a loaded
/// document whose block symbols are in `new_ids`; `p3` since mutate 3.1 —
/// the core may carry a `selection` (§11.8), so every plan digest changes.
pub const PLANNER_V: &str = "p3";
/// §11.8: the most hits a selector may yield when the request names no
/// `expect.max` — a selection past it is `selection_too_large`.
pub const SELECTION_CEILING: usize = 1000;

// ---- `$new.<n>` ---------------------------------------------------------------------------

/// `$new.<n>` → `n`; `None` for anything else.
#[must_use]
pub fn parse_new_symbol(s: &str) -> Option<usize> {
    let n = s.strip_prefix("$new.")?;
    if n.is_empty() || !n.bytes().all(|b| b.is_ascii_digit()) {
        return None;
    }
    n.parse().ok()
}

/// The `n`-th symbolic identity.
#[must_use]
pub fn new_symbol(n: usize) -> String {
    format!("$new.{n}")
}

// ---- the shape check's `fix` (§8, 3.4) ----------------------------------------------------

/// A §11.1 shape error: the message (naming `effects[i]` and the member) and,
/// since 3.4 (§8), the corrected call when the check can spell it — the
/// request as given with the offending effect rewritten, canonical JSON.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ShapeError {
    pub message: String,
    pub fix: Option<String>,
}

impl From<String> for ShapeError {
    fn from(message: String) -> Self {
        Self { message, fix: None }
    }
}

/// A live block's row for the anchor fix: its parent block id (`None` at the
/// top level) and its document's path (storage form).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ParentRow {
    pub parent: Option<String>,
    pub path: String,
}

/// What the shape check needs to spell a `fix` for the shape errors of §8
/// (3.4; the reference's `ShapeFixContext`): the request as given — `select`
/// and `expect` when present, the `effects` list (the corrected call is that
/// request with `effects[i]` AS WRITTEN rewritten, before any desugaring) —
/// and the live-row lookup for the one fix that reads the store: `parent_of`
/// a block id → its row, or `None` when no live block has the id (then there
/// is no fix). The planner's compile supplies it; a call without it gets the
/// same errors with no `fix`.
pub struct ShapeFixContext<'a> {
    pub select: Option<&'a Value>,
    pub effects: &'a Value,
    pub expect: Option<&'a Value>,
    pub parent_of: &'a dyn Fn(&str) -> Option<ParentRow>,
}

/// The fixer of one effect (the reference's `EffectFixer`): `build(effect,
/// expect)` is the request with `effects[i]` replaced by `effect` (and, when
/// given, its top-level `expect` replaced), canonical.
struct Fixer<'a> {
    ctx: &'a ShapeFixContext<'a>,
    i: usize,
    /// the effect as written in the request (the base every corrected effect is spelled from)
    written: Map<String, Value>,
}

impl<'a> Fixer<'a> {
    fn new(ctx: Option<&'a ShapeFixContext<'a>>, i: usize, v: &Map<String, Value>) -> Option<Self> {
        let ctx = ctx?;
        let written = ctx
            .effects
            .as_array()
            .and_then(|l| l.get(i))
            .and_then(Value::as_object)
            .unwrap_or(v)
            .clone();
        Some(Self { ctx, i, written })
    }

    fn build(&self, effect: Map<String, Value>, expect: Option<Value>) -> String {
        let effects = match self.ctx.effects {
            Value::Array(list) => {
                let mut copy = list.clone();
                if self.i < copy.len() {
                    copy[self.i] = Value::Object(effect);
                } else {
                    copy.resize(self.i, Value::Null);
                    copy.push(Value::Object(effect));
                }
                Value::Array(copy)
            }
            other => {
                let mut o = other.as_object().cloned().unwrap_or_default();
                o.insert(self.i.to_string(), Value::Object(effect));
                Value::Object(o)
            }
        };
        let mut m = Map::new();
        if let Some(s) = self.ctx.select {
            m.insert("select".to_owned(), s.clone());
        }
        m.insert("effects".to_owned(), effects);
        match expect {
            Some(e) => {
                m.insert("expect".to_owned(), e);
            }
            None => {
                if let Some(e) = self.ctx.expect {
                    m.insert("expect".to_owned(), e.clone());
                }
            }
        }
        canonical_json(&Value::Object(m))
    }
}

/// The reference form of a storage path: exactly one leading `/`.
fn reference_path(path: &str) -> String {
    format!("/{}", path.trim_start_matches('/'))
}

/// §8 (3.4): an effect-level `expect.max` — the bound belongs to the
/// request's top-level `expect`, beside `select`. The fix drops it from the
/// effect (the rest of that `expect` stays; an emptied `expect` goes) and,
/// when the request has a `select`, moves it to the top level unless a
/// top-level `expect.max` is already there (then the top-level one is kept
/// as written); without a `select` a top-level `expect` would itself be
/// refused, so the fix only drops it.
fn effect_level_max(v: &Map<String, Value>, here: &str, f: Option<&Fixer<'_>>) -> ShapeError {
    let message = format!(
        "{here}: `expect.max` bounds a selection — it is the request's top-level `expect`, beside `select`, not an effect's"
    );
    let Some(f) = f else {
        return message.into();
    };
    let mut rest = v.clone();
    let max = rest.remove("max").unwrap_or(Value::Null);
    let mut effect = f.written.clone();
    if rest.is_empty() {
        effect.remove("expect");
    } else {
        effect.insert("expect".to_owned(), Value::Object(rest));
    }
    if f.ctx.select.is_none() {
        return ShapeError {
            message,
            fix: Some(f.build(effect, None)),
        };
    }
    let mut top = f
        .ctx
        .expect
        .and_then(Value::as_object)
        .cloned()
        .unwrap_or_default();
    if !top.contains_key("max") {
        top.insert("max".to_owned(), max);
    }
    ShapeError {
        message,
        fix: Some(f.build(effect, Some(Value::Object(top)))),
    }
}

/// §8 (3.4): `at` given as the bare string `"after"` / `"before"` with a
/// block `into` — "right after block X" is `into: X's parent, at: { after:
/// X }`. The fix needs the block's live row (its parent, or its document
/// when it is top-level, spelled as the rooted path); a block the store does
/// not know gets no fix.
fn bare_anchor(at: &str, into: &Target, here: &str, f: Option<&Fixer<'_>>) -> ShapeError {
    let message = format!(
        "{here}: `at` must be \"start\", \"end\", {{ before: <block id> }} or {{ after: <block id> }} — \"{at} block X\" is into: X's parent (a block, or the document when X is top-level), at: {{ {at}: X }}"
    );
    let (Some(f), Target::Block { id }) = (f, into) else {
        return message.into();
    };
    let Some(row) = (f.ctx.parent_of)(id) else {
        return message.into();
    };
    let parent = match row.parent {
        None => json!(reference_path(&row.path)),
        Some(p) => json!({ "kind": "block", "id": p }),
    };
    let mut effect = f.written.clone();
    effect.insert("into".to_owned(), parent);
    effect.insert("at".to_owned(), json!({ at: id }));
    ShapeError {
        message,
        fix: Some(f.build(effect, None)),
    }
}

/// §8 (3.4): a plural-target `expect` written as `{ content_hash: { <id>:
/// <hash>, … } }` (every key a guard name, every value a map of strings) —
/// the fix inverts the nesting to `{ <id>: { content_hash: <hash> }, … }`.
fn inverted_expect_map(
    v: &Map<String, Value>,
    here: &str,
    f: Option<&Fixer<'_>>,
) -> Option<ShapeError> {
    let is_string_record = |x: &Value| {
        x.as_object()
            .is_some_and(|o| o.values().all(Value::is_string))
    };
    if v.is_empty()
        || !v
            .keys()
            .all(|k| k == "content_hash" || k == "parent_children_hash")
        || !v.values().all(is_string_record)
    {
        return None;
    }
    let message = format!(
        "{here}: a plural-target `expect` is keyed by block id — {{ <block id>: {{ content_hash?, parent_children_hash? }}, … }}"
    );
    let Some(f) = f else {
        return Some(message.into());
    };
    let mut inverted: Map<String, Value> = Map::new();
    for (guard, by_id) in v {
        for (id, hash) in by_id.as_object().expect("checked") {
            let entry = inverted
                .entry(id.clone())
                .or_insert_with(|| Value::Object(Map::new()));
            if let Some(o) = entry.as_object_mut() {
                o.insert(guard.clone(), hash.clone());
            }
        }
    }
    let mut effect = f.written.clone();
    effect.insert("expect".to_owned(), Value::Object(inverted));
    Some(ShapeError {
        message,
        fix: Some(f.build(effect, None)),
    })
}

/// §8 (3.4): the block-field misspellings the fix corrects to `markdown`.
const BLOCK_FIELD_ALIASES: &[&str] = &["text", "content", "body", "raw"];

// ---- targets ------------------------------------------------------------------------------

/// What an effect addresses (§11 `Target`). A document is named by `id`
/// and/or `path` (a resolved target carries both); a section is the derived
/// range under a heading block (ADR-005), never a stored id.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Target {
    Document {
        id: Option<String>,
        path: Option<String>,
    },
    Block {
        id: String,
    },
    Node {
        id: String,
    },
    Section {
        heading_id: String,
    },
}

impl Target {
    /// `document` / `block` / `node` / `section`.
    #[must_use]
    pub const fn kind(&self) -> &'static str {
        match self {
            Target::Document { .. } => "document",
            Target::Block { .. } => "block",
            Target::Node { .. } => "node",
            Target::Section { .. } => "section",
        }
    }

    /// The id the target names, if any (a document's `id`, a block's or
    /// node's `id`, a section's heading id).
    #[must_use]
    pub fn id(&self) -> Option<&str> {
        match self {
            Target::Document { id, .. } => id.as_deref(),
            Target::Block { id } | Target::Node { id } => Some(id),
            Target::Section { heading_id } => Some(heading_id),
        }
    }

    /// `{ kind, … }`; optional keys absent.
    #[must_use]
    pub fn to_json(&self) -> Value {
        let mut m = Map::new();
        m.insert("kind".to_owned(), json!(self.kind()));
        match self {
            Target::Document { id, path } => {
                if let Some(id) = id {
                    m.insert("id".to_owned(), json!(id));
                }
                if let Some(path) = path {
                    m.insert("path".to_owned(), json!(path));
                }
            }
            Target::Block { id } | Target::Node { id } => {
                m.insert("id".to_owned(), json!(id));
            }
            Target::Section { heading_id } => {
                m.insert("heading_id".to_owned(), json!(heading_id));
            }
        }
        Value::Object(m)
    }

    /// Parse `{ kind, … }` of any kind.
    pub fn from_json(v: &Value) -> std::result::Result<Target, String> {
        validate_target(Some(v), "target", &["document", "block", "node", "section"])
    }
}

/// A `targets` list as resolved effects spell it: block targets.
fn block_refs_to_json(ids: &[String]) -> Value {
    Value::Array(
        ids.iter()
            .map(|id| Target::Block { id: id.clone() }.to_json())
            .collect(),
    )
}

// ---- expectations -------------------------------------------------------------------------

/// §11 `Expect`: the kernel's CAS tokens plus the document's current
/// revision (`revision`), checked at plan time and pinned into the plan.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct EffectExpect {
    pub content_hash: Option<String>,
    pub parent_children_hash: Option<String>,
    pub revision: Option<String>,
}

impl EffectExpect {
    /// The kernel's `Expect` when either hash is given.
    #[must_use]
    pub fn kernel(&self) -> Option<Expect> {
        if self.content_hash.is_none() && self.parent_children_hash.is_none() {
            return None;
        }
        Some(Expect {
            content_hash: self.content_hash.clone(),
            parent_children_hash: self.parent_children_hash.clone(),
        })
    }

    #[must_use]
    pub fn to_json(&self) -> Value {
        let mut m = Map::new();
        if let Some(h) = &self.content_hash {
            m.insert("content_hash".to_owned(), json!(h));
        }
        if let Some(h) = &self.parent_children_hash {
            m.insert("parent_children_hash".to_owned(), json!(h));
        }
        if let Some(r) = &self.revision {
            m.insert("revision".to_owned(), json!(r));
        }
        Value::Object(m)
    }

    pub fn from_json(v: &Value) -> std::result::Result<Self, String> {
        validate_expect(Some(v), "expect", None)
            .map(|e| e.expect("given"))
            .map_err(|e| e.message)
    }
}

// ---- the effects --------------------------------------------------------------------------

/// A `from` → `to` destination rewrite of a `retarget`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Repair {
    pub from: String,
    pub to: String,
}

/// Per-block expectations of a `remove`/`merge` (§11.1 `expect: { <block id>: Expect }`).
pub type ExpectMap = BTreeMap<String, Expect>;

/// §11 `Effect`: the nine public effects (two shapes each for `move` and
/// `remove`).
#[derive(Clone, Debug, PartialEq)]
pub enum Effect {
    /// A new document at `path` from `markdown` and an optional frontmatter
    /// mapping (composed as `docs_create` composes).
    Create {
        path: String,
        markdown: String,
        frontmatter: Option<Map<String, Value>>,
    },
    /// New blocks parsed from `markdown` into a document's top level, a
    /// section's range or a container block, at `at` (default `end`).
    Insert {
        into: Target,
        at: At,
        markdown: String,
        expect: Option<EffectExpect>,
    },
    /// Write a field: `frontmatter.<key>` / `content` of a document,
    /// `markdown` / `attrs.checked` of a block, an editable property of a
    /// node.
    Set {
        target: Target,
        field: String,
        value: Value,
        expect: Option<EffectExpect>,
    },
    /// Remove a document's `frontmatter.<key>`.
    Unset {
        target: Target,
        field: String,
        expect: Option<EffectExpect>,
    },
    /// Rename a document (identity kept), rewriting the inbound links unless
    /// `retarget_inbound` is false.
    MoveDocument {
        target: Target,
        to: String,
        retarget_inbound: bool,
    },
    /// Move blocks under a new parent at a position.
    MoveBlocks {
        targets: Vec<String>,
        into: Target,
        at: At,
        expect: Option<EffectExpect>,
    },
    /// Tombstone a document (nothing pooled).
    RemoveDocument { target: Target },
    /// Remove blocks (subtrees).
    RemoveBlocks {
        targets: Vec<String>,
        expect: Option<ExpectMap>,
    },
    /// Split a block at byte offsets.
    Split {
        target: String,
        at: Vec<usize>,
        expect: Option<EffectExpect>,
    },
    /// Merge blocks into the first (`separator` default `" "`, made explicit
    /// once resolved).
    Merge {
        targets: Vec<String>,
        separator: Option<String>,
        expect: Option<ExpectMap>,
    },
    /// Rewrite link destinations repository-wide (`links_repair`).
    Retarget {
        repairs: Vec<Repair>,
        path_glob: Option<String>,
    },
}

/// `start` / `end` / `{ before }` / `{ after }`.
#[must_use]
pub fn at_to_json(at: &At) -> Value {
    match at {
        At::Start => json!("start"),
        At::End => json!("end"),
        At::Before(id) => json!({ "before": id }),
        At::After(id) => json!({ "after": id }),
    }
}

/// Parse an `at`; absent → `end`.
pub fn at_from_json(v: Option<&Value>, here: &str) -> std::result::Result<At, String> {
    match v {
        None => Ok(At::End),
        Some(Value::String(s)) if s == "start" => Ok(At::Start),
        Some(Value::String(s)) if s == "end" => Ok(At::End),
        Some(Value::Object(a)) if a.len() == 1 => {
            if let Some(b) = a.get("before").and_then(Value::as_str) {
                Ok(At::Before(b.to_owned()))
            } else if let Some(b) = a.get("after").and_then(Value::as_str) {
                Ok(At::After(b.to_owned()))
            } else {
                Err(format!(
                    "{here}: `at` must be \"start\", \"end\", {{ before: <block id> }} or {{ after: <block id> }}"
                ))
            }
        }
        _ => Err(format!(
            "{here}: `at` must be \"start\", \"end\", {{ before: <block id> }} or {{ after: <block id> }}"
        )),
    }
}

/// `at` of an `insert` / block `move` (the reference's `validateAt`): the
/// bare string `"before"` / `"after"` is the anchor mistake of §8 (3.4), its
/// message naming the right shape and its fix anchoring on the block from
/// its parent.
fn validate_at(
    v: Option<&Value>,
    here: &str,
    into: &Target,
    f: Option<&Fixer<'_>>,
) -> std::result::Result<At, ShapeError> {
    if let Some(Value::String(s)) = v
        && (s == "before" || s == "after")
    {
        return Err(bare_anchor(s, into, here, f));
    }
    at_from_json(v, here).map_err(Into::into)
}

fn require_string(
    obj: &Map<String, Value>,
    key: &str,
    here: &str,
) -> std::result::Result<String, String> {
    obj.get(key)
        .and_then(Value::as_str)
        .map(str::to_owned)
        .ok_or_else(|| format!("{here}: `{key}` must be a string"))
}

fn optional_string(
    obj: &Map<String, Value>,
    key: &str,
    here: &str,
) -> std::result::Result<Option<String>, String> {
    match obj.get(key) {
        None => Ok(None),
        Some(Value::String(s)) => Ok(Some(s.clone())),
        Some(_) => Err(format!("{here}: `{key}` must be a string")),
    }
}

fn only_keys(
    obj: &Map<String, Value>,
    allowed: &[&str],
    here: &str,
) -> std::result::Result<(), String> {
    let extra: Vec<String> = obj
        .keys()
        .filter(|k| !allowed.contains(&k.as_str()))
        .map(|k| format!("`{k}`"))
        .collect();
    if extra.is_empty() {
        Ok(())
    } else {
        Err(format!(
            "{here}: unknown key{} {}",
            if extra.len() > 1 { "s" } else { "" },
            extra.join(", ")
        ))
    }
}

/// §11.1: a target of one of `kinds`.
fn validate_target(
    v: Option<&Value>,
    here: &str,
    kinds: &[&str],
) -> std::result::Result<Target, String> {
    let kinds_text = kinds
        .iter()
        .map(|k| format!("\"{k}\""))
        .collect::<Vec<_>>()
        .join(" | ");
    let obj = v
        .and_then(Value::as_object)
        .filter(|o| o.get("kind").is_some_and(Value::is_string))
        .ok_or_else(|| format!("{here}: a target is {{ kind: {kinds_text}, … }}"))?;
    let kind = obj["kind"].as_str().expect("checked");
    if !kinds.contains(&kind) {
        return Err(format!(
            "{here}: `kind` must be one of {} (got \"{kind}\")",
            kinds.join(", ")
        ));
    }
    Ok(match kind {
        "document" => {
            only_keys(obj, &["kind", "id", "path"], here)?;
            let id = optional_string(obj, "id", here)?;
            let path = optional_string(obj, "path", here)?;
            if id.is_none() && path.is_none() {
                return Err(format!("{here}: a document target needs `id` or `path`"));
            }
            Target::Document { id, path }
        }
        "block" => {
            only_keys(obj, &["kind", "id"], here)?;
            Target::Block {
                id: require_string(obj, "id", here)?,
            }
        }
        "node" => {
            only_keys(obj, &["kind", "id"], here)?;
            Target::Node {
                id: require_string(obj, "id", here)?,
            }
        }
        "section" => {
            only_keys(obj, &["kind", "heading_id"], here)?;
            Target::Section {
                heading_id: require_string(obj, "heading_id", here)?,
            }
        }
        _ => unreachable!("kinds are the four above"),
    })
}

/// `targets`: a non-empty array of block targets.
fn validate_targets(v: Option<&Value>, here: &str) -> std::result::Result<Vec<String>, String> {
    let list = v
        .and_then(Value::as_array)
        .filter(|a| !a.is_empty())
        .ok_or_else(|| format!("{here}: `targets` must be a non-empty array of block targets"))?;
    list.iter()
        .enumerate()
        .map(|(i, t)| {
            match validate_target(Some(t), &format!("{here}.targets[{i}]"), &["block"])? {
                Target::Block { id } => Ok(id),
                _ => unreachable!("kinds is [block]"),
            }
        })
        .collect()
}

fn validate_expect(
    v: Option<&Value>,
    here: &str,
    f: Option<&Fixer<'_>>,
) -> std::result::Result<Option<EffectExpect>, ShapeError> {
    let Some(v) = v else { return Ok(None) };
    let obj = v
        .as_object()
        .ok_or_else(|| format!("{here}: `expect` must be an object"))?;
    if obj.contains_key("max") {
        return Err(effect_level_max(obj, here, f));
    }
    let at = format!("{here}.expect");
    only_keys(
        obj,
        &["content_hash", "parent_children_hash", "revision"],
        &at,
    )?;
    Ok(Some(EffectExpect {
        content_hash: optional_string(obj, "content_hash", &at)?,
        parent_children_hash: optional_string(obj, "parent_children_hash", &at)?,
        revision: optional_string(obj, "revision", &at)?,
    }))
}

fn validate_expect_map(
    v: Option<&Value>,
    here: &str,
    f: Option<&Fixer<'_>>,
) -> std::result::Result<Option<ExpectMap>, ShapeError> {
    let Some(v) = v else { return Ok(None) };
    let obj = v
        .as_object()
        .ok_or_else(|| format!("{here}: `expect` must be an object keyed by block id"))?;
    if obj.contains_key("max") {
        return Err(effect_level_max(obj, here, f));
    }
    if let Some(e) = inverted_expect_map(obj, here, f) {
        return Err(e);
    }
    let mut out = ExpectMap::new();
    for (id, x) in obj {
        let at = format!("{here}.expect[{}]", Value::String(id.clone()));
        let x = x
            .as_object()
            .ok_or_else(|| format!("{at}: must be an object"))?;
        only_keys(x, &["content_hash", "parent_children_hash"], &at)?;
        out.insert(
            id.clone(),
            Expect {
                content_hash: optional_string(x, "content_hash", &at)?,
                parent_children_hash: optional_string(x, "parent_children_hash", &at)?,
            },
        );
    }
    Ok(Some(out))
}

/// §11.2: the `field` spellings per target kind, checked at the shape level.
fn check_field(
    target: &Target,
    field: &str,
    here: &str,
    op: &str,
    f: Option<&Fixer<'_>>,
) -> std::result::Result<(), ShapeError> {
    match target {
        Target::Document { .. } => {
            if field
                .strip_prefix("frontmatter.")
                .is_some_and(|k| !k.is_empty())
                || (op == "set" && field == "content")
            {
                Ok(())
            } else {
                Err(format!(
                    "{here}: a document's `field` is `frontmatter.<key>`{} (got \"{field}\")",
                    if op == "set" { " or `content`" } else { "" }
                )
                .into())
            }
        }
        Target::Block { .. } => {
            if field == "markdown" || field == "attrs.checked" {
                Ok(())
            } else {
                // (3.4, §8) `text` / `content` / `body` / `raw` on a block: the fix spells `markdown`.
                let fix = f.filter(|_| BLOCK_FIELD_ALIASES.contains(&field)).map(|f| {
                    let mut effect = f.written.clone();
                    effect.insert("field".to_owned(), json!("markdown"));
                    f.build(effect, None)
                });
                Err(ShapeError {
                    message: format!(
                        "{here}: a block's `field` is `markdown` or `attrs.checked` (got \"{field}\")"
                    ),
                    fix,
                })
            }
        }
        Target::Node { .. } => {
            if field.is_empty() || field.contains('.') {
                Err(format!(
                    "{here}: a node's `field` is one of its editable properties (got \"{field}\")"
                )
                .into())
            } else {
                Ok(())
            }
        }
        Target::Section { .. } => Err(format!("{here}: a section has no settable field").into()),
    }
}

fn expect_map_to_json(m: &ExpectMap) -> Value {
    Value::Object(
        m.iter()
            .map(|(k, e)| {
                let mut o = Map::new();
                if let Some(h) = &e.content_hash {
                    o.insert("content_hash".to_owned(), json!(h));
                }
                if let Some(h) = &e.parent_children_hash {
                    o.insert("parent_children_hash".to_owned(), json!(h));
                }
                (k.clone(), Value::Object(o))
            })
            .collect(),
    )
}

impl Effect {
    /// The effect's `op`.
    #[must_use]
    pub const fn name(&self) -> &'static str {
        match self {
            Effect::Create { .. } => "create",
            Effect::Insert { .. } => "insert",
            Effect::Set { .. } => "set",
            Effect::Unset { .. } => "unset",
            Effect::MoveDocument { .. } | Effect::MoveBlocks { .. } => "move",
            Effect::RemoveDocument { .. } | Effect::RemoveBlocks { .. } => "remove",
            Effect::Split { .. } => "split",
            Effect::Merge { .. } => "merge",
            Effect::Retarget { .. } => "retarget",
        }
    }

    /// The wire form (§11.4 `ResolvedEffect` once resolved): `op` first,
    /// `at` always present, `separator` present when set, optional keys
    /// absent.
    #[must_use]
    pub fn to_json(&self) -> Value {
        let mut m = Map::new();
        m.insert("op".to_owned(), json!(self.name()));
        let expect = |m: &mut Map<String, Value>, e: &Option<EffectExpect>| {
            if let Some(e) = e {
                m.insert("expect".to_owned(), e.to_json());
            }
        };
        match self {
            Effect::Create {
                path,
                markdown,
                frontmatter,
            } => {
                m.insert("path".to_owned(), json!(path));
                m.insert("markdown".to_owned(), json!(markdown));
                if let Some(fm) = frontmatter {
                    m.insert("frontmatter".to_owned(), Value::Object(fm.clone()));
                }
            }
            Effect::Insert {
                into,
                at,
                markdown,
                expect: e,
            } => {
                m.insert("into".to_owned(), into.to_json());
                m.insert("at".to_owned(), at_to_json(at));
                m.insert("markdown".to_owned(), json!(markdown));
                expect(&mut m, e);
            }
            Effect::Set {
                target,
                field,
                value,
                expect: e,
            } => {
                m.insert("target".to_owned(), target.to_json());
                m.insert("field".to_owned(), json!(field));
                m.insert("value".to_owned(), value.clone());
                expect(&mut m, e);
            }
            Effect::Unset {
                target,
                field,
                expect: e,
            } => {
                m.insert("target".to_owned(), target.to_json());
                m.insert("field".to_owned(), json!(field));
                expect(&mut m, e);
            }
            Effect::MoveDocument {
                target,
                to,
                retarget_inbound,
            } => {
                m.insert("target".to_owned(), target.to_json());
                m.insert("to".to_owned(), json!(to));
                m.insert("retarget_inbound".to_owned(), json!(retarget_inbound));
            }
            Effect::MoveBlocks {
                targets,
                into,
                at,
                expect: e,
            } => {
                m.insert("targets".to_owned(), block_refs_to_json(targets));
                m.insert("into".to_owned(), into.to_json());
                m.insert("at".to_owned(), at_to_json(at));
                expect(&mut m, e);
            }
            Effect::RemoveDocument { target } => {
                m.insert("target".to_owned(), target.to_json());
            }
            Effect::RemoveBlocks { targets, expect: e } => {
                m.insert("targets".to_owned(), block_refs_to_json(targets));
                if let Some(e) = e {
                    m.insert("expect".to_owned(), expect_map_to_json(e));
                }
            }
            Effect::Split {
                target,
                at,
                expect: e,
            } => {
                m.insert(
                    "target".to_owned(),
                    Target::Block { id: target.clone() }.to_json(),
                );
                m.insert("at".to_owned(), json!(at));
                expect(&mut m, e);
            }
            Effect::Merge {
                targets,
                separator,
                expect: e,
            } => {
                m.insert("targets".to_owned(), block_refs_to_json(targets));
                if let Some(s) = separator {
                    m.insert("separator".to_owned(), json!(s));
                }
                if let Some(e) = e {
                    m.insert("expect".to_owned(), expect_map_to_json(e));
                }
            }
            Effect::Retarget { repairs, path_glob } => {
                m.insert(
                    "repairs".to_owned(),
                    Value::Array(
                        repairs
                            .iter()
                            .map(|r| json!({ "from": r.from, "to": r.to }))
                            .collect(),
                    ),
                );
                if let Some(g) = path_glob {
                    m.insert("path_glob".to_owned(), json!(g));
                }
            }
        }
        Value::Object(m)
    }

    /// §11.1's shape check of `effects[i]`: an unknown key, a missing or
    /// mistyped member, a target kind the op does not take, a `field` not in
    /// §11.2 — the message names `effects[i]` and the member (the surface
    /// reports it as `filter_invalid { reason, hint: "arguments" }`).
    pub fn validate(v: &Value, i: usize) -> std::result::Result<Effect, String> {
        Effect::validate_with(v, i, None).map_err(|e| e.message)
    }

    /// [`Effect::validate`] with the shape fixes of §8 (3.4): given a
    /// [`ShapeFixContext`] — the request as written and the store's row
    /// lookup — the four shape mistakes carry their corrected call as
    /// [`ShapeError::fix`]; without one the same errors carry none.
    pub fn validate_with(
        v: &Value,
        i: usize,
        fix: Option<&ShapeFixContext<'_>>,
    ) -> std::result::Result<Effect, ShapeError> {
        let here = format!("effects[{i}]");
        let ops = "create/insert/set/unset/move/remove/split/merge/retarget";
        let obj = v
            .as_object()
            .filter(|o| o.get("op").is_some_and(Value::is_string))
            .ok_or_else(|| format!("{here}: an effect is an object whose `op` is one of {ops}"))?;
        let op = obj["op"].as_str().expect("checked");
        let fixer = Fixer::new(fix, i, obj);
        let f = fixer.as_ref();
        Ok(match op {
            "create" => {
                only_keys(obj, &["op", "path", "markdown", "frontmatter"], &here)?;
                let path = require_string(obj, "path", &here)?;
                let markdown = require_string(obj, "markdown", &here)?;
                let frontmatter = match obj.get("frontmatter") {
                    None => None,
                    Some(Value::Object(fm)) => Some(fm.clone()),
                    Some(_) => {
                        return Err(format!("{here}: `frontmatter` must be an object").into());
                    }
                };
                Effect::Create {
                    path,
                    markdown,
                    frontmatter,
                }
            }
            "insert" => {
                only_keys(obj, &["op", "into", "at", "markdown", "expect"], &here)?;
                let into = validate_target(
                    obj.get("into"),
                    &format!("{here}.into"),
                    &["document", "section", "block"],
                )?;
                let at = validate_at(obj.get("at"), &here, &into, f)?;
                let markdown = require_string(obj, "markdown", &here)?;
                let expect = validate_expect(obj.get("expect"), &here, f)?;
                Effect::Insert {
                    into,
                    at,
                    markdown,
                    expect,
                }
            }
            "set" => {
                only_keys(obj, &["op", "target", "field", "value", "expect"], &here)?;
                let target = validate_target(
                    obj.get("target"),
                    &format!("{here}.target"),
                    &["document", "block", "node"],
                )?;
                let field = require_string(obj, "field", &here)?;
                let value = obj
                    .get("value")
                    .cloned()
                    .ok_or_else(|| format!("{here}: `value` is required"))?;
                check_field(&target, &field, &here, "set", f)?;
                let expect = validate_expect(obj.get("expect"), &here, f)?;
                Effect::Set {
                    target,
                    field,
                    value,
                    expect,
                }
            }
            "unset" => {
                only_keys(obj, &["op", "target", "field", "expect"], &here)?;
                let target =
                    validate_target(obj.get("target"), &format!("{here}.target"), &["document"])?;
                let field = require_string(obj, "field", &here)?;
                check_field(&target, &field, &here, "unset", None)?;
                let expect = validate_expect(obj.get("expect"), &here, f)?;
                Effect::Unset {
                    target,
                    field,
                    expect,
                }
            }
            "move" => {
                if obj.contains_key("targets") {
                    only_keys(obj, &["op", "targets", "into", "at", "expect"], &here)?;
                    let targets = validate_targets(obj.get("targets"), &here)?;
                    let into = validate_target(
                        obj.get("into"),
                        &format!("{here}.into"),
                        &["document", "section", "block"],
                    )?;
                    let at = validate_at(obj.get("at"), &here, &into, f)?;
                    let expect = validate_expect(obj.get("expect"), &here, f)?;
                    Effect::MoveBlocks {
                        targets,
                        into,
                        at,
                        expect,
                    }
                } else {
                    only_keys(obj, &["op", "target", "to", "retarget_inbound"], &here)?;
                    let target = validate_target(
                        obj.get("target"),
                        &format!("{here}.target"),
                        &["document"],
                    )?;
                    let to = require_string(obj, "to", &here)?;
                    let retarget_inbound = match obj.get("retarget_inbound") {
                        None => true,
                        Some(Value::Bool(b)) => *b,
                        Some(_) => {
                            return Err(
                                format!("{here}: `retarget_inbound` must be a boolean").into()
                            );
                        }
                    };
                    Effect::MoveDocument {
                        target,
                        to,
                        retarget_inbound,
                    }
                }
            }
            "remove" => {
                if obj.contains_key("targets") {
                    only_keys(obj, &["op", "targets", "expect"], &here)?;
                    Effect::RemoveBlocks {
                        targets: validate_targets(obj.get("targets"), &here)?,
                        expect: validate_expect_map(obj.get("expect"), &here, f)?,
                    }
                } else {
                    only_keys(obj, &["op", "target"], &here)?;
                    Effect::RemoveDocument {
                        target: validate_target(
                            obj.get("target"),
                            &format!("{here}.target"),
                            &["document"],
                        )?,
                    }
                }
            }
            "split" => {
                only_keys(obj, &["op", "target", "at", "expect"], &here)?;
                let Target::Block { id } =
                    validate_target(obj.get("target"), &format!("{here}.target"), &["block"])?
                else {
                    unreachable!("kinds is [block]")
                };
                let at = obj
                    .get("at")
                    .and_then(Value::as_array)
                    .and_then(|a| {
                        a.iter()
                            .map(|n| n.as_u64().and_then(|n| usize::try_from(n).ok()))
                            .collect::<Option<Vec<usize>>>()
                    })
                    .ok_or_else(|| format!("{here}: `at` must be an array of byte offsets"))?;
                let expect = validate_expect(obj.get("expect"), &here, f)?;
                Effect::Split {
                    target: id,
                    at,
                    expect,
                }
            }
            "merge" => {
                only_keys(obj, &["op", "targets", "separator", "expect"], &here)?;
                Effect::Merge {
                    targets: validate_targets(obj.get("targets"), &here)?,
                    separator: optional_string(obj, "separator", &here)?,
                    expect: validate_expect_map(obj.get("expect"), &here, f)?,
                }
            }
            "retarget" => {
                only_keys(obj, &["op", "repairs", "path_glob"], &here)?;
                let repairs = obj
                    .get("repairs")
                    .and_then(Value::as_array)
                    .ok_or_else(|| format!("{here}: `repairs` must be an array of {{ from, to }}"))?
                    .iter()
                    .enumerate()
                    .map(|(j, r)| {
                        let at = format!("{here}.repairs[{j}]");
                        let r = r
                            .as_object()
                            .ok_or_else(|| format!("{at}: must be {{ from, to }}"))?;
                        only_keys(r, &["from", "to"], &at)?;
                        Ok(Repair {
                            from: require_string(r, "from", &at)?,
                            to: require_string(r, "to", &at)?,
                        })
                    })
                    .collect::<std::result::Result<Vec<_>, String>>()?;
                Effect::Retarget {
                    repairs,
                    path_glob: optional_string(obj, "path_glob", &here)?,
                }
            }
            other => {
                return Err(format!("{here}: `op` must be one of {ops} (got \"{other}\")").into());
            }
        })
    }

    /// Parse one effect (its message names `effects[0]`).
    pub fn from_json(v: &Value) -> std::result::Result<Effect, String> {
        Effect::validate(v, 0)
    }

    /// Parse an `effects` array: a non-array or an empty list is a shape
    /// error too.
    pub fn list_from_json(v: &Value) -> std::result::Result<Vec<Effect>, String> {
        let list = v
            .as_array()
            .ok_or("`effects` must be an array of effects")?;
        if list.is_empty() {
            return Err("`effects` must name at least one effect".into());
        }
        list.iter()
            .enumerate()
            .map(|(i, e)| Effect::validate(e, i))
            .collect()
    }

    /// The `expect` an effect carries, if any (not the per-block maps).
    #[must_use]
    pub fn expect(&self) -> Option<&EffectExpect> {
        match self {
            Effect::Insert { expect, .. }
            | Effect::Set { expect, .. }
            | Effect::Unset { expect, .. }
            | Effect::MoveBlocks { expect, .. }
            | Effect::Split { expect, .. } => expect.as_ref(),
            _ => None,
        }
    }

    /// `describe` (§11.3): the words a dropped duplicate's diagnostic uses —
    /// `set <field> on document <id>`, `move block b_1,block b_2`, ….
    #[must_use]
    pub fn describe(&self) -> String {
        fn name(t: &Target) -> String {
            match t {
                Target::Section { heading_id } => format!("section {heading_id}"),
                other => format!("{} {}", other.kind(), other.id().unwrap_or_default()),
            }
        }
        fn blocks(ids: &[String]) -> String {
            ids.iter()
                .map(|id| format!("block {id}"))
                .collect::<Vec<_>>()
                .join(",")
        }
        match self {
            Effect::Create { path, .. } => format!("create {path}"),
            Effect::Insert { into, .. } => format!("insert into {}", name(into)),
            Effect::Set { target, field, .. } => format!("set {field} on {}", name(target)),
            Effect::Unset { target, field, .. } => format!("unset {field} on {}", name(target)),
            Effect::MoveDocument { target, to, .. } => format!("move {} -> {to}", name(target)),
            Effect::MoveBlocks { targets, .. } => format!("move {}", blocks(targets)),
            Effect::RemoveDocument { target } => format!("remove {}", name(target)),
            Effect::RemoveBlocks { targets, .. } => format!("remove {}", blocks(targets)),
            Effect::Split { target, .. } => format!("split block {target}"),
            Effect::Merge { targets, .. } => format!("merge {}", blocks(targets)),
            Effect::Retarget { repairs, .. } => format!(
                "retarget {}",
                repairs
                    .iter()
                    .map(|r| format!("{}->{}", r.from, r.to))
                    .collect::<Vec<_>>()
                    .join(",")
            ),
        }
    }
}

// ---- fields ------------------------------------------------------------------------------

/// What a `set`/`unset` `field` names, by target kind (§11.2).
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Field<'a> {
    /// `frontmatter.<key>` of a document.
    Frontmatter(&'a str),
    /// `content` of a document: the whole-document planner.
    Content,
    /// `markdown` of a block.
    Markdown,
    /// `attrs.checked` of a block.
    Checked,
    /// An editable property of a node (`value`, `name`, `checked`).
    NodeProp(&'a str),
}

/// Classify a validated `field` for `target`.
pub fn classify_field<'a>(
    target: &Target,
    field: &'a str,
) -> std::result::Result<Field<'a>, String> {
    check_field(target, field, "field", "set", None).map_err(|e| e.message)?;
    Ok(match target {
        Target::Document { .. } => match field.strip_prefix("frontmatter.") {
            Some(key) => Field::Frontmatter(key),
            None => Field::Content,
        },
        Target::Block { .. } => {
            if field == "markdown" {
                Field::Markdown
            } else {
                Field::Checked
            }
        }
        Target::Node { .. } => Field::NodeProp(field),
        Target::Section { .. } => unreachable!("check_field rejects sections"),
    })
}

/// `$n.ids[i]` placeholders of one kernel op shifted by `offset` (an opset
/// planned alone, spliced into a longer op list — `set document.content`).
#[must_use]
pub fn shift_placeholders(op: &Op, offset: usize) -> Op {
    map_block_ids(op, |v| match crate::changeset::parse_placeholder(v) {
        Some((n, i)) => format!("${}.ids[{i}]", n + offset),
        None => v.to_owned(),
    })
}

/// Every block id a kernel op names — `block`, `blocks`, a placement's parent
/// block or section heading and its anchor, the keys of a per-block `expect`
/// map, and an `insert`'s `doc` — rewritten by `f` (§11.7: the replay turns
/// the `$new.<n>` symbols of a created document into the ids it minted).
#[must_use]
pub fn map_block_ids(op: &Op, f: impl Fn(&str) -> String) -> Op {
    let s = |v: &String| -> String { f(v) };
    let to = |t: &To| To {
        parent: match &t.parent {
            Parent::Block(id) => Parent::Block(s(id)),
            Parent::Section { heading } => Parent::Section {
                heading: s(heading),
            },
            Parent::Doc => Parent::Doc,
        },
        at: match &t.at {
            At::Before(id) => At::Before(s(id)),
            At::After(id) => At::After(s(id)),
            other => other.clone(),
        },
    };
    let map = |m: &Option<BTreeMap<String, Expect>>| -> Option<BTreeMap<String, Expect>> {
        m.as_ref()
            .map(|m| m.iter().map(|(k, e)| (s(k), e.clone())).collect())
    };
    match op {
        Op::Insert {
            doc,
            to: t,
            markdown,
            expect,
        } => Op::Insert {
            doc: doc.as_ref().map(s),
            to: to(t),
            markdown: markdown.clone(),
            expect: expect.clone(),
        },
        Op::Update {
            block,
            markdown,
            attrs,
            expect,
            trivia,
            child_ids,
        } => Op::Update {
            block: s(block),
            markdown: markdown.clone(),
            attrs: attrs.clone(),
            expect: expect.clone(),
            trivia: trivia.clone(),
            child_ids: child_ids.clone(),
        },
        Op::Move {
            blocks,
            to: t,
            doc,
            expect,
        } => Op::Move {
            blocks: blocks.iter().map(s).collect(),
            to: to(t),
            doc: doc.as_ref().map(s),
            expect: expect.clone(),
        },
        Op::Remove { blocks, expect } => Op::Remove {
            blocks: blocks.iter().map(s).collect(),
            expect: map(expect),
        },
        Op::Split { block, at, expect } => Op::Split {
            block: s(block),
            at: at.clone(),
            expect: expect.clone(),
        },
        Op::Merge {
            blocks,
            separator,
            expect,
        } => Op::Merge {
            blocks: blocks.iter().map(s).collect(),
            separator: separator.clone(),
            expect: map(expect),
        },
    }
}

// ---- focus and conflicts (decision 4, §11.3) ----------------------------------------------

/// What a focus names: `{ kind: "document" | "block" | "node" | "path", id? | path? }`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct FocusTarget {
    pub kind: &'static str,
    pub id: Option<String>,
    pub path: Option<String>,
}

impl FocusTarget {
    #[must_use]
    pub fn document(id: &str) -> Self {
        Self {
            kind: "document",
            id: Some(id.to_owned()),
            path: None,
        }
    }

    #[must_use]
    pub fn block(id: &str) -> Self {
        Self {
            kind: "block",
            id: Some(id.to_owned()),
            path: None,
        }
    }

    #[must_use]
    pub fn node(id: &str) -> Self {
        Self {
            kind: "node",
            id: Some(id.to_owned()),
            path: None,
        }
    }

    #[must_use]
    pub fn path(path: &str) -> Self {
        Self {
            kind: "path",
            id: None,
            path: Some(path.to_owned()),
        }
    }

    #[must_use]
    pub fn to_json(&self) -> Value {
        let mut m = Map::new();
        m.insert("kind".to_owned(), json!(self.kind));
        if let Some(id) = &self.id {
            m.insert("id".to_owned(), json!(id));
        }
        if let Some(path) = &self.path {
            m.insert("path".to_owned(), json!(path));
        }
        Value::Object(m)
    }
}

/// The focus of a conflict: `{ kind, target, field? }`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Focus {
    /// `scalar` or `identity`.
    pub kind: &'static str,
    pub target: FocusTarget,
    pub field: Option<String>,
}

impl Focus {
    #[must_use]
    pub fn to_json(&self) -> Value {
        let mut m = Map::new();
        m.insert("kind".to_owned(), json!(self.kind));
        m.insert("target".to_owned(), self.target.to_json());
        if let Some(f) = &self.field {
            m.insert("field".to_owned(), json!(f));
        }
        Value::Object(m)
    }
}

/// `conflicting_effects { effects: [i, j], focus, retriable: false }` (§8).
#[must_use]
pub fn conflicting_effects(i: usize, j: usize, focus: &Focus) -> MutationError {
    let who = focus
        .target
        .id
        .clone()
        .or_else(|| focus.target.path.clone())
        .unwrap_or_default();
    let what = match &focus.field {
        Some(f) => format!("{} {who} {f}", focus.target.kind),
        None => format!("{} {who}", focus.target.kind),
    };
    MutationError::with_data(
        ErrorCode::ConflictingEffects,
        format!("effects {i} and {j} contradict each other on {what}"),
        json!({ "effects": [i, j], "focus": focus.to_json(), "retriable": false }),
    )
}

/// `target_missing { symbol }` for a `$new.<n>` no earlier effect created
/// (`kind` `None`), or one of the other kind.
#[must_use]
pub fn symbol_missing(symbol: &str, kind: Option<NewIdKind>, wanted: &str) -> MutationError {
    let message = match kind {
        None => format!("{symbol} is not created by an earlier effect"),
        Some(k) => format!("{symbol} names a {}, not a {wanted}", k.as_str()),
    };
    MutationError::with_data(
        ErrorCode::TargetMissing,
        message,
        json!({ "symbol": symbol }),
    )
}

/// A scalar write: one `(target, field)` key, `set` with a value or `unset`.
#[derive(Clone, Debug, PartialEq)]
pub struct ScalarWrite {
    /// `document:<id>:<field>`, `block:<id>:<field>`, `node:<id>:<field>`.
    pub key: String,
    pub target: FocusTarget,
    pub field: String,
    /// `Some(value)` for a `set`, `None` for an `unset`.
    pub value: Option<Value>,
}

/// What one effect addresses and retires (§11.3): the planner computes it
/// against its trees and the store, the [`ConflictTracker`] judges it.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct FocusInfo {
    pub scalar: Option<ScalarWrite>,
    /// Every `(block, markdown)` focus of a `retarget` (never deduped).
    pub scalars: Vec<ScalarWrite>,
    /// The documents, blocks and paths the effect addresses.
    pub docs: Vec<String>,
    pub blocks: Vec<String>,
    pub paths: Vec<String>,
    /// What later effects may no longer address.
    pub retires_docs: Vec<String>,
    pub retires_blocks: Vec<String>,
    pub retires_paths: Vec<String>,
    /// `set document.content`: the whole document is rewritten.
    pub whole_doc: Option<String>,
}

/// The focus bookkeeping over an ordered effect list (§11.3).
#[derive(Debug, Default)]
pub struct ConflictTracker {
    scalar: HashMap<String, (usize, ScalarWrite)>,
    retired_docs: HashMap<String, usize>,
    retired_blocks: HashMap<String, usize>,
    retired_paths: HashMap<String, usize>,
    touched_docs: HashMap<String, usize>,
    /// The dropped duplicates, verbatim.
    pub diagnostics: Vec<String>,
}

impl ConflictTracker {
    /// Check effect `i`: `Ok(false)` when it is an identical duplicate to
    /// drop (a diagnostic is recorded), `Ok(true)` when it stands,
    /// `Err(conflicting_effects)` when it contradicts an earlier effect.
    pub fn check(&mut self, i: usize, info: &FocusInfo, describe: &str) -> Result<bool> {
        for d in &info.docs {
            if let Some(&by) = self.retired_docs.get(d) {
                return Err(conflicting_effects(
                    by,
                    i,
                    &identity(FocusTarget::document(d)),
                ));
            }
        }
        for b in &info.blocks {
            if let Some(&by) = self.retired_blocks.get(b) {
                return Err(conflicting_effects(by, i, &identity(FocusTarget::block(b))));
            }
        }
        for p in &info.paths {
            if let Some(&by) = self.retired_paths.get(p) {
                return Err(conflicting_effects(by, i, &identity(FocusTarget::path(p))));
            }
        }
        if let Some(d) = &info.whole_doc {
            if let Some(&by) = self.touched_docs.get(d) {
                return Err(conflicting_effects(
                    by,
                    i,
                    &identity(FocusTarget::document(d)),
                ));
            }
        }
        if let Some(s) = &info.scalar {
            if let Some((prev_i, prev)) = self.scalar.get(&s.key) {
                let identical = match (&prev.value, &s.value) {
                    (None, None) => true,
                    (Some(a), Some(b)) => canonical_json(a) == canonical_json(b),
                    _ => false,
                };
                if !identical {
                    return Err(conflicting_effects(
                        *prev_i,
                        i,
                        &Focus {
                            kind: "scalar",
                            target: s.target.clone(),
                            field: Some(s.field.clone()),
                        },
                    ));
                }
                self.diagnostics.push(format!(
                    "effect {i} ({describe}) duplicates effect {prev_i}; dropped"
                ));
                return Ok(false);
            }
        }
        for s in &info.scalars {
            if let Some((prev_i, _)) = self.scalar.get(&s.key) {
                return Err(conflicting_effects(
                    *prev_i,
                    i,
                    &Focus {
                        kind: "scalar",
                        target: s.target.clone(),
                        field: Some(s.field.clone()),
                    },
                ));
            }
        }
        // Record.
        if let Some(s) = &info.scalar {
            self.scalar.insert(s.key.clone(), (i, s.clone()));
        }
        for s in &info.scalars {
            self.scalar.insert(s.key.clone(), (i, s.clone()));
        }
        for d in &info.docs {
            self.touched_docs.entry(d.clone()).or_insert(i);
        }
        for d in &info.retires_docs {
            self.retired_docs.insert(d.clone(), i);
        }
        for b in &info.retires_blocks {
            self.retired_blocks.insert(b.clone(), i);
        }
        for p in &info.retires_paths {
            self.retired_paths.insert(p.clone(), i);
        }
        Ok(true)
    }
}

fn identity(target: FocusTarget) -> Focus {
    Focus {
        kind: "identity",
        target,
        field: None,
    }
}

// ---- canonical JSON and the digest ---------------------------------------------------------

/// §11 canonical JSON (module docs).
#[must_use]
pub fn canonical_json(v: &Value) -> String {
    let mut out = String::new();
    write_canonical(v, &mut out);
    out
}

fn write_canonical(v: &Value, out: &mut String) {
    match v {
        Value::Object(map) => {
            let mut keys: Vec<&String> = map.keys().collect();
            keys.sort_unstable_by(|a, b| a.as_bytes().cmp(b.as_bytes()));
            out.push('{');
            for (i, k) in keys.iter().enumerate() {
                if i > 0 {
                    out.push(',');
                }
                out.push_str(&Value::String((*k).clone()).to_string());
                out.push(':');
                write_canonical(&map[*k], out);
            }
            out.push('}');
        }
        Value::Array(items) => {
            out.push('[');
            for (i, item) in items.iter().enumerate() {
                if i > 0 {
                    out.push(',');
                }
                write_canonical(item, out);
            }
            out.push(']');
        }
        Value::Number(n) => out.push_str(&canonical_number(n)),
        scalar => out.push_str(&scalar.to_string()),
    }
}

/// A number as ECMAScript `JSON.stringify` prints it.
fn canonical_number(n: &serde_json::Number) -> String {
    if let Some(i) = n.as_i64() {
        return i.to_string();
    }
    if let Some(u) = n.as_u64() {
        return u.to_string();
    }
    let Some(f) = n.as_f64() else {
        return "null".to_owned();
    };
    js_number(f)
}

/// ECMAScript `Number::toString(x)` for a finite `x` (`null` otherwise).
#[must_use]
pub fn js_number(x: f64) -> String {
    const TWO_53: f64 = 9_007_199_254_740_992.0;
    if !x.is_finite() {
        return "null".to_owned();
    }
    if x == 0.0 {
        return "0".to_owned();
    }
    if x.fract() == 0.0 && x.abs() < TWO_53 {
        // Integral below 2^53: no fraction, no exponent.
        #[allow(clippy::cast_possible_truncation)]
        return (x as i64).to_string();
    }
    // Shortest round-trip digits and the decimal exponent from Rust's `{:e}`
    // (`d.ddde±X`), re-laid out per Number::toString.
    let sci = format!("{:e}", x.abs());
    let (mantissa, exp) = sci.split_once('e').expect("{:e} has an exponent");
    let exp: i32 = exp.parse().expect("{:e} exponent is an integer");
    let digits: String = mantissa.chars().filter(|c| *c != '.').collect();
    let k = digits.len() as i32;
    let n = exp + 1; // x = 0.digits × 10^n
    let mut out = String::new();
    if x < 0.0 {
        out.push('-');
    }
    if k <= n && n <= 21 {
        out.push_str(&digits);
        out.push_str(&"0".repeat((n - k) as usize));
    } else if 0 < n && n <= 21 {
        out.push_str(&digits[..n as usize]);
        out.push('.');
        out.push_str(&digits[n as usize..]);
    } else if -6 < n && n <= 0 {
        out.push_str("0.");
        out.push_str(&"0".repeat((-n) as usize));
        out.push_str(&digits);
    } else {
        let e = n - 1;
        out.push_str(&digits[..1]);
        if k > 1 {
            out.push('.');
            out.push_str(&digits[1..]);
        }
        out.push('e');
        out.push(if e < 0 { '-' } else { '+' });
        out.push_str(&e.abs().to_string());
    }
    out
}

/// `hex(sha256(canonical_json(core)))`.
#[must_use]
pub fn digest(core: &Value) -> String {
    hex(&sha256(canonical_json(core).as_bytes()))
}

// ---- the plan ----------------------------------------------------------------------------

/// `opset.creates[]` (3.0): a `create` as the plan carries it — its document
/// symbol, path, composed file, and `before_op`, the index of the first
/// kernel op planned after it (`ops.len()` when none): where `execute`
/// adopts it again so the replay mints its block ids in the plan's order.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PlanCreate {
    pub symbol: String,
    pub path: String,
    pub source: String,
    pub before_op: usize,
}

/// `opset.moves[]`: a document rename (its retarget updates are in `ops`).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PlanMove {
    pub id: String,
    pub from: String,
    pub to: String,
}

/// `opset.tombstones[]`: a `remove document`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PlanTombstone {
    pub id: String,
    pub path: String,
}

/// `opset.set_frontmatter[]`: a document's file **head** — everything before
/// its first block (frontmatter with fences and separator, or the leading
/// trivia alone).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PlanFrontmatter {
    pub doc: String,
    pub raw: String,
}

/// §11.4 `opset`: every key present (`[]` when empty); the ops in the fixture
/// spelling (`child_ids`), new structure named by kernel placeholders.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct PlanOpset {
    pub creates: Vec<PlanCreate>,
    pub moves: Vec<PlanMove>,
    pub tombstones: Vec<PlanTombstone>,
    pub set_frontmatter: Vec<PlanFrontmatter>,
    pub ops: Vec<Op>,
}

impl PlanOpset {
    #[must_use]
    pub fn to_json(&self) -> Value {
        json!({
            "creates": self.creates.iter().map(|c| json!({ "symbol": c.symbol, "path": c.path, "source": c.source, "before_op": c.before_op })).collect::<Vec<_>>(),
            "moves": self.moves.iter().map(|m| json!({ "id": m.id, "from": m.from, "to": m.to })).collect::<Vec<_>>(),
            "tombstones": self.tombstones.iter().map(|t| json!({ "id": t.id, "path": t.path })).collect::<Vec<_>>(),
            "set_frontmatter": self.set_frontmatter.iter().map(|f| json!({ "doc": f.doc, "raw": f.raw })).collect::<Vec<_>>(),
            "ops": self.ops.iter().map(Op::to_json).collect::<Vec<_>>(),
        })
    }

    pub fn from_json(v: &Value) -> std::result::Result<Self, String> {
        let obj = v.as_object().ok_or("`plan.opset` must be an object")?;
        let arr = |k: &str| -> std::result::Result<&Vec<Value>, String> {
            obj.get(k)
                .and_then(Value::as_array)
                .ok_or_else(|| format!("`plan.opset.{k}` must be an array"))
        };
        let s = |v: &Value, k: &str, here: &str| -> std::result::Result<String, String> {
            v.get(k)
                .and_then(Value::as_str)
                .map(str::to_owned)
                .ok_or_else(|| format!("`plan.opset.{here}.{k}` must be a string"))
        };
        Ok(Self {
            creates: arr("creates")?
                .iter()
                .map(|c| {
                    let str_of = |k: &str| c.get(k).and_then(Value::as_str).map(str::to_owned);
                    let before_op = c
                        .get("before_op")
                        .and_then(Value::as_u64)
                        .and_then(|n| usize::try_from(n).ok());
                    match (str_of("symbol"), str_of("path"), str_of("source"), before_op) {
                        (Some(symbol), Some(path), Some(source), Some(before_op)) => {
                            Ok(PlanCreate {
                                symbol,
                                path,
                                source,
                                before_op,
                            })
                        }
                        _ => Err(
                            "`plan.opset.creates[]` entries are { symbol, path, source, before_op }"
                                .to_owned(),
                        ),
                    }
                })
                .collect::<std::result::Result<_, String>>()?,
            moves: arr("moves")?
                .iter()
                .map(|m| {
                    Ok(PlanMove {
                        id: s(m, "id", "moves[]")?,
                        from: s(m, "from", "moves[]")?,
                        to: s(m, "to", "moves[]")?,
                    })
                })
                .collect::<std::result::Result<_, String>>()?,
            tombstones: arr("tombstones")?
                .iter()
                .map(|t| {
                    Ok(PlanTombstone {
                        id: s(t, "id", "tombstones[]")?,
                        path: s(t, "path", "tombstones[]")?,
                    })
                })
                .collect::<std::result::Result<_, String>>()?,
            set_frontmatter: arr("set_frontmatter")?
                .iter()
                .map(|f| {
                    Ok(PlanFrontmatter {
                        doc: s(f, "doc", "set_frontmatter[]")?,
                        raw: s(f, "raw", "set_frontmatter[]")?,
                    })
                })
                .collect::<std::result::Result<_, String>>()?,
            ops: arr("ops")?
                .iter()
                .map(Op::from_json)
                .collect::<std::result::Result<Vec<_>, String>>()?,
        })
    }
}

/// A document's precondition: the `DocBase` triple as `{ id, path,
/// base_revision, hash }` — `null`s kept (they are values, §11.5).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DocPrecondition {
    pub id: String,
    pub path: String,
    pub base_revision: Option<String>,
    /// Lower-case hex of `docs.file_hash`.
    pub hash: Option<String>,
}

/// A block's CAS pin: `{ id, content_hash }`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct BlockPrecondition {
    pub id: String,
    pub content_hash: String,
}

/// A caller's destination-parent pin: `{ doc, parent: <block id> | null,
/// parent_children_hash }`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ParentPrecondition {
    pub doc: String,
    pub parent: Option<String>,
    pub parent_children_hash: String,
}

/// §11.4 `preconditions`.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Preconditions {
    pub docs: Vec<DocPrecondition>,
    pub blocks: Vec<BlockPrecondition>,
    pub parents: Vec<ParentPrecondition>,
    pub absent_paths: Vec<String>,
}

impl Preconditions {
    #[must_use]
    pub fn to_json(&self) -> Value {
        json!({
            "docs": self.docs.iter().map(|d| json!({ "id": d.id, "path": d.path, "base_revision": d.base_revision, "hash": d.hash })).collect::<Vec<_>>(),
            "blocks": self.blocks.iter().map(|b| json!({ "id": b.id, "content_hash": b.content_hash })).collect::<Vec<_>>(),
            "parents": self.parents.iter().map(|p| json!({ "doc": p.doc, "parent": p.parent, "parent_children_hash": p.parent_children_hash })).collect::<Vec<_>>(),
            "absent_paths": self.absent_paths,
        })
    }

    pub fn from_json(v: &Value) -> std::result::Result<Self, String> {
        let obj = v
            .as_object()
            .ok_or("`plan.preconditions` must be an object")?;
        let arr = |k: &str| -> std::result::Result<&Vec<Value>, String> {
            obj.get(k)
                .and_then(Value::as_array)
                .ok_or_else(|| format!("`plan.preconditions.{k}` must be an array"))
        };
        let s = |v: &Value, k: &str, here: &str| -> std::result::Result<String, String> {
            v.get(k)
                .and_then(Value::as_str)
                .map(str::to_owned)
                .ok_or_else(|| format!("`plan.preconditions.{here}.{k}` must be a string"))
        };
        let opt = |v: &Value, k: &str, here: &str| -> std::result::Result<Option<String>, String> {
            match v.get(k) {
                None | Some(Value::Null) => Ok(None),
                Some(Value::String(x)) => Ok(Some(x.clone())),
                Some(_) => Err(format!(
                    "`plan.preconditions.{here}.{k}` must be a string or null"
                )),
            }
        };
        Ok(Self {
            docs: arr("docs")?
                .iter()
                .map(|d| {
                    Ok(DocPrecondition {
                        id: s(d, "id", "docs[]")?,
                        path: s(d, "path", "docs[]")?,
                        base_revision: opt(d, "base_revision", "docs[]")?,
                        hash: opt(d, "hash", "docs[]")?,
                    })
                })
                .collect::<std::result::Result<_, String>>()?,
            blocks: arr("blocks")?
                .iter()
                .map(|b| {
                    Ok(BlockPrecondition {
                        id: s(b, "id", "blocks[]")?,
                        content_hash: s(b, "content_hash", "blocks[]")?,
                    })
                })
                .collect::<std::result::Result<_, String>>()?,
            parents: arr("parents")?
                .iter()
                .map(|p| {
                    Ok(ParentPrecondition {
                        doc: s(p, "doc", "parents[]")?,
                        parent: opt(p, "parent", "parents[]")?,
                        parent_children_hash: s(p, "parent_children_hash", "parents[]")?,
                    })
                })
                .collect::<std::result::Result<_, String>>()?,
            absent_paths: arr("absent_paths")?
                .iter()
                .map(|p| {
                    p.as_str().map(str::to_owned).ok_or_else(|| {
                        "`plan.preconditions.absent_paths[]` must be strings".to_owned()
                    })
                })
                .collect::<std::result::Result<_, String>>()?,
        })
    }
}

/// The kind of identity a `$new.<n>` stands for.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum NewIdKind {
    Block,
    Document,
}

impl NewIdKind {
    #[must_use]
    pub const fn as_str(&self) -> &'static str {
        match self {
            NewIdKind::Block => "block",
            NewIdKind::Document => "document",
        }
    }

    /// The kind a mint prefix stands for (`b` / `d`).
    #[must_use]
    pub fn from_prefix(prefix: &str) -> Option<Self> {
        match prefix {
            "b" => Some(NewIdKind::Block),
            "d" => Some(NewIdKind::Document),
            _ => None,
        }
    }
}

/// `{ symbol, kind }` in allocation order.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct NewId {
    pub symbol: String,
    pub kind: NewIdKind,
}

/// A planned revision `{ id, path, hash }` (a created document's `id` is
/// its symbol).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PlanRevision {
    pub id: String,
    pub path: String,
    pub hash: String,
}

/// One planned op of a `set document.content` as `preview.identity` reports
/// it (mutate 3.0): the §7 `PlanOp` minus the op itself — `op_index` names
/// the entry of `opset.ops` it became.
#[derive(Clone, Debug, PartialEq)]
pub struct IdentityOp {
    pub op_index: usize,
    pub disposition: PlanDisposition,
    /// The carried id(s) the op acts on; empty for an insert of new structure.
    pub blocks: Vec<String>,
    pub confidence: Option<f64>,
    pub reason: Option<String>,
    /// The matcher's detail, when the planner recorded one.
    pub detail: Option<Value>,
}

/// `preview.identity[<doc id>]` (mutate 3.0): what the whole-document
/// planner (§7) decided for a `set document.content` — the `Opset`'s
/// identity fields, surfaced since the opset itself is no longer a wire
/// shape (`converges` is not here: a returned plan always converges).
#[derive(Clone, Debug, PartialEq)]
pub struct IdentityPreview {
    pub matcher_v: String,
    pub summary: OpsetSummary,
    pub ops: Vec<IdentityOp>,
    pub diagnostics: Vec<String>,
}

impl IdentityPreview {
    #[must_use]
    pub fn to_json(&self) -> Value {
        json!({
            "matcher_v": self.matcher_v,
            "summary": self.summary.to_json(),
            "ops": self.ops.iter().map(|o| {
                let mut m = Map::new();
                m.insert("op_index".to_owned(), json!(o.op_index));
                m.insert("disposition".to_owned(), json!(o.disposition.as_str()));
                m.insert("blocks".to_owned(), json!(o.blocks));
                m.insert("confidence".to_owned(), json!(o.confidence));
                m.insert("reason".to_owned(), json!(o.reason));
                if let Some(d) = &o.detail {
                    m.insert("detail".to_owned(), d.clone());
                }
                Value::Object(m)
            }).collect::<Vec<_>>(),
            "diagnostics": self.diagnostics,
        })
    }

    pub fn from_json(v: &Value) -> std::result::Result<Self, String> {
        let obj = v
            .as_object()
            .ok_or("`plan.preview.identity[]` must be an object")?;
        let matcher_v = obj
            .get("matcher_v")
            .and_then(Value::as_str)
            .ok_or("`plan.preview.identity[].matcher_v` must be a string")?
            .to_owned();
        let summary = obj
            .get("summary")
            .and_then(Value::as_object)
            .ok_or("`plan.preview.identity[].summary` must be an object")?;
        let count = |k: &str| -> usize {
            summary
                .get(k)
                .and_then(Value::as_u64)
                .and_then(|n| usize::try_from(n).ok())
                .unwrap_or(0)
        };
        let summary = OpsetSummary {
            preserved: count("preserved"),
            updated: count("updated"),
            moved: count("moved"),
            created: count("created"),
            removed: count("removed"),
            split: count("split"),
            merged: count("merged"),
            ambiguous: count("ambiguous"),
        };
        let ops = obj
            .get("ops")
            .and_then(Value::as_array)
            .ok_or("`plan.preview.identity[].ops` must be an array")?
            .iter()
            .map(|o| {
                let disposition = o
                    .get("disposition")
                    .and_then(Value::as_str)
                    .and_then(PlanDisposition::parse)
                    .ok_or("`plan.preview.identity[].ops[].disposition` is not a disposition")?;
                let op_index = o
                    .get("op_index")
                    .and_then(Value::as_u64)
                    .and_then(|n| usize::try_from(n).ok())
                    .ok_or("`plan.preview.identity[].ops[].op_index` must be an integer")?;
                Ok(IdentityOp {
                    op_index,
                    disposition,
                    blocks: o
                        .get("blocks")
                        .and_then(Value::as_array)
                        .map(|a| {
                            a.iter()
                                .filter_map(Value::as_str)
                                .map(str::to_owned)
                                .collect()
                        })
                        .unwrap_or_default(),
                    confidence: o.get("confidence").and_then(Value::as_f64),
                    reason: o.get("reason").and_then(Value::as_str).map(str::to_owned),
                    detail: o.get("detail").cloned(),
                })
            })
            .collect::<std::result::Result<Vec<_>, String>>()?;
        let diagnostics = obj
            .get("diagnostics")
            .and_then(Value::as_array)
            .map(|a| {
                a.iter()
                    .filter_map(Value::as_str)
                    .map(str::to_owned)
                    .collect()
            })
            .unwrap_or_default();
        Ok(Self {
            matcher_v,
            summary,
            ops,
            diagnostics,
        })
    }
}

/// A block a `retarget` rewrites, as `links_repair` reports it:
/// `{ id, path, oldRaw, newRaw }`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RetargetHitPreview {
    pub id: String,
    pub path: String,
    pub old_raw: String,
    pub new_raw: String,
}

/// A repair pair with how many destinations it matched: `{ from, to, hits }`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RetargetPairPreview {
    pub from: String,
    pub to: String,
    pub hits: usize,
}

/// `preview.retarget[]` (mutate 3.0): what a `retarget` effect found —
/// `{ effect_index, hits, pairs }`, the `links_repair` report the retired
/// `links_retarget { dry_run }` used to return.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RetargetPreview {
    pub effect_index: usize,
    pub hits: Vec<RetargetHitPreview>,
    pub pairs: Vec<RetargetPairPreview>,
}

impl RetargetPreview {
    #[must_use]
    pub fn to_json(&self) -> Value {
        json!({
            "effect_index": self.effect_index,
            "hits": self.hits.iter().map(|h| json!({ "id": h.id, "path": h.path, "oldRaw": h.old_raw, "newRaw": h.new_raw })).collect::<Vec<_>>(),
            "pairs": self.pairs.iter().map(|p| json!({ "from": p.from, "to": p.to, "hits": p.hits })).collect::<Vec<_>>(),
        })
    }

    pub fn from_json(v: &Value) -> std::result::Result<Self, String> {
        let obj = v
            .as_object()
            .ok_or("`plan.preview.retarget[]` must be an object")?;
        let s = |v: &Value, k: &str| -> std::result::Result<String, String> {
            v.get(k)
                .and_then(Value::as_str)
                .map(str::to_owned)
                .ok_or_else(|| format!("`plan.preview.retarget[]` {k} must be a string"))
        };
        let n = |v: &Value, k: &str| -> std::result::Result<usize, String> {
            v.get(k)
                .and_then(Value::as_u64)
                .and_then(|n| usize::try_from(n).ok())
                .ok_or_else(|| format!("`plan.preview.retarget[]` {k} must be an integer"))
        };
        Ok(Self {
            effect_index: n(v, "effect_index")?,
            hits: obj
                .get("hits")
                .and_then(Value::as_array)
                .ok_or("`plan.preview.retarget[].hits` must be an array")?
                .iter()
                .map(|h| {
                    Ok(RetargetHitPreview {
                        id: s(h, "id")?,
                        path: s(h, "path")?,
                        old_raw: s(h, "oldRaw")?,
                        new_raw: s(h, "newRaw")?,
                    })
                })
                .collect::<std::result::Result<_, String>>()?,
            pairs: obj
                .get("pairs")
                .and_then(Value::as_array)
                .ok_or("`plan.preview.retarget[].pairs` must be an array")?
                .iter()
                .map(|p| {
                    Ok(RetargetPairPreview {
                        from: s(p, "from")?,
                        to: s(p, "to")?,
                        hits: n(p, "hits")?,
                    })
                })
                .collect::<std::result::Result<_, String>>()?,
        })
    }
}

/// §11.4 `preview`: excluded from the digest, omittable on echo. `identity`
/// (per document, in effect order) and `retarget` (per effect) are present
/// on the wire only when non-empty (mutate 3.0); `summary` (3.3) always.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct PlanPreview {
    pub results: Vec<OpResult>,
    pub revisions: Vec<PlanRevision>,
    /// Path → `(before, after)`, in insertion order.
    pub diffs: Vec<(String, (String, String))>,
    /// Doc id → the whole-document planner's identity decision.
    pub identity: Vec<(String, IdentityPreview)>,
    pub retarget: Vec<RetargetPreview>,
    /// One line in words per resolved effect (3.3, [`crate::summary`]);
    /// always on the wire (`[]` for a plan with nothing to do).
    pub summary: Vec<String>,
}

impl PlanPreview {
    #[must_use]
    pub fn to_json(&self) -> Value {
        let mut diffs = Map::new();
        for (path, (before, after)) in &self.diffs {
            diffs.insert(path.clone(), json!({ "before": before, "after": after }));
        }
        let mut m = Map::new();
        m.insert(
            "results".to_owned(),
            Value::Array(self.results.iter().map(OpResult::to_json).collect()),
        );
        m.insert(
            "revisions".to_owned(),
            Value::Array(
                self.revisions
                    .iter()
                    .map(|r| json!({ "id": r.id, "path": r.path, "hash": r.hash }))
                    .collect(),
            ),
        );
        m.insert("diffs".to_owned(), Value::Object(diffs));
        m.insert("summary".to_owned(), json!(self.summary));
        if !self.identity.is_empty() {
            let mut identity = Map::new();
            for (doc, i) in &self.identity {
                identity.insert(doc.clone(), i.to_json());
            }
            m.insert("identity".to_owned(), Value::Object(identity));
        }
        if !self.retarget.is_empty() {
            m.insert(
                "retarget".to_owned(),
                Value::Array(self.retarget.iter().map(RetargetPreview::to_json).collect()),
            );
        }
        Value::Object(m)
    }

    pub fn from_json(v: &Value) -> std::result::Result<Self, String> {
        let obj = v.as_object().ok_or("`plan.preview` must be an object")?;
        let identity = obj
            .get("identity")
            .and_then(Value::as_object)
            .map(|m| {
                m.iter()
                    .map(|(doc, i)| Ok((doc.clone(), IdentityPreview::from_json(i)?)))
                    .collect::<std::result::Result<Vec<_>, String>>()
            })
            .transpose()?
            .unwrap_or_default();
        let retarget = obj
            .get("retarget")
            .and_then(Value::as_array)
            .map(|a| {
                a.iter()
                    .map(RetargetPreview::from_json)
                    .collect::<std::result::Result<Vec<_>, String>>()
            })
            .transpose()?
            .unwrap_or_default();
        let strings = |v: Option<&Value>| -> Option<Vec<String>> {
            v.and_then(Value::as_array).map(|l| {
                l.iter()
                    .filter_map(Value::as_str)
                    .map(str::to_owned)
                    .collect()
            })
        };
        let results = obj
            .get("results")
            .and_then(Value::as_array)
            .map(|a| {
                a.iter()
                    .map(|r| OpResult {
                        ids: strings(r.get("ids")).unwrap_or_default(),
                        removed: strings(r.get("removed")),
                        merged_into: strings(r.get("merged_into")),
                    })
                    .collect()
            })
            .unwrap_or_default();
        let str_of = |v: &Value, k: &str| -> std::result::Result<String, String> {
            v.get(k)
                .and_then(Value::as_str)
                .map(str::to_owned)
                .ok_or_else(|| format!("`plan.preview` {k} must be a string"))
        };
        let revisions = obj
            .get("revisions")
            .and_then(Value::as_array)
            .map(|a| {
                a.iter()
                    .map(|r| {
                        Ok(PlanRevision {
                            id: str_of(r, "id")?,
                            path: str_of(r, "path")?,
                            hash: str_of(r, "hash")?,
                        })
                    })
                    .collect::<std::result::Result<Vec<_>, String>>()
            })
            .transpose()?
            .unwrap_or_default();
        let diffs = obj
            .get("diffs")
            .and_then(Value::as_object)
            .map(|d| {
                d.iter()
                    .map(|(p, v)| Ok((p.clone(), (str_of(v, "before")?, str_of(v, "after")?))))
                    .collect::<std::result::Result<Vec<_>, String>>()
            })
            .transpose()?
            .unwrap_or_default();
        let summary = strings(obj.get("summary")).unwrap_or_default();
        Ok(Self {
            results,
            revisions,
            diffs,
            identity,
            retarget,
            summary,
        })
    }
}

/// §11.8 `selection.expect`: the caller's bound on the selection.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct SelectionExpect {
    pub max: usize,
}

/// §11.8 `selection` (3.1): the seventh member of the digested core when
/// the plan was derived from an OQX selector — the query and the templates
/// **as given** (an `{ oqx }` slot intact; never the rewritten tree), the
/// bound, the hit count and the hit ids in result order. A hit that appears
/// or vanishes between `plan` and `execute` changes `identities`, so the
/// digest form is `plan_mismatch` without re-running anything but the plan.
#[derive(Clone, Debug, PartialEq)]
pub struct Selection {
    pub query: String,
    pub expect: Option<SelectionExpect>,
    pub templates: Vec<Value>,
    pub cardinality: usize,
    pub identities: Vec<String>,
}

impl Selection {
    /// `{ query, expect?, templates, cardinality, identities }`; `expect`
    /// absent when none was given.
    #[must_use]
    pub fn to_json(&self) -> Value {
        let mut m = Map::new();
        m.insert("query".to_owned(), json!(self.query));
        if let Some(e) = &self.expect {
            m.insert("expect".to_owned(), json!({ "max": e.max }));
        }
        m.insert("templates".to_owned(), Value::Array(self.templates.clone()));
        m.insert("cardinality".to_owned(), json!(self.cardinality));
        m.insert("identities".to_owned(), json!(self.identities));
        Value::Object(m)
    }

    pub fn from_json(v: &Value) -> std::result::Result<Self, String> {
        let obj = v.as_object().ok_or("`plan.selection` must be an object")?;
        only_keys(
            obj,
            &["query", "expect", "templates", "cardinality", "identities"],
            "`plan.selection`",
        )?;
        let query = obj
            .get("query")
            .and_then(Value::as_str)
            .ok_or("`plan.selection.query` must be a string")?
            .to_owned();
        let expect = match obj.get("expect") {
            None => None,
            Some(e) => {
                let e = e
                    .as_object()
                    .ok_or("`plan.selection.expect` must be { max }")?;
                only_keys(e, &["max"], "`plan.selection.expect`")?;
                let max = e
                    .get("max")
                    .and_then(Value::as_u64)
                    .and_then(|n| usize::try_from(n).ok())
                    .ok_or("`plan.selection.expect.max` must be a non-negative integer")?;
                Some(SelectionExpect { max })
            }
        };
        let templates = obj
            .get("templates")
            .and_then(Value::as_array)
            .filter(|t| !t.is_empty())
            .ok_or("`plan.selection.templates` must be a non-empty array")?
            .clone();
        let cardinality = obj
            .get("cardinality")
            .and_then(Value::as_u64)
            .and_then(|n| usize::try_from(n).ok())
            .ok_or("`plan.selection.cardinality` must be a non-negative integer")?;
        let identities = obj
            .get("identities")
            .and_then(Value::as_array)
            .ok_or("`plan.selection.identities` must be an array of ids")?
            .iter()
            .map(|id| {
                id.as_str()
                    .map(str::to_owned)
                    .ok_or_else(|| "`plan.selection.identities[]` must be strings".to_owned())
            })
            .collect::<std::result::Result<Vec<_>, String>>()?;
        if identities.len() != cardinality {
            return Err(
                "`plan.selection.cardinality` must equal the number of identities".to_owned(),
            );
        }
        Ok(Self {
            query,
            expect,
            templates,
            cardinality,
            identities,
        })
    }
}

/// §11.4 `Plan`.
#[derive(Clone, Debug, PartialEq)]
pub struct Plan {
    pub version: u64,
    pub planner_v: String,
    /// The effects with their targets resolved; `$new.<n>` kept symbolic;
    /// dropped duplicates excluded.
    pub effects: Vec<Effect>,
    pub opset: PlanOpset,
    pub preconditions: Preconditions,
    pub new_ids: Vec<NewId>,
    /// §11.8: present when the plan was derived from a selector (digested).
    pub selection: Option<Selection>,
    /// §11.8 "Sugar" (3.2): the effects **as written** when a selector-less
    /// request carried a `-> ` leader or an `{ oqx }` directive that was
    /// evaluated in its target's row scope — outside the digest (a plain
    /// request produces none, so no existing `plan_id` moves), on the wire,
    /// and in the intent record as `templates`.
    pub templates: Option<Vec<Value>>,
    pub plan_id: String,
    pub diagnostics: Vec<String>,
    pub preview: Option<PlanPreview>,
}

/// Why a plan handed to `execute` was not admitted (§11.7).
#[derive(Clone, Debug, PartialEq)]
pub enum Admission {
    /// `unsupported_plan_version` or `plan_mismatch`.
    Refused(MutationError),
    /// A missing or mistyped core member (`filter_invalid`).
    Invalid(String),
}

impl Plan {
    /// The executable core the digest covers: `{ version, planner_v,
    /// effects, opset, preconditions, new_ids, selection? }` (`selection`
    /// only when present, §11.8).
    #[must_use]
    pub fn core_json(&self) -> Value {
        let mut core = json!({
            "version": self.version,
            "planner_v": self.planner_v,
            "effects": self.effects.iter().map(Effect::to_json).collect::<Vec<_>>(),
            "opset": self.opset.to_json(),
            "preconditions": self.preconditions.to_json(),
            "new_ids": self.new_ids.iter().map(|n| json!({ "symbol": n.symbol, "kind": n.kind.as_str() })).collect::<Vec<_>>(),
        });
        if let Some(sel) = &self.selection {
            core["selection"] = sel.to_json();
        }
        core
    }

    /// `hex(sha256(canonical(core)))`.
    #[must_use]
    pub fn digest(&self) -> String {
        digest(&self.core_json())
    }

    /// The plan with `plan_id` recomputed over its core.
    #[must_use]
    pub fn sealed(mut self) -> Self {
        self.plan_id = self.digest();
        self
    }

    /// The wire form; `preview` only when present and `with_preview`.
    #[must_use]
    pub fn to_json(&self, with_preview: bool) -> Value {
        let Value::Object(mut m) = self.core_json() else {
            unreachable!("core_json is an object")
        };
        if let Some(t) = &self.templates {
            m.insert("templates".to_owned(), Value::Array(t.clone()));
        }
        m.insert("plan_id".to_owned(), json!(self.plan_id));
        m.insert("diagnostics".to_owned(), json!(self.diagnostics));
        if with_preview {
            if let Some(p) = &self.preview {
                m.insert("preview".to_owned(), p.to_json());
            }
        }
        Value::Object(m)
    }

    /// Parse a well-formed plan (`version` must already be 1: use
    /// [`Plan::admit`] for a client's object).
    pub fn from_json(v: &Value) -> std::result::Result<Plan, String> {
        let obj = v.as_object().ok_or("`plan` must be an object")?;
        for k in [
            "planner_v",
            "effects",
            "opset",
            "preconditions",
            "new_ids",
            "plan_id",
        ] {
            if !obj.contains_key(k) {
                return Err(format!("`plan.{k}` is required"));
            }
        }
        let version = obj
            .get("version")
            .and_then(Value::as_u64)
            .ok_or("`plan.version` must be an integer")?;
        let planner_v = obj["planner_v"]
            .as_str()
            .ok_or("`plan.planner_v` must be a string")?
            .to_owned();
        let effects = obj["effects"]
            .as_array()
            .ok_or("`plan.effects` must be an array")?
            .iter()
            .enumerate()
            .map(|(i, e)| Effect::validate(e, i))
            .collect::<std::result::Result<Vec<_>, String>>()?;
        let opset = PlanOpset::from_json(&obj["opset"])?;
        let preconditions = Preconditions::from_json(&obj["preconditions"])?;
        let new_ids = obj["new_ids"]
            .as_array()
            .ok_or("`plan.new_ids` must be an array")?
            .iter()
            .map(|n| {
                let kind = match n.get("kind").and_then(Value::as_str) {
                    Some("block") => NewIdKind::Block,
                    Some("document") => NewIdKind::Document,
                    _ => return Err("`plan.new_ids[].kind` must be block or document".to_owned()),
                };
                let symbol = n
                    .get("symbol")
                    .and_then(Value::as_str)
                    .ok_or("`plan.new_ids[].symbol` must be a string")?
                    .to_owned();
                Ok(NewId { symbol, kind })
            })
            .collect::<std::result::Result<Vec<_>, String>>()?;
        let plan_id = obj["plan_id"]
            .as_str()
            .ok_or("`plan.plan_id` must be a string")?
            .to_owned();
        let diagnostics = obj
            .get("diagnostics")
            .and_then(Value::as_array)
            .map(|a| {
                a.iter()
                    .filter_map(Value::as_str)
                    .map(str::to_owned)
                    .collect()
            })
            .unwrap_or_default();
        let preview = match obj.get("preview") {
            None | Some(Value::Null) => None,
            Some(p) => Some(PlanPreview::from_json(p)?),
        };
        // §11.8: an optional member — `null` is not "absent" (a value stays a
        // value under the canonical rules, so a client's `selection: null`
        // would digest differently from the planner's omission).
        let selection = match obj.get("selection") {
            None => None,
            Some(s) => Some(Selection::from_json(s)?),
        };
        // 3.2: the selector-less sugar's record of the effects as written;
        // outside the digest, so a client may drop it — never mistype it.
        let templates = match obj.get("templates") {
            None | Some(Value::Null) => None,
            Some(t) => Some(
                t.as_array()
                    .ok_or("`plan.templates` must be an array of effects as written")?
                    .clone(),
            ),
        };
        Ok(Plan {
            version,
            planner_v,
            effects,
            opset,
            preconditions,
            new_ids,
            selection,
            templates,
            plan_id,
            diagnostics,
            preview,
        })
    }

    /// §11.7 admission of a client's plan object, in this order: `version`
    /// ≠ 1 → `unsupported_plan_version` (before any other member is read);
    /// a missing or mistyped core member → invalid; the recomputed digest
    /// ≠ `plan_id` → `plan_mismatch { expected, actual }`.
    pub fn admit(v: &Value) -> std::result::Result<Plan, Admission> {
        let obj = v
            .as_object()
            .ok_or_else(|| Admission::Invalid("`plan` must be an object".into()))?;
        let version = obj.get("version").cloned().unwrap_or(Value::Null);
        if version != json!(PLAN_VERSION) {
            return Err(Admission::Refused(unsupported_plan_version(&version)));
        }
        let plan = Plan::from_json(v).map_err(Admission::Invalid)?;
        let actual = plan.digest();
        if actual != plan.plan_id {
            return Err(Admission::Refused(plan_mismatch(&plan.plan_id, &actual)));
        }
        Ok(plan)
    }
}

/// `unsupported_plan_version { version, supported: [1] }`.
#[must_use]
pub fn unsupported_plan_version(version: &Value) -> MutationError {
    MutationError::with_data(
        ErrorCode::UnsupportedPlanVersion,
        format!("plan version {version} is not supported (supported: {PLAN_VERSION})"),
        json!({ "version": version, "supported": [PLAN_VERSION] }),
    )
}

/// `plan_mismatch { expected, actual }`: the digest a caller named against
/// the one the plan's core (or a re-plan) yields.
#[must_use]
pub fn plan_mismatch(expected: &str, actual: &str) -> MutationError {
    MutationError::with_data(
        ErrorCode::PlanMismatch,
        "the plan's digest does not match its plan_id; it was edited or produced by a different planner — re-plan",
        json!({ "expected": expected, "actual": actual }),
    )
}

/// §11.7 `plan_mismatch` of the digest form (`execute { plan_id, effects }`):
/// the re-plan's digest is not the `plan_id` given — the effects, or the
/// documents they target, changed since the plan was made.
#[must_use]
pub fn plan_mismatch_replanned(expected: &str, actual: &str) -> MutationError {
    MutationError::with_data(
        ErrorCode::PlanMismatch,
        "the effects or the documents they target changed since the plan was made; re-plan",
        json!({ "expected": expected, "actual": actual }),
    )
}

/// The intent record an effect-driven commit stores in `commits.ops`
/// (ADR-003): `canonical({ v: 1, plan_id, effects, selection?, templates? })`
/// — `selection` only when the plan carried one (§11.8), `templates` only
/// when a selector-less request wrote `-> ` / `{ oqx }` slots (3.2, §11.8
/// "Sugar": the effects as written).
#[must_use]
pub fn intent_record(
    plan_id: &str,
    effects: &[Effect],
    selection: Option<&Selection>,
    templates: Option<&[Value]>,
) -> String {
    let mut record = json!({
        "v": 1,
        "plan_id": plan_id,
        "effects": effects.iter().map(Effect::to_json).collect::<Vec<_>>(),
    });
    if let Some(sel) = selection {
        record["selection"] = sel.to_json();
    }
    if let Some(t) = templates {
        record["templates"] = Value::Array(t.to_vec());
    }
    canonical_json(&record)
}

#[cfg(test)]
mod tests {
    use super::*;

    fn doc(id: &str, path: &str) -> Target {
        Target::Document {
            id: Some(id.into()),
            path: Some(path.into()),
        }
    }

    fn fm_set(key: &str, value: Value) -> Effect {
        Effect::Set {
            target: doc("d_0", "a.md"),
            field: format!("frontmatter.{key}"),
            value,
            expect: None,
        }
    }

    fn scalar(key: &str, target: FocusTarget, field: &str, value: Option<Value>) -> FocusInfo {
        FocusInfo {
            scalar: Some(ScalarWrite {
                key: key.into(),
                target,
                field: field.into(),
                value,
            }),
            docs: vec!["d_0".into()],
            ..Default::default()
        }
    }

    #[test]
    fn symbols_parse() {
        assert_eq!(parse_new_symbol("$new.0"), Some(0));
        assert_eq!(parse_new_symbol("$new.12"), Some(12));
        assert_eq!(parse_new_symbol("$new."), None);
        assert_eq!(parse_new_symbol("$new.a"), None);
        assert_eq!(parse_new_symbol("b_0"), None);
        assert_eq!(new_symbol(3), "$new.3");
    }

    #[test]
    fn effects_validate_and_round_trip_through_json() {
        let effects = json!([
            { "op": "create", "path": "n.md", "markdown": "# N", "frontmatter": { "k": 1 } },
            { "op": "insert", "into": { "kind": "section", "heading_id": "b_1" }, "at": "end", "markdown": "x" },
            { "op": "insert", "into": { "kind": "document", "id": "d_0", "path": "a.md" }, "at": { "after": "b_1" }, "markdown": "x", "expect": { "parent_children_hash": "cd", "revision": "r_0" } },
            { "op": "set", "target": { "kind": "document", "path": "a.md" }, "field": "frontmatter.status", "value": "done" },
            { "op": "set", "target": { "kind": "block", "id": "b_1" }, "field": "attrs.checked", "value": true, "expect": { "content_hash": "ab" } },
            { "op": "set", "target": { "kind": "node", "id": "n_1" }, "field": "value", "value": 3 },
            { "op": "unset", "target": { "kind": "document", "id": "d_0" }, "field": "frontmatter.old" },
            { "op": "move", "target": { "kind": "document", "id": "d_0" }, "to": "b.md", "retarget_inbound": true },
            { "op": "move", "targets": [{ "kind": "block", "id": "b_1" }], "into": { "kind": "block", "id": "b_2" }, "at": "start" },
            { "op": "remove", "target": { "kind": "document", "id": "d_0" } },
            { "op": "remove", "targets": [{ "kind": "block", "id": "b_1" }], "expect": { "b_1": { "content_hash": "ab" } } },
            { "op": "split", "target": { "kind": "block", "id": "b_1" }, "at": [3] },
            { "op": "merge", "targets": [{ "kind": "block", "id": "b_1" }, { "kind": "block", "id": "b_2" }], "separator": " " },
            { "op": "retarget", "repairs": [{ "from": "a.md", "to": "b.md" }], "path_glob": "notes/*" },
        ]);
        let parsed = Effect::list_from_json(&effects).unwrap();
        assert_eq!(parsed.len(), 14);
        for (v, e) in effects.as_array().unwrap().iter().zip(&parsed) {
            assert_eq!(e.to_json(), *v, "{}", e.name());
        }
        // Defaults materialize on the way out (`at`, `retarget_inbound`).
        let e = Effect::from_json(&json!({ "op": "move", "target": { "kind": "document", "path": "a.md" }, "to": "b.md" })).unwrap();
        assert_eq!(e.to_json()["retarget_inbound"], json!(true));
        let e = Effect::from_json(
            &json!({ "op": "insert", "into": { "kind": "block", "id": "b_1" }, "markdown": "x" }),
        )
        .unwrap();
        assert_eq!(e.to_json()["at"], json!("end"));
        // Shape errors name the effect and the member.
        let bad = |v: Value| Effect::validate(&v, 2).unwrap_err();
        assert!(bad(json!({ "op": "nope" })).starts_with("effects[2]: `op` must be one of"));
        assert_eq!(
            bad(
                json!({ "op": "set", "target": { "kind": "block", "id": "b" }, "field": "markdown" })
            ),
            "effects[2]: `value` is required"
        );
        assert!(
            bad(json!({ "op": "move", "target": { "kind": "block", "id": "b" }, "to": "x" }))
                .contains("`kind` must be one of document")
        );
        assert!(
            bad(json!({ "op": "create", "path": "x.md", "markdown": "", "extra": 1 }))
                .contains("unknown key `extra`")
        );
        assert!(
            bad(json!({ "op": "remove", "targets": ["b_1"] }))
                .contains("effects[2].targets[0]: a target is")
        );
        assert!(bad(json!({ "op": "remove", "targets": [] })).contains("non-empty"));
        assert!(bad(json!({ "op": "set", "target": { "kind": "document", "path": "a.md" }, "field": "title", "value": 1 })).contains("a document's `field` is `frontmatter.<key>` or `content`"));
        assert!(bad(json!({ "op": "unset", "target": { "kind": "document", "path": "a.md" }, "field": "content" })).contains("(got \"content\")"));
        assert!(bad(json!({ "op": "set", "target": { "kind": "node", "id": "n" }, "field": "a.b", "value": 1 })).contains("editable properties"));
        assert!(bad(json!({ "op": "insert", "into": { "kind": "document", "path": "a.md" }, "at": { "before": "b", "after": "c" }, "markdown": "x" })).contains("`at` must be"));
        assert!(Effect::list_from_json(&json!([])).is_err());
        assert!(Effect::list_from_json(&json!({})).is_err());
    }

    #[test]
    fn describe_and_classify() {
        assert_eq!(
            fm_set("status", json!(1)).describe(),
            "set frontmatter.status on document d_0"
        );
        let mv = Effect::MoveBlocks {
            targets: vec!["b_1".into(), "b_2".into()],
            into: Target::Section {
                heading_id: "b_0".into(),
            },
            at: At::End,
            expect: None,
        };
        assert_eq!(mv.describe(), "move block b_1,block b_2");
        let rt = Effect::Retarget {
            repairs: vec![Repair {
                from: "a".into(),
                to: "b".into(),
            }],
            path_glob: None,
        };
        assert_eq!(rt.describe(), "retarget a->b");
        assert_eq!(
            classify_field(&doc("d_0", "a.md"), "frontmatter.status"),
            Ok(Field::Frontmatter("status"))
        );
        assert_eq!(
            classify_field(&doc("d_0", "a.md"), "content"),
            Ok(Field::Content)
        );
        assert_eq!(
            classify_field(&Target::Block { id: "b".into() }, "attrs.checked"),
            Ok(Field::Checked)
        );
        assert_eq!(
            classify_field(&Target::Node { id: "n".into() }, "value"),
            Ok(Field::NodeProp("value"))
        );
        assert!(
            classify_field(
                &Target::Section {
                    heading_id: "h".into()
                },
                "x"
            )
            .is_err()
        );
    }

    #[test]
    fn placeholders_shift() {
        let op = Op::Move {
            blocks: vec!["$0.ids[1]".into(), "b_3".into()],
            to: To {
                parent: Parent::Block("$1.ids[0]".into()),
                at: At::After("$2.ids[0]".into()),
            },
            doc: None,
            expect: None,
        };
        assert_eq!(
            shift_placeholders(&op, 5).to_json(),
            json!({ "op": "move", "blocks": ["$5.ids[1]", "b_3"], "to": { "parent": "$6.ids[0]", "at": { "after": "$7.ids[0]" } } })
        );
    }

    #[test]
    fn the_tracker_dedupes_identical_scalars_and_refuses_the_rest() {
        let mut t = ConflictTracker::default();
        let write = |v: Option<Value>| {
            scalar(
                "document:d_0:frontmatter.status",
                FocusTarget::document("d_0"),
                "frontmatter.status",
                v,
            )
        };
        assert!(
            t.check(
                0,
                &write(Some(json!("done"))),
                "set frontmatter.status on document d_0"
            )
            .unwrap()
        );
        assert!(
            !t.check(
                1,
                &write(Some(json!("done"))),
                "set frontmatter.status on document d_0"
            )
            .unwrap()
        );
        assert_eq!(
            t.diagnostics,
            ["effect 1 (set frontmatter.status on document d_0) duplicates effect 0; dropped"]
        );
        let e = t.check(2, &write(Some(json!("open"))), "x").unwrap_err();
        assert_eq!(e.code, ErrorCode::ConflictingEffects);
        assert_eq!(
            e.to_json(),
            json!({ "code": "conflicting_effects", "effects": [0, 2], "focus": { "kind": "scalar", "target": { "kind": "document", "id": "d_0" }, "field": "frontmatter.status" }, "retriable": false })
        );
        // set then unset
        let e = t.check(3, &write(None), "x").unwrap_err();
        assert_eq!(e.data["effects"], json!([0, 3]));
        // A retarget's scalars never dedupe.
        let mut t = ConflictTracker::default();
        let hit = FocusInfo {
            scalars: vec![ScalarWrite {
                key: "block:b_1:markdown".into(),
                target: FocusTarget::block("b_1"),
                field: "markdown".into(),
                value: None,
            }],
            blocks: vec!["b_1".into()],
            ..Default::default()
        };
        assert!(t.check(0, &hit, "retarget").unwrap());
        let e = t.check(1, &hit, "retarget").unwrap_err();
        assert_eq!(
            e.data["focus"]["target"],
            json!({ "kind": "block", "id": "b_1" })
        );
    }

    #[test]
    fn the_tracker_enforces_identity_retirements() {
        let mut t = ConflictTracker::default();
        let remove = FocusInfo {
            docs: vec!["d_0".into()],
            blocks: vec!["b_1".into()],
            retires_blocks: vec!["b_1".into(), "b_2".into()],
            ..Default::default()
        };
        assert!(t.check(0, &remove, "remove block b_1").unwrap());
        let touch_child = FocusInfo {
            docs: vec!["d_0".into()],
            blocks: vec!["b_2".into()],
            ..Default::default()
        };
        let e = t.check(1, &touch_child, "x").unwrap_err();
        assert_eq!(
            e.data["focus"],
            json!({ "kind": "identity", "target": { "kind": "block", "id": "b_2" } })
        );
        // A path retired by a move; a create there.
        let mut t = ConflictTracker::default();
        let mv = FocusInfo {
            docs: vec!["d_0".into()],
            paths: vec!["moved/a.md".into()],
            retires_paths: vec!["a.md".into()],
            ..Default::default()
        };
        assert!(t.check(0, &mv, "move").unwrap());
        let create = FocusInfo {
            paths: vec!["a.md".into()],
            ..Default::default()
        };
        let e = t.check(1, &create, "create a.md").unwrap_err();
        assert_eq!(
            e.data["focus"],
            json!({ "kind": "identity", "target": { "kind": "path", "path": "a.md" } })
        );
        // `set content` after any touch of the document.
        let mut t = ConflictTracker::default();
        let insert = FocusInfo {
            docs: vec!["d_0".into()],
            blocks: vec!["b_2".into()],
            ..Default::default()
        };
        assert!(t.check(0, &insert, "insert").unwrap());
        let content = FocusInfo {
            scalar: Some(ScalarWrite {
                key: "document:d_0:content".into(),
                target: FocusTarget::document("d_0"),
                field: "content".into(),
                value: Some(json!("x")),
            }),
            docs: vec!["d_0".into()],
            whole_doc: Some("d_0".into()),
            ..Default::default()
        };
        let e = t
            .check(1, &content, "set content on document d_0")
            .unwrap_err();
        assert_eq!(
            e.data["focus"],
            json!({ "kind": "identity", "target": { "kind": "document", "id": "d_0" } })
        );
        // A removed document: its id is retired.
        let mut t = ConflictTracker::default();
        let rm = FocusInfo {
            docs: vec!["d_0".into()],
            retires_docs: vec!["d_0".into()],
            ..Default::default()
        };
        assert!(t.check(0, &rm, "remove document d_0").unwrap());
        let e = t.check(1, &insert, "insert").unwrap_err();
        assert_eq!(
            e.data["focus"]["target"],
            json!({ "kind": "document", "id": "d_0" })
        );
        let m = symbol_missing("$new.5", None, "block");
        assert_eq!(
            m.to_json(),
            json!({ "code": "target_missing", "symbol": "$new.5" })
        );
        let m = symbol_missing("$new.0", Some(NewIdKind::Document), "block");
        assert!(m.message.contains("names a document, not a block"));
    }

    #[test]
    fn canonical_json_sorts_keys_and_prints_numbers_like_javascript() {
        let v = json!({ "b": [1, 2.0, 2.5, -0.0, 1e21, 1e-7, 123456789012345680000.0, 0.000001, 1.5e300],
                        "a": { "z": null, "y": "q\"\n\u{1}é" }, "c": true });
        assert_eq!(
            canonical_json(&v),
            "{\"a\":{\"y\":\"q\\\"\\n\\u0001é\",\"z\":null},\"b\":[1,2,2.5,0,1e+21,1e-7,123456789012345680000,0.000001,1.5e+300],\"c\":true}"
        );
        assert_eq!(js_number(9007199254740993.0), "9007199254740992");
        assert_eq!(js_number(0.1), "0.1");
        assert_eq!(js_number(0.30000000000000004), "0.30000000000000004");
        assert_eq!(js_number(-1.5), "-1.5");
        assert_eq!(js_number(1e-6), "0.000001");
        assert_eq!(js_number(1.2e-7), "1.2e-7");
        assert_eq!(js_number(f64::NAN), "null");
        assert_eq!(js_number(100.0), "100");
        assert_eq!(js_number(1e20), "100000000000000000000");
        assert_eq!(js_number(1.7976931348623157e308), "1.7976931348623157e+308");
        assert_eq!(js_number(5e-324), "5e-324");
        // §11.5: the empty core digests to the pinned value (`p1`, the 2.3
        // vector) — and under the current planner version to its own.
        let empty = json!({ "version": 1, "planner_v": "p1", "effects": [], "opset": { "creates": [], "moves": [], "tombstones": [], "set_frontmatter": [], "ops": [] }, "preconditions": { "docs": [], "blocks": [], "parents": [], "absent_paths": [] }, "new_ids": [] });
        assert_eq!(
            digest(&empty),
            "a20097a9c319b59a1313c83e1fd494bbb3cf4895040fbbddd2866e56b16cddd3"
        );
        let mut current = empty.clone();
        current["planner_v"] = json!(PLANNER_V);
        assert_eq!(
            digest(&current),
            "5051e40051314fa855721d1943b42a9acb867c79a7b49eb4db0fd811559289ff"
        );
        // `p2` (the 3.0 vector) is still pinned: a plan echoed from a 3.0
        // planner is `plan_mismatch`, not a shape error.
        current["planner_v"] = json!("p2");
        assert_eq!(
            digest(&current),
            "6f43b302fdcd58ca4fd182b21a5bdab6fee3787ddc074f5e7c5c23b2cc368bf9"
        );
        // The spec's number vector (`effects::digest-vectors`), byte for byte.
        let numbers: Value = serde_json::from_str(
            "[1, 1.5, 0.30000000000000004, 1e+21, 1e-07, 9007199254740992, 1.7976931348623157e+308, -2.5, 100, 123456789012345680000]",
        )
        .unwrap();
        assert_eq!(
            canonical_json(&numbers),
            "[1,1.5,0.30000000000000004,1e+21,1e-7,9007199254740992,1.7976931348623157e+308,-2.5,100,123456789012345680000]"
        );
        // `z` before `é`; `/` and non-ASCII literal; lower-case `\u001f`.
        assert_eq!(
            canonical_json(&json!({ "é": "e", "z": 0 })),
            "{\"z\":0,\"é\":\"e\"}"
        );
        assert_eq!(canonical_json(&json!("a/b\u{1f}é😀")), "\"a/b\\u001fé😀\"");
    }

    /// 3.2 (§11.8 "Sugar"): `templates` — the effects as written of a
    /// selector-less request that evaluated an expression — rides outside the
    /// digest: on the wire and in the intent record, never in the core, so a
    /// plan with it has the literal plan's `plan_id`; admission keeps it and
    /// refuses a mistyped one; `null` is an omission.
    #[test]
    fn templates_ride_outside_the_digest() {
        let bare = Plan {
            version: PLAN_VERSION,
            planner_v: PLANNER_V.into(),
            effects: vec![fm_set("status", json!("done"))],
            opset: PlanOpset::default(),
            preconditions: Preconditions::default(),
            new_ids: vec![],
            selection: None,
            templates: None,
            plan_id: String::new(),
            diagnostics: vec![],
            preview: None,
        }
        .sealed();
        let written = vec![
            json!({ "op": "set", "target": "a.md", "field": "frontmatter.status", "value": "-> `done`" }),
        ];
        let sugared = Plan {
            templates: Some(written.clone()),
            ..bare.clone()
        }
        .sealed();
        assert_eq!(sugared.plan_id, bare.plan_id);
        assert!(sugared.core_json().get("templates").is_none());
        assert!(bare.to_json(false).get("templates").is_none());
        let wire = sugared.to_json(false);
        assert_eq!(wire["templates"], Value::Array(written.clone()));
        assert_eq!(Plan::admit(&wire).unwrap(), sugared);
        let mut nulled = wire.clone();
        nulled["templates"] = Value::Null;
        assert_eq!(Plan::admit(&nulled).unwrap(), bare);
        let mut mistyped = wire;
        mistyped["templates"] = json!("x");
        assert!(matches!(
            Plan::admit(&mistyped),
            Err(Admission::Invalid(m)) if m.contains("`plan.templates` must be an array")
        ));
        let plain = intent_record(&bare.plan_id, &bare.effects, None, None);
        assert!(!plain.contains("templates"), "{plain}");
        let record = intent_record(
            &sugared.plan_id,
            &sugared.effects,
            None,
            sugared.templates.as_deref(),
        );
        assert!(
            record.ends_with(
                "\"templates\":[{\"field\":\"frontmatter.status\",\"op\":\"set\",\"target\":\"a.md\",\"value\":\"-> `done`\"}],\"v\":1}"
            ),
            "{record}"
        );
    }

    #[test]
    fn a_plan_digests_its_core_and_round_trips() {
        let plan = Plan {
            version: PLAN_VERSION,
            planner_v: PLANNER_V.into(),
            effects: vec![fm_set("status", json!("done"))],
            templates: None,
            opset: PlanOpset {
                set_frontmatter: vec![PlanFrontmatter {
                    doc: "d_0".into(),
                    raw: "---\nstatus: done\n---\n\n".into(),
                }],
                ..Default::default()
            },
            preconditions: Preconditions {
                docs: vec![DocPrecondition {
                    id: "d_0".into(),
                    path: "a.md".into(),
                    base_revision: Some("r_0".into()),
                    hash: None,
                }],
                ..Default::default()
            },
            new_ids: vec![NewId {
                symbol: "$new.0".into(),
                kind: NewIdKind::Block,
            }],
            selection: None,
            plan_id: String::new(),
            diagnostics: vec![],
            preview: Some(PlanPreview::default()),
        }
        .sealed();
        assert_eq!(plan.plan_id.len(), 64);
        assert_eq!(plan.plan_id, digest(&plan.core_json()));
        let wire = plan.to_json(true);
        assert!(wire.get("preview").is_some());
        assert_eq!(
            wire["preconditions"]["docs"][0]["hash"],
            Value::Null,
            "a null value stays"
        );
        assert_eq!(wire["opset"]["creates"], json!([]));
        let back = Plan::from_json(&wire).unwrap();
        assert_eq!(back, plan);
        let trimmed = plan.to_json(false);
        assert!(trimmed.get("preview").is_none());
        assert_eq!(Plan::admit(&trimmed).unwrap().digest(), plan.plan_id);
        // Admission: version first, then shape, then the digest.
        let mut v2 = trimmed.clone();
        v2["version"] = json!(2);
        v2["opset"] = json!({});
        match Plan::admit(&v2) {
            Err(Admission::Refused(m)) => {
                assert_eq!(m.code, ErrorCode::UnsupportedPlanVersion);
                assert_eq!(m.data["supported"], json!([1]));
                assert_eq!(m.data["version"], json!(2));
            }
            other => panic!("{other:?}"),
        }
        let mut bare = trimmed.clone();
        bare["opset"] = json!({});
        assert!(
            matches!(Plan::admit(&bare), Err(Admission::Invalid(m)) if m.contains("opset.creates"))
        );
        let mut tampered = trimmed.clone();
        tampered["effects"] = json!([]);
        match Plan::admit(&tampered) {
            Err(Admission::Refused(m)) => {
                assert_eq!(m.code, ErrorCode::PlanMismatch);
                assert_eq!(m.data["expected"], json!(plan.plan_id));
                assert_ne!(m.data["actual"], json!(plan.plan_id));
            }
            other => panic!("{other:?}"),
        }
        let record = intent_record(&plan.plan_id, &plan.effects, None, None);
        assert!(
            record.starts_with("{\"effects\":[{\"field\":\"frontmatter.status\""),
            "{record}"
        );
        assert!(record.ends_with("\"v\":1}"));
        assert!(!record.contains("selection"));
    }

    /// §11.8: `selection` is the seventh core member — digested when present,
    /// omitted (never `null`) when absent; `expect` likewise inside it; the
    /// intent record carries it; admission reads it back and refuses a
    /// malformed one as a shape error.
    #[test]
    fn a_selection_is_digested_and_round_trips() {
        let selection = Selection {
            query: "from docs where status == \"completed\"".into(),
            expect: Some(SelectionExpect { max: 10 }),
            templates: vec![
                json!({ "op": "set", "field": "frontmatter.rolled_up", "value": true }),
            ],
            cardinality: 2,
            identities: vec!["d_1".into(), "d_0".into()],
        };
        assert_eq!(
            canonical_json(&selection.to_json()),
            "{\"cardinality\":2,\"expect\":{\"max\":10},\"identities\":[\"d_1\",\"d_0\"],\"query\":\"from docs where status == \\\"completed\\\"\",\"templates\":[{\"field\":\"frontmatter.rolled_up\",\"op\":\"set\",\"value\":true}]}"
        );
        let without = Selection {
            expect: None,
            ..selection.clone()
        };
        assert!(!canonical_json(&without.to_json()).contains("expect"));
        assert_eq!(
            Selection::from_json(&selection.to_json()),
            Ok(selection.clone())
        );
        assert_eq!(Selection::from_json(&without.to_json()), Ok(without));
        let bare = Plan {
            version: PLAN_VERSION,
            planner_v: PLANNER_V.into(),
            effects: vec![],
            opset: PlanOpset::default(),
            preconditions: Preconditions::default(),
            new_ids: vec![],
            selection: None,
            templates: None,
            plan_id: String::new(),
            diagnostics: vec![],
            preview: None,
        }
        .sealed();
        let selected = Plan {
            selection: Some(selection.clone()),
            ..bare.clone()
        }
        .sealed();
        assert_ne!(bare.plan_id, selected.plan_id);
        assert!(bare.core_json().get("selection").is_none());
        assert_eq!(selected.core_json()["selection"], selection.to_json());
        // The spec's vector (`effects::select-zero-hits-commit-null`): the empty
        // p3 core with a zero-hit selection, `expect` absent.
        let zero = Plan {
            selection: Some(Selection {
                query: "from docs where type == \"nope\"".into(),
                expect: None,
                templates: vec![json!({ "op": "set", "field": "frontmatter.x", "value": 1 })],
                cardinality: 0,
                identities: vec![],
            }),
            ..bare.clone()
        }
        .sealed();
        assert_eq!(
            zero.plan_id,
            "73ca03407ddf05fb522c4118bd5ef1e88887f8430acbaba7428378a0b1e342c9"
        );
        // The record and the wire form carry it; admission reads it back.
        let record = intent_record(
            &selected.plan_id,
            &selected.effects,
            selected.selection.as_ref(),
            None,
        );
        assert!(
            record.contains("\"selection\":{\"cardinality\":2"),
            "{record}"
        );
        let wire = selected.to_json(false);
        assert_eq!(Plan::admit(&wire).unwrap(), selected);
        // Tampering with the identities is a digest mismatch; a malformed
        // member is a shape error; `null` is not an omission.
        let mut tampered = wire.clone();
        tampered["selection"]["identities"] = json!(["d_1", "d_2"]);
        assert!(matches!(
            Plan::admit(&tampered),
            Err(Admission::Refused(m)) if m.code == ErrorCode::PlanMismatch
        ));
        let mut short = wire.clone();
        short["selection"]["identities"] = json!(["d_1"]);
        assert!(matches!(
            Plan::admit(&short),
            Err(Admission::Invalid(m)) if m.contains("cardinality")
        ));
        let mut nulled = wire.clone();
        nulled["selection"] = Value::Null;
        assert!(matches!(Plan::admit(&nulled), Err(Admission::Invalid(_))));
        let mut empty = wire;
        empty["selection"]["templates"] = json!([]);
        assert!(matches!(
            Plan::admit(&empty),
            Err(Admission::Invalid(m)) if m.contains("templates")
        ));
    }

    // ---- the shape fixes (§8, 3.4) ----------------------------------------------------------

    fn ctx<'a>(
        effects: &'a Value,
        select: Option<&'a Value>,
        expect: Option<&'a Value>,
        parent_of: &'a dyn Fn(&str) -> Option<ParentRow>,
    ) -> ShapeFixContext<'a> {
        ShapeFixContext {
            select,
            effects,
            expect,
            parent_of,
        }
    }

    fn rows(id: &str) -> Option<ParentRow> {
        match id {
            "b_4" => Some(ParentRow {
                parent: Some("b_3".to_owned()),
                path: "a.md".to_owned(),
            }),
            "b_1" => Some(ParentRow {
                parent: None,
                path: "a.md".to_owned(),
            }),
            _ => None,
        }
    }

    #[test]
    fn a_bare_anchor_is_fixed_from_the_blocks_parent() {
        let effects = json!([{ "op": "insert", "into": { "kind": "block", "id": "b_4" }, "at": "after", "markdown": "x" }]);
        let c = ctx(&effects, None, None, &rows);
        let e = Effect::validate_with(&effects[0], 0, Some(&c)).unwrap_err();
        assert_eq!(
            e.message,
            "effects[0]: `at` must be \"start\", \"end\", { before: <block id> } or { after: <block id> } — \"after block X\" is into: X's parent (a block, or the document when X is top-level), at: { after: X }"
        );
        assert_eq!(
            e.fix.as_deref(),
            Some(
                r#"{"effects":[{"at":{"after":"b_4"},"into":{"id":"b_3","kind":"block"},"markdown":"x","op":"insert"}]}"#
            )
        );
        // top-level: the document's rooted path; the written effect is the base
        let effects = json!([{ "op": "move", "targets": [{ "kind": "block", "id": "b_6" }], "into": { "kind": "block", "id": "b_1" }, "at": "before" }]);
        let c = ctx(&effects, None, None, &rows);
        let e = Effect::validate_with(&effects[0], 0, Some(&c)).unwrap_err();
        assert!(e.message.contains("\"before block X\""));
        assert_eq!(
            e.fix.as_deref(),
            Some(
                r#"{"effects":[{"at":{"before":"b_1"},"into":"/a.md","op":"move","targets":[{"id":"b_6","kind":"block"}]}]}"#
            )
        );
        // an unknown block, a document `into`, or no context: the message alone
        let effects = json!([{ "op": "insert", "into": { "kind": "block", "id": "b_99" }, "at": "after", "markdown": "x" }]);
        let c = ctx(&effects, None, None, &rows);
        assert_eq!(
            Effect::validate_with(&effects[0], 0, Some(&c))
                .unwrap_err()
                .fix,
            None
        );
        let effects = json!([{ "op": "insert", "into": { "kind": "document", "path": "a.md" }, "at": "after", "markdown": "x" }]);
        let c = ctx(&effects, None, None, &rows);
        assert_eq!(
            Effect::validate_with(&effects[0], 0, Some(&c))
                .unwrap_err()
                .fix,
            None
        );
        assert_eq!(
            Effect::validate_with(&effects[0], 0, None).unwrap_err().fix,
            None
        );
    }

    #[test]
    fn a_guard_first_plural_expect_is_inverted() {
        let effects = json!([{ "op": "remove", "targets": [{ "kind": "block", "id": "b_1" }, { "kind": "block", "id": "b_8" }],
            "expect": { "content_hash": { "b_1": "h1", "b_8": "h8" }, "parent_children_hash": { "b_1": "p1" } } }]);
        let c = ctx(&effects, None, None, &rows);
        let e = Effect::validate_with(&effects[0], 0, Some(&c)).unwrap_err();
        assert_eq!(
            e.message,
            "effects[0]: a plural-target `expect` is keyed by block id — { <block id>: { content_hash?, parent_children_hash? }, … }"
        );
        assert_eq!(
            e.fix.as_deref(),
            Some(
                r#"{"effects":[{"expect":{"b_1":{"content_hash":"h1","parent_children_hash":"p1"},"b_8":{"content_hash":"h8"}},"op":"remove","targets":[{"id":"b_1","kind":"block"},{"id":"b_8","kind":"block"}]}]}"#
            )
        );
        // a value that is not a map of strings is the plain per-id message
        let effects = json!([{ "op": "merge", "targets": [{ "kind": "block", "id": "b_1" }], "expect": { "content_hash": "h1" } }]);
        let c = ctx(&effects, None, None, &rows);
        let e = Effect::validate_with(&effects[0], 0, Some(&c)).unwrap_err();
        assert_eq!(
            e.message,
            "effects[0].expect[\"content_hash\"]: must be an object"
        );
        assert_eq!(e.fix, None);
    }

    #[test]
    fn an_effect_level_max_moves_beside_select_or_is_dropped() {
        let select = json!("from blocks where type == \"paragraph\"");
        let effects =
            json!([{ "op": "set", "field": "markdown", "value": "x", "expect": { "max": 5 } }]);
        // the probe the compile validates (a target in the slot)
        let probe = json!({ "op": "set", "target": { "kind": "block", "id": "b_1" }, "field": "markdown", "value": "x", "expect": { "max": 5 } });
        let c = ctx(&effects, Some(&select), None, &rows);
        let e = Effect::validate_with(&probe, 0, Some(&c)).unwrap_err();
        assert_eq!(
            e.message,
            "effects[0]: `expect.max` bounds a selection — it is the request's top-level `expect`, beside `select`, not an effect's"
        );
        assert_eq!(
            e.fix.as_deref(),
            Some(
                r#"{"effects":[{"field":"markdown","op":"set","value":"x"}],"expect":{"max":5},"select":"from blocks where type == \"paragraph\""}"#
            )
        );
        // a top-level `max` already there is kept; the other guards stay
        let effects = json!([{ "op": "set", "field": "markdown", "value": "x", "expect": { "max": 9, "revision": "r_0" } }]);
        let probe = json!({ "op": "set", "target": { "kind": "block", "id": "b_1" }, "field": "markdown", "value": "x", "expect": { "max": 9, "revision": "r_0" } });
        let top = json!({ "max": 2 });
        let c = ctx(&effects, Some(&select), Some(&top), &rows);
        let e = Effect::validate_with(&probe, 0, Some(&c)).unwrap_err();
        assert_eq!(
            e.fix.as_deref(),
            Some(
                r#"{"effects":[{"expect":{"revision":"r_0"},"field":"markdown","op":"set","value":"x"}],"expect":{"max":2},"select":"from blocks where type == \"paragraph\""}"#
            )
        );
        // without a `select`: only the drop (a plural `expect` too)
        let effects = json!([{ "op": "remove", "targets": [{ "kind": "block", "id": "b_1" }], "expect": { "max": 2 } }]);
        let c = ctx(&effects, None, None, &rows);
        let e = Effect::validate_with(&effects[0], 0, Some(&c)).unwrap_err();
        assert_eq!(
            e.fix.as_deref(),
            Some(r#"{"effects":[{"op":"remove","targets":[{"id":"b_1","kind":"block"}]}]}"#)
        );
    }

    #[test]
    fn a_block_field_alias_is_fixed_to_markdown() {
        for alias in ["text", "content", "body", "raw"] {
            let effects = json!([{ "op": "set", "target": { "kind": "block", "id": "b_1" }, "field": alias, "value": "x" }]);
            let c = ctx(&effects, None, None, &rows);
            let e = Effect::validate_with(&effects[0], 0, Some(&c)).unwrap_err();
            assert_eq!(
                e.message,
                format!(
                    "effects[0]: a block's `field` is `markdown` or `attrs.checked` (got \"{alias}\")"
                )
            );
            assert_eq!(
                e.fix.as_deref(),
                Some(
                    r#"{"effects":[{"field":"markdown","op":"set","target":{"id":"b_1","kind":"block"},"value":"x"}]}"#
                )
            );
        }
        let effects = json!([{ "op": "set", "target": { "kind": "block", "id": "b_1" }, "field": "title", "value": "x" }]);
        let c = ctx(&effects, None, None, &rows);
        assert_eq!(
            Effect::validate_with(&effects[0], 0, Some(&c))
                .unwrap_err()
                .fix,
            None
        );
        // the corrected effect is spelled from the request as written, not the probe
        let effects = json!([{ "op": "set", "target": "b_1", "field": "text", "value": "x" }]);
        let probe = json!({ "op": "set", "target": { "kind": "block", "id": "b_1" }, "field": "text", "value": "x" });
        let c = ctx(&effects, None, None, &rows);
        assert_eq!(
            Effect::validate_with(&probe, 0, Some(&c))
                .unwrap_err()
                .fix
                .as_deref(),
            Some(r#"{"effects":[{"field":"markdown","op":"set","target":"b_1","value":"x"}]}"#)
        );
    }
}