omnidiff 0.2.0

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

use anyhow::Result;
use tree_sitter::Node;

use super::{
    Caches, HumanTextSpan, MarkKind, NamedTextMapping, NodeStatus, TextLabel, label_bytes, load,
    paintings_for_mode, rebuild_caches_for_mapping, status_after, status_before,
};
use crate::code::Code;
use crate::diff::text::{RenderOptions, WHOLE_TOKENS};

/// One painting projected to per-byte labels, `[before, after]` - `None` where nothing paints that
/// byte.
type PaintedLabels = [Vec<Option<TextLabel>>; 2];

/// Where a violation is, on one side.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ViolationSite {
    /// 0 = before, 1 = after - the same side convention `TextDiff::all` and `PaintedLabels` use.
    pub side: usize,
    /// **0-based rows, byte columns** (the [`HumanTextSpan`] convention, for tools). Messages say
    /// 1-based rows, as a gutter shows them.
    pub span: HumanTextSpan,
}

/// One way a fixture's ground truth contradicts itself: which rule, what it says, and where to
/// look. The sites let a tool (`human_solver`'s `V` popup) jump to each location.
#[derive(Debug, Clone)]
pub struct GroundTruthViolation {
    /// Which of the twenty-three rules, numbered as the module doc lists them.
    pub invariant: u8,
    /// The painting this is about, or `None` for the three rules that read only the tree mapping.
    pub painting: Option<String>,
    /// The human-readable line - what a test failure prints and what the popup lists.
    pub message: String,
    /// Every place to look, with runs of contiguous bytes already collapsed into one span each.
    pub sites: Vec<ViolationSite>,
}

impl std::fmt::Display for GroundTruthViolation {
    /// `[9] painting 'Full' before paints ...` - the rule's number, then its sentence. Not part of
    /// `message` because `human_solver`'s popup shows the number in its own column.
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "[{}] {}", self.invariant, self.message)
    }
}

impl GroundTruthViolation {
    fn new(
        invariant: u8,
        painting: Option<&str>,
        message: String,
        sites: Vec<ViolationSite>,
    ) -> Self {
        Self {
            invariant,
            painting: painting.map(str::to_string),
            message,
            sites,
        }
    }
}

/// At most this many sites are carried per violation. The message's count stays exact; this only
/// bounds how many can be jumped to.
const MAX_SITES: usize = 20;

/// The span covering `start..end` of `contents`, in 0-based rows and byte columns.
fn span_of_bytes(contents: &str, start: usize, end: usize) -> HumanTextSpan {
    let row_and_column = |offset: usize| {
        let row = contents[..offset].matches('\n').count();
        let column = offset - contents[..offset].rfind('\n').map_or(0, |index| index + 1);
        (row, column)
    };
    let (start_row, start_column) = row_and_column(start);
    let (end_row, end_column) = row_and_column(end);
    HumanTextSpan {
        start_row,
        start_column,
        end_row,
        end_column,
    }
}

/// The span a node occupies (`tree_sitter::Point::column` is already a byte offset).
fn span_of_node(node: Node) -> HumanTextSpan {
    HumanTextSpan {
        start_row: node.start_position().row,
        start_column: node.start_position().column,
        end_row: node.end_position().row,
        end_column: node.end_position().column,
    }
}

/// Byte offsets on one side as sites, with contiguous offsets collapsed into one span each (a
/// jump per byte is useless). `offsets` must be ascending.
fn sites_from_offsets(side: usize, contents: &str, offsets: &[usize]) -> Vec<ViolationSite> {
    let mut sites: Vec<ViolationSite> = Vec::new();
    let mut run: Option<(usize, usize)> = None;
    for &offset in offsets {
        match run {
            Some((start, end)) if end == offset => run = Some((start, offset + 1)),
            Some((start, end)) => {
                sites.push(ViolationSite {
                    side,
                    span: span_of_bytes(contents, start, end),
                });
                run = Some((offset, offset + 1));
            }
            None => run = Some((offset, offset + 1)),
        }
        if sites.len() >= MAX_SITES {
            return sites;
        }
    }
    if let Some((start, end)) = run {
        sites.push(ViolationSite {
            side,
            span: span_of_bytes(contents, start, end),
        });
    }
    sites
}

/// What invariants 2 and 8 carry while scoring one `Minimal` alternative against every `Full` one:
/// both report only the closest counterpart, since the alternatives are a disjunction (see
/// [`full_painting_covers_minimal`]).
struct ClosestFull<'a> {
    /// Bytes the two disagree about - the number being minimised.
    count: usize,
    /// The `Full` alternative's own name (invariant 2's message).
    name: &'a str,
    /// 1-based rows, per side, for the message's row list.
    rows: [Vec<usize>; 2],
    /// Byte offsets, per side, for the violation's sites.
    offsets: [Vec<usize>; 2],
    /// One example, already phrased (invariant 8's message); empty where there is none.
    detail: String,
}

/// One site covering a whole row's `start_column..end_column`, 0-based.
fn site_on_row(side: usize, row: usize, start_column: usize, end_column: usize) -> ViolationSite {
    ViolationSite {
        side,
        span: HumanTextSpan {
            start_row: row,
            start_column,
            end_row: row,
            end_column,
        },
    }
}

/// Every way `name`'s ground truth contradicts itself, in a stable order. Empty is a pass.
pub fn ground_truth_invariant_violations(name: &str) -> Result<Vec<GroundTruthViolation>> {
    let (before, after) = &*crate::test::helper::handmade_test_code_pair(name)?;
    ground_truth_invariant_violations_for(&load(name)?, before, after)
}

/// [`ground_truth_invariant_violations`] over an already-loaded mapping and code pair.
/// **`human_solver` must call this one**: its mapping is in memory and usually unsaved, so the
/// by-name form would report violations the reader has just repaired.
pub fn ground_truth_invariant_violations_for(
    mapping: &super::HumanMapping,
    before: &Code,
    after: &Code,
) -> Result<Vec<GroundTruthViolation>> {
    let mut violations = Vec::new();

    // Every check reads the painting through the scorer's own projection (`label_bytes`), so an
    // invariant can never fire on a byte no comparison looks at.
    let mut paintings: Vec<(&str, PaintedLabels)> = Vec::new();
    for named in &mapping.text_mappings {
        paintings.push((named.name.as_str(), painted_labels(named, before, after)?));
    }

    for (name, labels) in &paintings {
        violations.extend(rows_end_on_visible_characters(name, labels, before, after));
    }
    // Reads the spans, not the labels - see `painted_ranges_do_not_overlap`.
    for named in &mapping.text_mappings {
        violations.extend(painted_ranges_do_not_overlap(named, before, after));
    }
    violations.extend(full_painting_covers_minimal(mapping, before, after)?);
    violations.extend(presets_agree_on_what_survives(mapping, before, after)?);
    violations.extend(mapping_and_painting_agree_on_what_survives(
        mapping, before, after,
    )?);
    violations.extend(delimiter_pairs_agree(mapping, before, after));
    if let (Some(before_tree), Some(after_tree)) = (before.ast.as_ref(), after.ast.as_ref()) {
        let context = TreeContext::build(mapping, before_tree.root_node(), after_tree.root_node());
        for (name, labels) in &paintings {
            violations.extend(paired_leaves_are_not_deleted_and_inserted(
                name, labels, &context, before, after,
            ));
            violations.extend(removed_leaves_are_painted(
                name, labels, &context, before, after,
            ));
            violations.extend(edited_leaves_are_painted(
                name, labels, &context, before, after,
            ));
        }
        for named in &mapping.text_mappings {
            violations.extend(painting_implies_mapping_edits(
                mapping, named, before, after,
            ));
        }
        for named in &mapping.text_mappings {
            let labels = &paintings
                .iter()
                .find(|(name, _)| *name == named.name.as_str())
                .expect("one labelling per painting")
                .1;
            violations.extend(painted_updates_are_not_removed(
                named, labels, &context, before, after,
            ));
            violations.extend(identical_pairs_are_not_painted_removed(
                &named.name,
                labels,
                &context,
                before,
                after,
            ));
            violations.extend(painted_matches_hold_the_mapping_partner(
                named, &context, before, after,
            ));
        }
        for (name, labels) in &paintings {
            violations.extend(identifier_updates_are_painted_by_preset(
                name, labels, &context, before, after,
            ));
            violations.extend(tokens_are_painted_whole(
                name, labels, &context, before, after,
            ));
        }
        violations.extend(boolean_flips_are_one_edit(
            &paintings, &context, before, after,
        ));
        violations.extend(identical_entries_are_token_identical(
            &context, before, after,
        ));
        violations.extend(match_but_not_identical_entries_differ(
            &context, before, after,
        ));
        violations.extend(single_valued_fields_hold_a_pair(&context, before, after));
        violations.extend(wrapped_tokens_are_paired(&context, before, after));
    }
    // Invariants 4 and 5 read only the paintings `FULL` answers to.
    let (leading, interior, minimal_indentation) =
        full_painting_whitespace_violations(mapping, before, after)?;
    violations.extend(leading);
    violations.extend(interior);
    violations.extend(minimal_indentation);

    Ok(violations)
}

/// One painting reduced to per-byte labels, `[before, after]`.
pub(crate) fn painted_labels(
    named: &NamedTextMapping,
    before: &Code,
    after: &Code,
) -> Result<PaintedLabels> {
    let mut spans: [Vec<(HumanTextSpan, TextLabel)>; 2] = [Vec::new(), Vec::new()];
    for entry in &named.mapping.entries {
        let label = TextLabel::from_verdict(entry.verdict(&before.contents, &after.contents)?);
        for span in &entry.before {
            spans[0].push((*span, label));
        }
        for span in &entry.after {
            spans[1].push((*span, label));
        }
    }
    Ok([
        label_bytes(&before.contents, &spans[0]),
        label_bytes(&after.contents, &spans[1]),
    ])
}

// ─────────────────────────────────────────────────────────────────────────────────────────────
// Invariant 1: a painted row ends on a visible character
// ─────────────────────────────────────────────────────────────────────────────────────────────

/// No painted run may end in a row's **trailing** whitespace: a stripe of colour hanging off the
/// end of a line, pointing at nothing.
///
/// A run ending on a space mid-row is the ordinary shape of an edit (deleting `foo ` from
/// `foo bar`), and a run that is *entirely* whitespace has no visible character to end on; both
/// pass. A row with nothing visible is skipped: no painting of it could pass.
///
/// Checked against the projected labels, not raw spans, so the `\n` a span ending at column 0 of
/// the next row swallows is not reported: nothing paints it.
fn rows_end_on_visible_characters(
    painting: &str,
    labels: &PaintedLabels,
    before: &Code,
    after: &Code,
) -> Vec<GroundTruthViolation> {
    let mut violations = Vec::new();
    for (side, contents) in [(0usize, &before.contents), (1usize, &after.contents)] {
        let mut offset = 0usize;
        for (row, line) in contents.split('\n').enumerate() {
            let start = offset;
            offset += line.len() + 1;
            if !line.chars().any(|c| !c.is_whitespace()) {
                continue;
            }
            let Some(last) = (0..line.len())
                .rev()
                .find(|&i| labels[side][start + i].is_some())
            else {
                continue;
            };
            // `last` can land inside a multi-byte character; the character it belongs to is the
            // one a reader sees at the end of the painted run.
            let boundary = (0..=last)
                .rev()
                .find(|&i| line.is_char_boundary(i))
                .unwrap_or(0);
            let Some(character) = line[boundary..].chars().next() else {
                continue;
            };
            if !character.is_whitespace() {
                continue;
            }
            // Only *trailing* whitespace counts.
            if line[boundary..].chars().any(|c| !c.is_whitespace()) {
                continue;
            }
            // An all-whitespace run is exempt. Both ends snap to character boundaries: `last` is a
            // byte index.
            let run_start = (0..=last)
                .rev()
                .take_while(|&i| labels[side][start + i].is_some())
                .last()
                .unwrap_or(last);
            let run_start = (0..=run_start)
                .rev()
                .find(|&i| line.is_char_boundary(i))
                .unwrap_or(0);
            let run_end = boundary + character.len_utf8();
            if line[run_start..run_end].chars().all(char::is_whitespace) {
                continue;
            }
            violations.push(GroundTruthViolation::new(
                1,
                Some(painting),
                format!(
                    "painting '{painting}' {} row {} ends its last painted run on {character:?}, \
                     not on a visible character: {line:?}",
                    side_name(side),
                    row + 1,
                ),
                vec![site_on_row(side, row, run_start, run_end)],
            ));
        }
    }
    violations
}

// ─────────────────────────────────────────────────────────────────────────────────────────────
// Invariant 2: Full paints everything Minimal paints
// ─────────────────────────────────────────────────────────────────────────────────────────────

/// Whatever `Minimal` paints, `Full` paints too.
///
/// The presets differ in *how much* of an edit to highlight, not in *what* the edit is. Only
/// painted-or-not is compared, since `Full` routinely widens a `Move` into the enclosing `Update`.
/// A lone painting answers for both presets, so nothing is compared. With several alternatives
/// per preset, each `Minimal` need only be covered by *some* `Full`: holding one arm of a
/// disjunction to another's `Full` asserts a pairing the painter never claimed.
fn full_painting_covers_minimal(
    mapping: &super::HumanMapping,
    before: &Code,
    after: &Code,
) -> Result<Vec<GroundTruthViolation>> {
    let (Ok(minimal), Ok(full)) = (
        paintings_for_mode(mapping, RenderOptions::MINIMAL),
        paintings_for_mode(mapping, RenderOptions::FULL),
    ) else {
        return Ok(Vec::new());
    };
    // A single painting is trivially its own superset.
    if minimal
        .iter()
        .all(|m| full.iter().any(|f| std::ptr::eq(*m, *f)))
    {
        return Ok(Vec::new());
    }

    let mut violations = Vec::new();
    for minimal in &minimal {
        let minimal_labels = painted_labels(minimal, before, after)?;
        let mut closest: Option<ClosestFull> = None;
        for full in &full {
            let full_labels = painted_labels(full, before, after)?;
            let mut missing = 0usize;
            let mut rows: [Vec<usize>; 2] = [Vec::new(), Vec::new()];
            let mut offsets: [Vec<usize>; 2] = [Vec::new(), Vec::new()];
            for (side, contents) in [(0usize, &before.contents), (1usize, &after.contents)] {
                for (offset, (minimal, full)) in minimal_labels[side]
                    .iter()
                    .zip(full_labels[side].iter())
                    .enumerate()
                {
                    if minimal.is_some() && full.is_none() {
                        missing += 1;
                        rows[side].push(row_of(contents, offset));
                        offsets[side].push(offset);
                    }
                }
            }
            if closest.as_ref().is_none_or(|best| missing < best.count) {
                closest = Some(ClosestFull {
                    count: missing,
                    name: full.name.as_str(),
                    rows,
                    offsets,
                    detail: String::new(),
                });
            }
        }
        if let Some(ClosestFull {
            count: missing,
            name: full,
            rows,
            offsets,
            ..
        }) = closest
            && missing > 0
        {
            violations.push(GroundTruthViolation::new(
                2,
                Some(&minimal.name),
                format!(
                    "painting '{}' paints {missing} byte(s) that '{full}' leaves unpainted, on {} \
                     - a Full painting must cover everything its Minimal counterpart covers",
                    minimal.name,
                    site_rows(&rows),
                ),
                [
                    sites_from_offsets(0, &before.contents, &offsets[0]),
                    sites_from_offsets(1, &after.contents, &offsets[1]),
                ]
                .concat(),
            ));
        }
    }
    Ok(violations)
}

// ─────────────────────────────────────────────────────────────────────────────────────────────
// Invariants 4, 5 and 6: what each preset may and may not do with whitespace
// ─────────────────────────────────────────────────────────────────────────────────────────────

/// Every painting of `mapping` that `options`' own rules can be held to, paired with its per-byte
/// labels. A lone painting counts for both presets - **except** when it is explicitly named for
/// the *other* preset: holding a reading labelled *minimal* to the generous preset's rules
/// asserts something the painter never claimed.
pub(crate) fn paintings_with_labels<'a>(
    mapping: &'a super::HumanMapping,
    before: &Code,
    after: &Code,
    options: RenderOptions,
) -> Result<Vec<(&'a str, PaintedLabels)>> {
    let Ok(paintings) = paintings_for_mode(mapping, options) else {
        return Ok(Vec::new());
    };
    // Only a *lone* painting can be misnamed this way: with several, `paintings_for_mode` has
    // already filtered by name.
    let wanted_minimal = options == RenderOptions::MINIMAL;
    paintings
        .iter()
        .filter(|named| {
            paintings.len() > 1
                || !(designates_minimal(&named.name) || designates_full(&named.name))
                || designates_minimal(&named.name) == wanted_minimal
        })
        .map(|named| Ok((named.name.as_str(), painted_labels(named, before, after)?)))
        .collect()
}

/// Whether a painting's name declares it the `Minimal` reading (the name, or the name and a
/// qualifier - `human_mapping::designates_preset`'s rule). `pub` for `human_solver`, which keeps
/// invariant 6 for the painter as they paint.
pub fn designates_minimal(name: &str) -> bool {
    super::designates_preset(name, "Minimal")
}

/// Whether a painting's name declares it the `Full` reading. `pub` for `human_solver`, which keeps
/// invariant 4 for the painter when branching a painting.
pub fn designates_full(name: &str) -> bool {
    super::designates_preset(name, "Full")
}

/// Rows of `contents` as `(row index, byte offset of the row, the row itself)`.
fn rows_of(contents: &str) -> impl Iterator<Item = (usize, usize, &str)> {
    let mut offset = 0usize;
    contents.split('\n').enumerate().map(move |(row, line)| {
        let start = offset;
        offset += line.len() + 1;
        (row, start, line)
    })
}

/// **Invariant 4.** If a `Full` painting calls *every* visible character on a line inserted, or
/// every one deleted, the whole line up to its last visible character - whitespace included - is
/// accounted for. A line entering or leaving the file does so whole; unpainted whitespace in it
/// reads as several edits to a surviving line. The data-side counterpart of
/// `RenderOptions::leading_whitespace`.
///
/// "All of them", not "the first one": a *surviving* line may begin with an inserted token.
/// Only `Insert`/`Delete`: a wholly `Move`d or `Update`d line survives, and its whitespace may
/// genuinely be unchanged. Any verdict on the whitespace passes, only **unpainted** bytes are
/// reported: pairing shared indentation in a `Match` is a stronger claim, not a weaker one
/// (`go-lazygit-switch-to-strings` row 22). A line with nothing visible is skipped.
fn full_paints_a_wholly_changed_line_whole(
    painting: &str,
    labels: &PaintedLabels,
    before: &Code,
    after: &Code,
) -> Vec<GroundTruthViolation> {
    let mut violations = Vec::new();
    for (side, contents) in [(0usize, &before.contents), (1usize, &after.contents)] {
        for (row, start, line) in rows_of(contents) {
            let visible: Vec<usize> = line
                .char_indices()
                .filter(|(_, c)| !c.is_whitespace())
                .map(|(i, _)| i)
                .collect();
            if visible.is_empty() {
                continue;
            }
            let Some(label) = labels[side][start + visible[0]] else {
                continue;
            };
            if !matches!(label, TextLabel::Insert | TextLabel::Delete) {
                continue;
            }
            if !visible
                .iter()
                .all(|&i| labels[side][start + i] == Some(label))
            {
                continue;
            }
            // Never past the last visible character: trailing whitespace is what invariant 1
            // forbids painting, so including it would make the two rules contradict each other.
            let end = visible.last().copied().unwrap_or(0)
                + line[visible.last().copied().unwrap_or(0)..]
                    .chars()
                    .next()
                    .map_or(1, char::len_utf8);
            let unpainted: Vec<usize> = (0..end)
                .filter(|&i| labels[side][start + i].is_none())
                .collect();
            // The exact columns: a human repairing the painting needs *which* bytes.
            if let (Some(&low), Some(&high)) = (unpainted.first(), unpainted.last()) {
                violations.push(GroundTruthViolation::new(
                    4,
                    Some(painting),
                    format!(
                        "painting '{painting}' {} row {} paints every visible character {label:?} \
                         but leaves columns {low}..{} unpainted ({} byte(s) of whitespace inside \
                         the line's own content): {line:?}",
                        side_name(side),
                        row + 1,
                        high + 1,
                        unpainted.len(),
                    ),
                    vec![site_on_row(side, row, low, high + 1)],
                ));
            }
        }
    }
    violations
}

/// **Invariant 5.** A `Full` painting never leaves an all-whitespace run unpainted between two
/// painted regions on the same row: that breaks one highlight into two edits. A gap holding any
/// visible character is a real gap between two edits and passes.
fn no_unpainted_whitespace_between_painted_regions(
    painting: &str,
    labels: &PaintedLabels,
    before: &Code,
    after: &Code,
) -> Vec<GroundTruthViolation> {
    let mut violations = Vec::new();
    for (side, contents) in [(0usize, &before.contents), (1usize, &after.contents)] {
        for (row, start, line) in rows_of(contents) {
            let painted: Vec<usize> = (0..line.len())
                .filter(|&i| labels[side][start + i].is_some())
                .collect();
            let (Some(&first), Some(&last)) = (painted.first(), painted.last()) else {
                continue;
            };
            let mut run: Option<usize> = None;
            for i in first..=last {
                if labels[side][start + i].is_some() {
                    if let Some(run_start) = run.take()
                        && line[run_start..i].chars().all(char::is_whitespace)
                    {
                        violations.push(GroundTruthViolation::new(
                            5,
                            Some(painting),
                            format!(
                                "painting '{painting}' {} row {} leaves columns {}..{} unpainted \
                                 between two painted regions, and they are only whitespace: \
                                 {line:?}",
                                side_name(side),
                                row + 1,
                                run_start,
                                i,
                            ),
                            vec![site_on_row(side, row, run_start, i)],
                        ));
                    }
                } else if run.is_none() {
                    run = Some(i);
                }
            }
        }
    }
    violations
}

/// **Invariant 6.** A `Minimal` painting never paints a line's leading whitespace.
///
/// The mirror of invariant 4, and the data side of `RenderOptions::leading_whitespace` being off
/// under `MINIMAL`: a `Minimal` painting that claims indentation grades omnidiff against a
/// reading `MINIMAL` never produces. Unconditional on the verdict, `Insert` on a new line
/// included - that is exactly where the presets part company. A line with nothing visible is
/// skipped, as in invariants 1 and 4.
fn minimal_never_paints_leading_whitespace(
    painting: &str,
    labels: &PaintedLabels,
    before: &Code,
    after: &Code,
) -> Vec<GroundTruthViolation> {
    let mut violations = Vec::new();
    for (side, contents) in [(0usize, &before.contents), (1usize, &after.contents)] {
        for (row, start, line) in rows_of(contents) {
            let Some(first) = line.find(|c: char| !c.is_whitespace()) else {
                continue;
            };
            let painted: Vec<usize> = (0..first)
                .filter(|&i| labels[side][start + i].is_some())
                .collect();
            if let (Some(&low), Some(&high)) = (painted.first(), painted.last()) {
                violations.push(GroundTruthViolation::new(
                    6,
                    Some(painting),
                    format!(
                        "painting '{painting}' {} row {} paints columns {low}..{} of its own \
                         leading whitespace ({} byte(s)) - Minimal never claims a line's \
                         indentation: {line:?}",
                        side_name(side),
                        row + 1,
                        high + 1,
                        painted.len(),
                    ),
                    vec![site_on_row(side, row, low, high + 1)],
                ));
            }
        }
    }
    violations
}

/// The three preset-scoped whitespace rules, as `(invariant 4, invariant 5, invariant 6)`, kept
/// apart so a corpus sweep can say which one a fixture fails.
pub fn full_painting_whitespace_violations(
    mapping: &super::HumanMapping,
    before: &Code,
    after: &Code,
) -> Result<(
    Vec<GroundTruthViolation>,
    Vec<GroundTruthViolation>,
    Vec<GroundTruthViolation>,
)> {
    let mut leading = Vec::new();
    let mut interior = Vec::new();
    let mut minimal_indentation = Vec::new();
    // A lone painting asserts its rendering is unambiguous, not that it follows `Full`'s
    // conventions, so invariant 5 applies only to a painting actually named for `Full`.
    let named_for_full = mapping.text_mappings.len() > 1;
    for (painting, labels) in paintings_with_labels(mapping, before, after, RenderOptions::FULL)? {
        leading.extend(full_paints_a_wholly_changed_line_whole(
            painting, &labels, before, after,
        ));
        if named_for_full {
            interior.extend(no_unpainted_whitespace_between_painted_regions(
                painting, &labels, before, after,
            ));
        }
    }
    for (painting, labels) in paintings_with_labels(mapping, before, after, RenderOptions::MINIMAL)?
    {
        minimal_indentation.extend(minimal_never_paints_leading_whitespace(
            painting, &labels, before, after,
        ));
    }
    Ok((leading, interior, minimal_indentation))
}

// ─────────────────────────────────────────────────────────────────────────────────────────────
// Invariant 8: a byte one preset calls Move is not removed or added by the other
// ─────────────────────────────────────────────────────────────────────────────────────────────

/// **Invariant 8.** A byte one preset paints `Move` is never painted `Insert` or `Delete` by the
/// other. `Move` says the bytes *survive*; two renderings of one edit cannot disagree about that.
///
/// `Move` against `Update` is the ordinary widening between presets (see
/// [`full_painting_covers_minimal`]) and is not reported. Alternatives are a disjunction, as in
/// invariant 2: each `Minimal` is scored against its closest `Full`. A lone painting is skipped.
fn presets_agree_on_what_survives(
    mapping: &super::HumanMapping,
    before: &Code,
    after: &Code,
) -> Result<Vec<GroundTruthViolation>> {
    let (Ok(minimal), Ok(full)) = (
        paintings_for_mode(mapping, RenderOptions::MINIMAL),
        paintings_for_mode(mapping, RenderOptions::FULL),
    ) else {
        return Ok(Vec::new());
    };
    if minimal
        .iter()
        .all(|m| full.iter().any(|f| std::ptr::eq(*m, *f)))
    {
        return Ok(Vec::new());
    }

    /// Whether one byte's two readings disagree about the code being there at all.
    fn contradicts(one: TextLabel, other: TextLabel) -> bool {
        matches!(
            (one, other),
            (TextLabel::Move, TextLabel::Insert | TextLabel::Delete)
                | (TextLabel::Insert | TextLabel::Delete, TextLabel::Move)
        )
    }

    let mut violations = Vec::new();
    for minimal in &minimal {
        let minimal_labels = painted_labels(minimal, before, after)?;
        let mut closest: Option<ClosestFull> = None;
        for full in &full {
            let full_labels = painted_labels(full, before, after)?;
            let mut count = 0usize;
            let mut first = String::new();
            let mut rows: [Vec<usize>; 2] = [Vec::new(), Vec::new()];
            let mut offsets: [Vec<usize>; 2] = [Vec::new(), Vec::new()];
            for (side, contents) in [(0usize, &before.contents), (1usize, &after.contents)] {
                for (offset, (left, right)) in minimal_labels[side]
                    .iter()
                    .zip(full_labels[side].iter())
                    .enumerate()
                {
                    let (Some(left), Some(right)) = (left, right) else {
                        continue;
                    };
                    if !contradicts(*left, *right) {
                        continue;
                    }
                    if count == 0 {
                        first = format!(
                            "the first reads {left:?} under '{}' and {right:?} under '{}'",
                            minimal.name, full.name,
                        );
                    }
                    rows[side].push(row_of(contents, offset));
                    offsets[side].push(offset);
                    count += 1;
                }
            }
            if closest.as_ref().is_none_or(|best| count < best.count) {
                closest = Some(ClosestFull {
                    count,
                    name: full.name.as_str(),
                    rows,
                    offsets,
                    detail: first,
                });
            }
        }
        if let Some(ClosestFull {
            count,
            rows,
            offsets,
            detail: first,
            ..
        }) = closest
            && count > 0
        {
            violations.push(GroundTruthViolation::new(
                8,
                Some(&minimal.name),
                format!(
                    "{count} byte(s) survive under one preset and do not under the other, on {} - \
                     {first}. A Move says the code is still there, so the other preset cannot \
                     call it removed or added",
                    site_rows(&rows),
                ),
                [
                    sites_from_offsets(0, &before.contents, &offsets[0]),
                    sites_from_offsets(1, &after.contents, &offsets[1]),
                ]
                .concat(),
            ));
        }
    }
    Ok(violations)
}

// ─────────────────────────────────────────────────────────────────────────────────────────────
// Invariant 7: two painted ranges never claim the same byte
// ─────────────────────────────────────────────────────────────────────────────────────────────

/// **Invariant 7.** No two ranges of one painting claim the same byte.
///
/// An overlap renders one way (`render_paint_side` takes the highest-ranked verdict) and scores
/// another (`label_bytes` takes the last entry). `human_solver` refuses new ones at the keystroke
/// (`overlapping_painted_range`); this checks what is on disk.
///
/// **Checked against the raw spans**, unlike every other rule: the projection is exactly what
/// hides a double claim. Line terminators are never painted, so ranges meeting at a line break do
/// not overlap. One violation per range that lands on an earlier range's ground, per side.
fn painted_ranges_do_not_overlap(
    named: &NamedTextMapping,
    before: &Code,
    after: &Code,
) -> Vec<GroundTruthViolation> {
    let mut violations = Vec::new();
    for (side, contents) in [(0usize, &before.contents), (1usize, &after.contents)] {
        let bytes = contents.as_bytes();
        // Which entry claimed each byte, in list order - the order `label_bytes` resolves by.
        let mut claimed: Vec<Option<usize>> = vec![None; contents.len()];
        for (index, entry) in named.mapping.entries.iter().enumerate() {
            let spans = if side == 0 {
                &entry.before
            } else {
                &entry.after
            };
            for span in spans {
                let (Some(start), Some(end)) = (
                    super::byte_offset(contents, span.start_row, span.start_column),
                    super::byte_offset(contents, span.end_row, span.end_column),
                ) else {
                    continue;
                };
                let mut clash: Option<(usize, usize)> = None;
                for offset in start..end.min(contents.len()) {
                    if bytes[offset] == b'\n'
                        || (bytes[offset] == b'\r' && bytes.get(offset + 1) == Some(&b'\n'))
                    {
                        continue;
                    }
                    match claimed[offset] {
                        Some(owner) if clash.is_none() => clash = Some((owner, offset)),
                        _ => {}
                    }
                    claimed[offset] = Some(index);
                }
                if let Some((owner, offset)) = clash {
                    let row = contents[..offset].matches('\n').count();
                    violations.push(GroundTruthViolation::new(
                        7,
                        Some(&named.name),
                        format!(
                            "painting '{}' {} range {} claims byte {offset} (row {}) already \
                             claimed by range {owner} - an overlap renders by highest verdict and \
                             scores by list order, so it reads as one painting and grades as \
                             another",
                            named.name,
                            side_name(side),
                            index,
                            row + 1,
                        ),
                        // The whole offending range: shortening a range is the repair.
                        vec![ViolationSite {
                            side,
                            span: span_of_bytes(contents, start, end.min(contents.len())),
                        }],
                    ));
                }
            }
        }
    }
    violations
}

// ─────────────────────────────────────────────────────────────────────────────────────────────
// Invariant 9: the mapping and the painting agree on what survives
// ─────────────────────────────────────────────────────────────────────────────────────────────

/// **Invariant 9.** A byte the painting calls `Move` is not one the tree mapping leaves unmatched.
///
/// The two ground truths chunk one edit differently by design (see
/// [`super::text_mapping_disagreements`]), but a painted `Move` says the code survives and an
/// unmatched node says it has no counterpart; only one can hold.
///
/// **Only that direction**: the tree side's own `Move` labels come from `TextDiff::from`'s
/// column-shift heuristic, so a tree `Move` against a painted `Delete` measures the renderer, not
/// the humans. **And only where the mapping really leaves the byte unmatched**, per
/// [`unmatched_bytes`]: `TextDiff::from` also emits `Delete`/`Insert` for characters edited inside
/// a matched leaf (`rust-rust-lang-rust-update-comment`).
///
/// Every painting is checked, not the best one: each claims to be a correct rendering.
fn mapping_and_painting_agree_on_what_survives(
    mapping: &super::HumanMapping,
    before: &Code,
    after: &Code,
) -> Result<Vec<GroundTruthViolation>> {
    if mapping.text_mappings.is_empty() || mapping.entries.is_empty() {
        return Ok(Vec::new());
    }
    let Ok(ast_diff) = super::as_ast_diff_for_mapping(mapping, before, after) else {
        return Ok(Vec::new());
    };
    let (Some(before_tree), Some(after_tree)) = (before.ast.as_ref(), after.ast.as_ref()) else {
        return Ok(Vec::new());
    };
    let node_cache = crate::diff::NodeCache::build(before, after);
    let text_diff = crate::diff::text::TextDiff::from(before, after, &ast_diff, &node_cache);
    let tree = [
        super::label_bytes_from_ranges(&before.contents, &text_diff.all(0)),
        super::label_bytes_from_ranges(&after.contents, &text_diff.all(1)),
    ];
    let caches =
        rebuild_caches_for_mapping(mapping, before_tree.root_node(), after_tree.root_node());
    let unmatched = [
        unmatched_bytes(
            before_tree.root_node(),
            before.contents.len(),
            0,
            &mapping.groups,
            &caches,
        ),
        unmatched_bytes(
            after_tree.root_node(),
            after.contents.len(),
            1,
            &mapping.groups,
            &caches,
        ),
    ];

    let mut violations = Vec::new();
    for named in &mapping.text_mappings {
        let painted = painted_labels(named, before, after)?;
        violations.extend(move_against_unmatched(
            &named.name,
            &painted,
            &tree,
            &unmatched,
            before,
            after,
        ));
    }
    Ok(violations)
}

/// Per byte of one side, whether the **smallest node containing it** is one the tree mapping
/// leaves unmatched.
///
/// A node its multi-map group leaves free does not count: which member is left over is
/// [`representative_entries`](super::representative_entries)' choice, not the human's
/// (`java-defects4j-chart-9-timeseries`). Painted in preorder so a child overwrites its parent,
/// and whitespace between children keeps the parent's answer - what `descendant_for_byte_range`
/// would say per byte, in one walk.
fn unmatched_bytes(
    root: Node,
    len: usize,
    side: usize,
    groups: &[super::MultiMapGroup],
    caches: &Caches,
) -> Vec<bool> {
    let mut mask = vec![false; len];
    let mut stack = vec![root];
    while let Some(node) = stack.pop() {
        let status = if side == 0 {
            status_before(node, caches)
        } else {
            status_after(node, caches)
        };
        let unmatched = matches!(status, NodeStatus::Marked { .. })
            && !group_leaves_status_open(node, side, groups, caches);
        let (start, end) = (node.start_byte().min(len), node.end_byte().min(len));
        mask[start..end].fill(unmatched);
        let mut cursor = node.walk();
        for child in node.children(&mut cursor) {
            stack.push(child);
        }
    }
    mask
}

/// [`mapping_and_painting_agree_on_what_survives`]' comparison over the built projections, split
/// out to test against label vectors. `unmatched` is [`unmatched_bytes`]' output per side.
fn move_against_unmatched(
    painting: &str,
    painted: &PaintedLabels,
    tree: &PaintedLabels,
    unmatched: &[Vec<bool>; 2],
    before: &Code,
    after: &Code,
) -> Vec<GroundTruthViolation> {
    let mut violations = Vec::new();
    for (side, contents) in [(0usize, &before.contents), (1usize, &after.contents)] {
        let mut count = 0usize;
        let mut rows = Vec::new();
        let mut offsets = Vec::new();
        let mut labels: Vec<&'static str> = Vec::new();
        for (offset, (paint, from_tree)) in painted[side].iter().zip(tree[side].iter()).enumerate()
        {
            if *paint != Some(TextLabel::Move)
                || !matches!(from_tree, Some(TextLabel::Delete | TextLabel::Insert))
                // The renderer says these bytes went away; only the mapping can say whether that
                // is a node with no counterpart or a character edited out of one that has one.
                || !unmatched[side].get(offset).copied().unwrap_or(false)
                // Whitespace lives between tokens, where the tree has no node, so neither ground
                // truth really describes it: `unmatched_bytes` gives it the enclosing verdict while
                // a `Full` painting takes indentation with its construct.
                || contents.as_bytes()[offset].is_ascii_whitespace()
            {
                continue;
            }
            let label = if *from_tree == Some(TextLabel::Delete) {
                "Delete"
            } else {
                "Insert"
            };
            if !labels.contains(&label) {
                labels.push(label);
            }
            rows.push(row_of(contents, offset));
            offsets.push(offset);
            count += 1;
        }
        if count > 0 {
            violations.push(GroundTruthViolation::new(
                9,
                Some(painting),
                format!(
                    "painting '{painting}' {} paints {count} byte(s) Move on {} that the tree \
                     mapping reads {} - a Move says the code survives and an unmatched node says \
                     it does not",
                    side_name(side),
                    row_list(&rows),
                    labels.join("/"),
                ),
                sites_from_offsets(side, contents, &offsets),
            ));
        }
    }
    violations
}

// ─────────────────────────────────────────────────────────────────────────────────────────────
// Invariant 3: a delimiter and its partner carry one verdict
// ─────────────────────────────────────────────────────────────────────────────────────────────

/// The delimiters this pairs, opener to the closers that may end it: every anonymous leaf in the
/// corpus whose kind *is* its own text. `kind == text` keeps a `)` inside a string or comment
/// out. `<` also takes `/>`; a `<` with no closer among its siblings (`a < b`) never pairs.
const DELIMITERS: &[(&str, &[&str])] = &[
    ("(", &[")"]),
    ("[", &["]"]),
    ("{", &["}"]),
    ("<", &[">", "/>"]),
    ("</", &[">"]),
    ("<?", &["?>"]),
];

fn closers_of(kind: &str) -> Option<&'static [&'static str]> {
    DELIMITERS
        .iter()
        .find(|(open, _)| *open == kind)
        .map(|(_, close)| *close)
}

fn is_closer(kind: &str) -> bool {
    DELIMITERS
        .iter()
        .any(|(_, closers)| closers.contains(&kind))
}

/// **Invariant 3.** A delimiter and its partner carry one status in the tree mapping: nobody
/// deletes a `(` and keeps its `)`.
///
/// **The mapping only.** A painting may legitimately replace one delimiter with another (`<tag>`
/// becoming `<tag/>`) or move a `}` without its `{`; a tree node is matched or not, so there the
/// two halves really are two claims about one construct.
///
/// Pairing is structural, within one parent's direct children: a stack pairs each closer with the
/// nearest unclosed opener that admits it, so nothing crosses a parent. A pair with a parse error
/// between its halves is skipped, since error recovery invents pairs no human saw.
///
/// A half its multi-map group leaves free is not a claim ([`group_leaves_status_open`]): the
/// question is whether *some* admissible pairing agrees, as `check_group_entry` asks of omnidiff.
/// Checked per pair, so two pairs jointly infeasible through one group's count go unreported -
/// a false negative, never a false positive.
///
/// Compares **status only** (deleted, inserted, matched), not the derived move flag, which is a
/// numbering consequence. An `Unmarked` half makes no claim, so the pair is not counted.
fn delimiter_pairs_agree(
    mapping: &super::HumanMapping,
    before: &Code,
    after: &Code,
) -> Vec<GroundTruthViolation> {
    let (Some(before_tree), Some(after_tree)) = (before.ast.as_ref(), after.ast.as_ref()) else {
        return Vec::new();
    };
    let caches =
        rebuild_caches_for_mapping(mapping, before_tree.root_node(), after_tree.root_node());

    let mut violations = Vec::new();
    for (side, code, root) in [
        (0usize, before, before_tree.root_node()),
        (1usize, after, after_tree.root_node()),
    ] {
        let errors = error_ranges(root);
        for (open, close) in delimiter_pairs(root, &code.contents) {
            let (from, to) = (open.end_byte(), close.start_byte());
            if errors.iter().any(|&(start, end)| start < to && end > from) {
                continue;
            }

            let (opened, closed) = (
                mark_of(open, side, &mapping.groups, &caches),
                mark_of(close, side, &mapping.groups, &caches),
            );
            if let (Some(opened), Some(closed)) = (opened, closed)
                && opened != closed
            {
                violations.push(GroundTruthViolation::new(
                    3,
                    None,
                    format!(
                        "mapping {} marks {:?} on row {} as {opened} but its matching {:?} on row \
                         {} as {closed}",
                        side_name(side),
                        open.kind(),
                        open.start_position().row + 1,
                        close.kind(),
                        close.start_position().row + 1,
                    ),
                    vec![
                        ViolationSite {
                            side,
                            span: span_of_node(open),
                        },
                        ViolationSite {
                            side,
                            span: span_of_node(close),
                        },
                    ],
                ));
            }
        }
    }
    violations
}

/// Byte ranges of every `ERROR`/`MISSING` node in `root`'s tree. A zero-width `MISSING` node is
/// widened to one byte, or it could never overlap the pairs invented around it.
pub(crate) fn error_ranges(root: Node) -> Vec<(usize, usize)> {
    let mut ranges = Vec::new();
    let mut stack = vec![root];
    while let Some(node) = stack.pop() {
        if node.is_error() || node.is_missing() {
            ranges.push((
                node.start_byte(),
                node.end_byte().max(node.start_byte() + 1),
            ));
        }
        let mut cursor = node.walk();
        for child in node.children(&mut cursor) {
            stack.push(child);
        }
    }
    ranges
}

/// Every (opener, closer) pair in `root`'s tree - see [`delimiter_pairs_agree`] for the rule.
pub(crate) fn delimiter_pairs<'tree>(
    root: Node<'tree>,
    contents: &str,
) -> Vec<(Node<'tree>, Node<'tree>)> {
    let mut pairs = Vec::new();
    let mut stack = vec![root];
    while let Some(node) = stack.pop() {
        let mut open: Vec<Node<'tree>> = Vec::new();
        let mut cursor = node.walk();
        for child in node.children(&mut cursor) {
            stack.push(child);
            let kind = child.kind();
            if child.child_count() != 0 || contents.get(child.byte_range()) != Some(kind) {
                continue;
            }
            if closers_of(kind).is_some() {
                open.push(child);
            } else if is_closer(kind)
                && let Some(at) = open
                    .iter()
                    .rposition(|node| closers_of(node.kind()).is_some_and(|c| c.contains(&kind)))
            {
                pairs.push((open.remove(at), child));
            }
        }
    }
    pairs
}

/// True when the pairings `node`'s [`MultiMapGroup`](super::MultiMapGroup) admits disagree about
/// whether *this* member is matched, so the mapping makes no claim here.
///
/// With N before and M after members, `min(N, M)` pairs match: every member of the shorter side is
/// always matched, and if the other side is empty none is. Strictly between, which member is left
/// over is not something the human wrote down. An
/// [`AllToAll`](super::GroupPairing::AllToAll) group leaves nothing open. Nothing propagates to
/// descendants: both halves of a delimiter pair share a parent, so one member holds both.
fn group_leaves_status_open(
    node: Node,
    side: usize,
    groups: &[super::MultiMapGroup],
    caches: &Caches,
) -> bool {
    let index = if side == 0 {
        caches.before_group.get(&node.id())
    } else {
        caches.after_group.get(&node.id())
    };
    let Some(group) = index.and_then(|index| groups.get(*index)) else {
        return false;
    };
    if group.pairing == super::GroupPairing::AllToAll {
        return false;
    }
    let (mine, theirs) = if side == 0 {
        (group.before_paths.len(), group.after_paths.len())
    } else {
        (group.after_paths.len(), group.before_paths.len())
    };
    let matched = mine.min(theirs);
    matched > 0 && matched < mine
}

/// What the tree mapping says happened to `node`, or `None` if it says nothing.
fn mark_of(
    node: Node,
    side: usize,
    groups: &[super::MultiMapGroup],
    caches: &Caches,
) -> Option<&'static str> {
    if group_leaves_status_open(node, side, groups, caches) {
        return None;
    }
    let status = if side == 0 {
        status_before(node, caches)
    } else {
        status_after(node, caches)
    };
    match status {
        NodeStatus::Unmarked => None,
        NodeStatus::Matched => Some("matched"),
        NodeStatus::Marked {
            kind: MarkKind::Deleted,
            ..
        } => Some("deleted"),
        NodeStatus::Marked {
            kind: MarkKind::Inserted,
            ..
        } => Some("inserted"),
    }
}

fn side_name(side: usize) -> &'static str {
    if side == 0 { "before" } else { "after" }
}

/// One side's sites as a sorted, deduplicated row list, capped at `MAX_LISTED_ROWS` with the
/// remainder counted.
fn row_list(rows: &[usize]) -> String {
    const MAX_LISTED_ROWS: usize = 10;
    let mut rows = rows.to_vec();
    rows.sort_unstable();
    rows.dedup();
    let shown = rows
        .iter()
        .take(MAX_LISTED_ROWS)
        .map(usize::to_string)
        .collect::<Vec<_>>()
        .join(", ");
    match rows.len().checked_sub(MAX_LISTED_ROWS) {
        None | Some(0) if rows.len() == 1 => format!("row {shown}"),
        None | Some(0) => format!("rows {shown}"),
        Some(rest) => format!("rows {shown} and {rest} more"),
    }
}

/// Both sides' sites as one row list, naming each side - `before rows 3, 4 and after row 7`. A
/// side with no sites is left out.
fn site_rows(rows: &[Vec<usize>; 2]) -> String {
    [0usize, 1]
        .into_iter()
        .filter(|&side| !rows[side].is_empty())
        .map(|side| format!("{} {}", side_name(side), row_list(&rows[side])))
        .collect::<Vec<_>>()
        .join(" and ")
}

// ─────────────────────────────────────────────────────────────────────────────────────────────
// Invariants 10-15: the tree mapping read at the leaf, against the painting and against itself
// ─────────────────────────────────────────────────────────────────────────────────────────────

/// What the tree mapping says about one leaf: the nearest entry on the path from it to the root,
/// its own or an ancestor's, since a mapping speaks about subtrees, not leaves.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum LeafStatus<'tree> {
    /// Paired with a leaf that reads the same: the leaf's own `Identical` entry, or the leaf at
    /// the same offset under an `Identical` ancestor - well defined because such subtrees read
    /// token-for-token the same (invariant 14).
    Same(Node<'tree>),
    /// Paired by the leaf's own `Update` or `MatchButNotIdentical` entry.
    Paired(Node<'tree>),
    /// Deleted or inserted, by its own entry or under a `*WithChildren` ancestor.
    Removed,
    /// Under an `Update`/`MatchButNotIdentical` ancestor, or a childless `Delete`/`Insert`, with no
    /// entry of its own, or in a group member the group could leave over: the mapping has not said.
    Undecided,
}

/// The two trees indexed for the leaf-level invariants, built once per fixture.
pub(crate) struct TreeContext<'tree> {
    caches: Caches,
    /// The mapping's multi-map groups: a leaf whose group could leave it over is `Undecided`.
    groups: Vec<super::MultiMapGroup>,
    /// Node id to node, per side - how a partner id from [`Caches`] becomes a node again.
    ids: [std::collections::HashMap<usize, Node<'tree>>; 2],
    /// Every leaf per side, in source order.
    pub(crate) leaves: [Vec<Node<'tree>>; 2],
}

impl<'tree> TreeContext<'tree> {
    pub(crate) fn build(
        mapping: &super::HumanMapping,
        before_root: Node<'tree>,
        after_root: Node<'tree>,
    ) -> Self {
        let caches = rebuild_caches_for_mapping(mapping, before_root, after_root);
        let (before_ids, before_leaves) = index_tree(before_root);
        let (after_ids, after_leaves) = index_tree(after_root);
        Self {
            caches,
            groups: mapping.groups.clone(),
            ids: [before_ids, after_ids],
            leaves: [before_leaves, after_leaves],
        }
    }

    pub(crate) fn status(&self, leaf: Node<'tree>, side: usize) -> LeafStatus<'tree> {
        if group_leaves_status_open(leaf, side, &self.groups, &self.caches) {
            return LeafStatus::Undecided;
        }
        let (matches, operations, removed) = if side == 0 {
            (
                &self.caches.before_match,
                &self.caches.before_operation,
                &self.caches.before_removed,
            )
        } else {
            (
                &self.caches.after_match,
                &self.caches.after_operation,
                &self.caches.after_removed,
            )
        };
        let mut current = leaf;
        loop {
            if let Some(&partner) = matches.get(&current.id()) {
                let identical = operations.get(&current.id()).copied()
                    == Some(super::HumanOperation::Identical);
                let Some(partner) = self.ids[1 - side].get(&partner).copied() else {
                    return LeafStatus::Undecided;
                };
                if current.id() == leaf.id() {
                    return if identical {
                        LeafStatus::Same(partner)
                    } else {
                        LeafStatus::Paired(partner)
                    };
                }
                if !identical {
                    return LeafStatus::Undecided;
                }
                // The leaf at the same offset in the partner subtree.
                let start = partner.start_byte() + (leaf.start_byte() - current.start_byte());
                let end = start + (leaf.end_byte() - leaf.start_byte());
                return match partner.descendant_for_byte_range(start, end) {
                    Some(twin)
                        if twin.start_byte() == start
                            && twin.end_byte() == end
                            && twin.kind() == leaf.kind() =>
                    {
                        LeafStatus::Same(twin)
                    }
                    _ => LeafStatus::Undecided,
                };
            }
            if let Some(&with_children) = removed.get(&current.id()) {
                return if group_leaves_status_open(current, side, &self.groups, &self.caches) {
                    // The group could equally have left another member over.
                    LeafStatus::Undecided
                } else if current.id() == leaf.id() || with_children {
                    LeafStatus::Removed
                } else {
                    LeafStatus::Undecided
                };
            }
            match current.parent() {
                Some(parent) => current = parent,
                None => return LeafStatus::Undecided,
            }
        }
    }

    /// The node `node` is matched with on the other side, or `None` when the mapping pairs it with
    /// nothing.
    pub(crate) fn partner(&self, node: Node<'tree>, side: usize) -> Option<Node<'tree>> {
        let matches = if side == 0 {
            &self.caches.before_match
        } else {
            &self.caches.after_match
        };
        matches
            .get(&node.id())
            .and_then(|id| self.ids[1 - side].get(id))
            .copied()
    }
}

fn index_tree<'tree>(
    root: Node<'tree>,
) -> (
    std::collections::HashMap<usize, Node<'tree>>,
    Vec<Node<'tree>>,
) {
    let mut ids = std::collections::HashMap::new();
    let mut leaves = Vec::new();
    let mut stack = vec![root];
    while let Some(node) = stack.pop() {
        ids.insert(node.id(), node);
        if node.child_count() == 0 {
            leaves.push(node);
        }
        let mut cursor = node.walk();
        for child in node.children(&mut cursor) {
            stack.push(child);
        }
    }
    leaves.sort_by_key(|node| node.start_byte());
    (ids, leaves)
}

/// A leaf with something visible in it. Zero-width and whitespace-only leaves (Python's `indent`
/// and `newline`, and the like) carry nothing a painting could colour.
pub(crate) fn is_visible_leaf(leaf: Node, contents: &str) -> bool {
    contents
        .get(leaf.byte_range())
        .is_some_and(|text| !text.trim().is_empty())
}

/// A leaf whose text is not its own kind name: identifiers, literals, comments, string contents.
/// Punctuation is excluded where a rule says so, since which of two `}` survives is each ground
/// truth's own choice.
fn is_named_leaf(leaf: Node, contents: &str) -> bool {
    contents.get(leaf.byte_range()) != Some(leaf.kind())
}

/// The painting's verdict over a whole leaf: `Some(None)` unpainted, `Some(Some(label))` one label
/// over every byte, `None` a mixture.
fn whole_leaf_label(labels: &[Option<TextLabel>], leaf: Node) -> Option<Option<TextLabel>> {
    let slice = labels.get(leaf.byte_range())?;
    let first = *slice.first()?;
    slice.iter().all(|label| *label == first).then_some(first)
}

fn leaf_text(leaf: Node, contents: &str) -> String {
    contents[leaf.byte_range()].chars().take(40).collect()
}

fn row_of(contents: &str, byte: usize) -> usize {
    contents[..byte].matches('\n').count() + 1
}

/// The text with all whitespace removed: a reformatting is not an edit to a token.
fn without_whitespace(text: &str) -> String {
    text.chars().filter(|c| !c.is_whitespace()).collect()
}

/// Invariant 10: a leaf the mapping pairs with a byte-identical leaf is never painted `Delete`
/// while that partner is painted `Insert`.
///
/// The mirror of invariant 9, asked of the tree's pairs. `Identical` says one text; `Delete` and
/// `Insert` say it left and something new arrived. A line painted whole leaves the mapper's
/// tokens under `Update` ancestors, which [`LeafStatus::Undecided`] skips.
fn paired_leaves_are_not_deleted_and_inserted(
    painting: &str,
    painted: &PaintedLabels,
    context: &TreeContext,
    before: &Code,
    after: &Code,
) -> Vec<GroundTruthViolation> {
    let mut count = 0usize;
    let mut first = String::new();
    let mut rows: [Vec<usize>; 2] = [Vec::new(), Vec::new()];
    let mut sites = Vec::new();
    for leaf in &context.leaves[0] {
        if !is_visible_leaf(*leaf, &before.contents) {
            continue;
        }
        let LeafStatus::Same(partner) = context.status(*leaf, 0) else {
            continue;
        };
        if whole_leaf_label(&painted[0], *leaf) != Some(Some(TextLabel::Delete))
            || whole_leaf_label(&painted[1], partner) != Some(Some(TextLabel::Insert))
        {
            continue;
        }
        if count == 0 {
            first = leaf_text(*leaf, &before.contents);
        }
        rows[0].push(row_of(&before.contents, leaf.start_byte()));
        rows[1].push(row_of(&after.contents, partner.start_byte()));
        if sites.len() < MAX_SITES {
            sites.push(ViolationSite {
                side: 0,
                span: span_of_node(*leaf),
            });
            sites.push(ViolationSite {
                side: 1,
                span: span_of_node(partner),
            });
        }
        count += 1;
    }
    if count == 0 {
        return Vec::new();
    }
    vec![GroundTruthViolation::new(
        10,
        Some(painting),
        format!(
            "painting '{painting}' paints {count} leaf pair(s) gone on one side and new on the \
             other that the tree mapping calls the same text, on {} - the first is `{first}`",
            site_rows(&rows),
        ),
        sites,
    )]
}

/// Invariant 11: a named leaf the mapping deletes or inserts has at least one painted byte.
///
/// Unpainted text claims "unchanged, and in place". Named leaves only ([`is_named_leaf`]): a
/// deleted `}` whose partner the painter kept instead is the ordinary brace-identity difference.
fn removed_leaves_are_painted(
    painting: &str,
    painted: &PaintedLabels,
    context: &TreeContext,
    before: &Code,
    after: &Code,
) -> Vec<GroundTruthViolation> {
    let mut violations = Vec::new();
    for (side, code) in [(0usize, before), (1usize, after)] {
        let mut count = 0usize;
        let mut first = String::new();
        let mut rows = Vec::new();
        let mut sites = Vec::new();
        for leaf in &context.leaves[side] {
            if !is_visible_leaf(*leaf, &code.contents) || !is_named_leaf(*leaf, &code.contents) {
                continue;
            }
            if context.status(*leaf, side) != LeafStatus::Removed
                || whole_leaf_label(&painted[side], *leaf) != Some(None)
            {
                continue;
            }
            if count == 0 {
                first = format!("{:?} `{}`", leaf.kind(), leaf_text(*leaf, &code.contents));
            }
            rows.push(row_of(&code.contents, leaf.start_byte()));
            if sites.len() < MAX_SITES {
                sites.push(ViolationSite {
                    side,
                    span: span_of_node(*leaf),
                });
            }
            count += 1;
        }
        if count > 0 {
            violations.push(GroundTruthViolation::new(
                11,
                Some(painting),
                format!(
                    "painting '{painting}' {} leaves {count} removed leaf/leaves unpainted on {}, \
                     the first {first} - unpainted text is unchanged and in place, and the tree \
                     mapping says this is gone",
                    side_name(side),
                    row_list(&rows),
                ),
                sites,
            ));
        }
    }
    violations
}

/// Invariant 12: a leaf the mapping pairs with a leaf that reads differently is painted on at
/// least one side.
///
/// *At least one side*: `Minimal` paints a rename's deleted prefix and nothing on the after side,
/// which is exact. Whitespace-only differences are exempt, as in invariant 14.
fn edited_leaves_are_painted(
    painting: &str,
    painted: &PaintedLabels,
    context: &TreeContext,
    before: &Code,
    after: &Code,
) -> Vec<GroundTruthViolation> {
    let mut count = 0usize;
    let mut first = String::new();
    let mut rows: [Vec<usize>; 2] = [Vec::new(), Vec::new()];
    let mut sites = Vec::new();
    for leaf in &context.leaves[0] {
        if !is_visible_leaf(*leaf, &before.contents) {
            continue;
        }
        let LeafStatus::Paired(partner) = context.status(*leaf, 0) else {
            continue;
        };
        if without_whitespace(&before.contents[leaf.byte_range()])
            == without_whitespace(&after.contents[partner.byte_range()])
        {
            continue;
        }
        if whole_leaf_label(&painted[0], *leaf) != Some(None)
            || whole_leaf_label(&painted[1], partner) != Some(None)
        {
            continue;
        }
        if count == 0 {
            first = format!(
                "`{}` becoming `{}`",
                leaf_text(*leaf, &before.contents),
                leaf_text(partner, &after.contents),
            );
        }
        rows[0].push(row_of(&before.contents, leaf.start_byte()));
        rows[1].push(row_of(&after.contents, partner.start_byte()));
        if sites.len() < MAX_SITES {
            sites.push(ViolationSite {
                side: 0,
                span: span_of_node(*leaf),
            });
            sites.push(ViolationSite {
                side: 1,
                span: span_of_node(partner),
            });
        }
        count += 1;
    }
    if count == 0 {
        return Vec::new();
    }
    vec![GroundTruthViolation::new(
        12,
        Some(painting),
        format!(
            "painting '{painting}' paints nothing on either side of {count} edited leaf/leaves, \
             on {} - the first is {first}; the tree mapping says the text changed",
            site_rows(&rows),
        ),
        sites,
    )]
}

/// Invariant 13: a painting that records an edit belongs to a mapping that records one too.
///
/// An all-`Identical` mapping with balanced groups says nothing changed, and grades omnidiff
/// against nothing. A painting with a visible `Delete`/`Insert`, or a `Match` differing beyond
/// whitespace, says otherwise. Whitespace is exempt: it lives between nodes, where the tree cannot
/// record it.
fn painting_implies_mapping_edits(
    mapping: &super::HumanMapping,
    named: &NamedTextMapping,
    before: &Code,
    after: &Code,
) -> Vec<GroundTruthViolation> {
    if mapping.entries.is_empty()
        || mapping
            .entries
            .iter()
            .any(|entry| entry.operation != super::HumanOperation::Identical)
        || mapping
            .groups
            .iter()
            .any(|group| group.before_paths.len() != group.after_paths.len())
    {
        return Vec::new();
    }
    let side_text = |contents: &str, spans: &[HumanTextSpan]| -> String {
        spans
            .iter()
            .filter_map(|span| super::span_text(contents, *span))
            .map(without_whitespace)
            .collect()
    };
    let mut edits = 0usize;
    let mut rows: [Vec<usize>; 2] = [Vec::new(), Vec::new()];
    let mut sites = Vec::new();
    for entry in &named.mapping.entries {
        let before_text = side_text(&before.contents, &entry.before);
        let after_text = side_text(&after.contents, &entry.after);
        let is_edit = match entry.operation {
            super::HumanTextOperation::Match => before_text != after_text,
            super::HumanTextOperation::Delete => !before_text.is_empty(),
            super::HumanTextOperation::Insert => !after_text.is_empty(),
        };
        if !is_edit {
            continue;
        }
        edits += 1;
        for (side, spans) in [(0usize, &entry.before), (1usize, &entry.after)] {
            rows[side].extend(spans.iter().map(|span| span.start_row + 1));
            sites.extend(
                spans
                    .iter()
                    .take(MAX_SITES.saturating_sub(sites.len()))
                    .map(|span| ViolationSite { side, span: *span }),
            );
        }
    }
    if edits == 0 {
        return Vec::new();
    }
    vec![GroundTruthViolation::new(
        13,
        Some(&named.name),
        format!(
            "painting '{}' records {edits} edit(s) to visible text on {} but every entry of the \
             tree mapping is Identical - one of the two records has not been finished",
            named.name,
            site_rows(&rows),
        ),
        sites,
    )]
}

/// The visible tokens under `node`, in source order, as (kind, text).
fn tokens_of(node: Node, contents: &str) -> Vec<(&'static str, String)> {
    let mut tokens = Vec::new();
    let mut stack = vec![node];
    while let Some(current) = stack.pop() {
        if current.child_count() == 0 {
            if is_visible_leaf(current, contents) {
                tokens.push((current.kind(), contents[current.byte_range()].to_string()));
            }
        } else {
            let mut cursor = current.walk();
            let children: Vec<Node> = current.children(&mut cursor).collect();
            stack.extend(children.into_iter().rev());
        }
    }
    tokens
}

/// Invariant 14: an `Identical` entry's two subtrees carry the same tokens. Tokens, not text,
/// since a reformatting is not an edit. The leaf-level rules rely on it to find a leaf's twin.
fn identical_entries_are_token_identical(
    context: &TreeContext,
    before: &Code,
    after: &Code,
) -> Vec<GroundTruthViolation> {
    let mut violations = Vec::new();
    let mut pairs: Vec<(usize, usize)> = context
        .caches
        .before_match
        .iter()
        .filter(|(b, _)| {
            context.caches.before_operation.get(*b).copied()
                == Some(super::HumanOperation::Identical)
        })
        .map(|(b, a)| (*b, *a))
        .collect();
    pairs.sort_by_key(|(b, _)| context.ids[0].get(b).map(|n| n.start_byte()));
    for (b, a) in pairs {
        let (Some(before_node), Some(after_node)) =
            (context.ids[0].get(&b), context.ids[1].get(&a))
        else {
            continue;
        };
        let before_tokens = tokens_of(*before_node, &before.contents);
        let after_tokens = tokens_of(*after_node, &after.contents);
        if before_tokens == after_tokens {
            continue;
        }
        let difference = before_tokens
            .iter()
            .zip(after_tokens.iter())
            .find(|(x, y)| x != y)
            .map(|(x, y)| format!("`{}` against `{}`", x.1, y.1))
            .unwrap_or_else(|| {
                format!(
                    "{} token(s) against {}",
                    before_tokens.len(),
                    after_tokens.len()
                )
            });
        violations.push(GroundTruthViolation::new(
            14,
            None,
            format!(
                "mapping calls {:?} on before row {} Identical to {:?} on after row {}, but their \
                 tokens differ: {difference}",
                before_node.kind(),
                row_of(&before.contents, before_node.start_byte()),
                after_node.kind(),
                row_of(&after.contents, after_node.start_byte()),
            ),
            vec![
                ViolationSite {
                    side: 0,
                    span: span_of_node(*before_node),
                },
                ViolationSite {
                    side: 1,
                    span: span_of_node(*after_node),
                },
            ],
        ));
    }
    violations
}

/// Which field of `parent` holds `node`, or `None` when the grammar gives it no field.
pub(crate) fn field_of<'tree>(parent: Node<'tree>, node: Node<'tree>) -> Option<String> {
    let mut cursor = parent.walk();
    let children: Vec<Node<'tree>> = parent.children(&mut cursor).collect();
    children
        .iter()
        .position(|child| child.id() == node.id())
        .and_then(|i| parent.field_name_for_child(i as u32))
        .map(str::to_string)
}

/// How many of `parent`'s children carry `field`. More than one makes it a list, and a position
/// in a list is not an identity.
pub(crate) fn field_arity(parent: Node, field: &str) -> usize {
    let mut cursor = parent.walk();
    let count = parent.children(&mut cursor).count();
    (0..count)
        .filter(|i| parent.field_name_for_child(*i as u32) == Some(field))
        .count()
}

/// The after-side node that occupies the same unambiguous position as `before_leaf`, or `None`.
///
/// * **By name** - a *named* field holding exactly one child on both sides.
/// * **By elimination** - equal child counts with every *other* position paired. Needed because
///   some grammars name no fields where position is obvious (tree-sitter-java's `argument_list`).
pub(crate) fn pinned_counterpart<'tree>(
    context: &TreeContext<'tree>,
    before_leaf: Node<'tree>,
    before_parent: Node<'tree>,
    after_parent: Node<'tree>,
) -> Option<Node<'tree>> {
    if let Some(field) = field_of(before_parent, before_leaf)
        && field_arity(before_parent, &field) == 1
        && field_arity(after_parent, &field) == 1
        && let Some(after_leaf) = after_parent.child_by_field_name(field.as_str())
    {
        return Some(after_leaf);
    }

    let mut before_cursor = before_parent.walk();
    let before_children: Vec<Node<'tree>> = before_parent.children(&mut before_cursor).collect();
    let mut after_cursor = after_parent.walk();
    let after_children: Vec<Node<'tree>> = after_parent.children(&mut after_cursor).collect();
    if before_children.len() != after_children.len() {
        return None;
    }
    let index = before_children
        .iter()
        .position(|child| child.id() == before_leaf.id())?;
    // Every other position paired, in order. One unpaired position is pinned; two are a guess.
    for (i, (b, a)) in before_children
        .iter()
        .zip(after_children.iter())
        .enumerate()
    {
        if i == index {
            continue;
        }
        if context.caches.before_match.get(&b.id()) != Some(&a.id()) {
            return None;
        }
    }
    Some(after_children[index])
}

/// The token a node reads as: the node itself when it is a leaf, or its only child when that is
/// an unnamed leaf spanning all of it, as in the C grammar's `null` around `NULL` or `nullptr`.
/// `None` for anything larger - a Rust `line_comment` whose only child is its `//` reads as more
/// than that token.
pub(crate) fn lexeme_token(node: Node) -> Option<Node> {
    match node.child_count() {
        0 => Some(node),
        1 => node.child(0).filter(|child| {
            !child.is_named() && child.child_count() == 0 && child.byte_range() == node.byte_range()
        }),
        _ => None,
    }
}

/// A node that is nothing but one unnamed token ([`lexeme_token`]): C's `null`, not `NULL`.
fn wraps_one_token(node: Node) -> bool {
    lexeme_token(node).is_some_and(|token| token.id() != node.id())
}

/// Every position a matched pair pins ([`pinned_counterpart`]) whose occupant reads as one token
/// ([`lexeme_token`]) and is deleted on the before side while the after side's is inserted, as
/// `(before, after)` occupants. An occupant is the token itself, or the node wrapping it when that
/// node is unmatched too; a wrapper the mapping pairs puts its token in its own pinned position.
/// Visible tokens only.
pub(crate) fn pinned_removed_lexemes<'tree>(
    context: &TreeContext<'tree>,
    before: &Code,
    after: &Code,
) -> Vec<(Node<'tree>, Node<'tree>)> {
    let mut found = Vec::new();
    for &token in &context.leaves[0] {
        if !is_visible_leaf(token, &before.contents)
            || context.status(token, 0) != LeafStatus::Removed
        {
            continue;
        }
        let mut occupants = vec![token];
        if let Some(wrapper) = token.parent()
            && lexeme_token(wrapper).is_some_and(|inner| inner.id() == token.id())
            && context.partner(wrapper, 0).is_none()
        {
            occupants.push(wrapper);
        }
        for occupant in occupants {
            let Some(parent) = occupant.parent() else {
                continue;
            };
            let Some(after_parent) = context.partner(parent, 0) else {
                continue;
            };
            let Some(after_occupant) = pinned_counterpart(context, occupant, parent, after_parent)
            else {
                continue;
            };
            let Some(after_token) = lexeme_token(after_occupant) else {
                continue;
            };
            if after_occupant.id() != after_token.id()
                && context.partner(after_occupant, 1).is_some()
            {
                continue;
            }
            if !is_visible_leaf(after_token, &after.contents)
                || context.status(after_token, 1) != LeafStatus::Removed
            {
                continue;
            }
            found.push((occupant, after_occupant));
        }
    }
    found
}

/// Invariant 18: an unambiguous position of a matched pair holds a matched pair, never a
/// delete beside an insert: the parent match already says the role persists.
///
/// Each condition prevents a real false positive: nodes that *read as one token*
/// ([`lexeme_token`]: a leaf, or a node around one unnamed token spanning all of it - an empty
/// container has no named children either, but `()` is two tokens), a *named* field (two adjacent
/// comments share no role), and arity *one* (a removed flag beside an added subcommand in one
/// argument list is not a pair). `LeafStatus::Undecided` is not a violation.
///
/// Wrappers count since 2026-09-30: C's `nullptr` is a `null` node around the token, so `0` ->
/// `nullptr` escaped a leaf-only test, as did Java's `?` (a `wildcard`). Two wrappers against each
/// other are not this rule's: see invariant 20.
fn single_valued_fields_hold_a_pair(
    context: &TreeContext,
    before: &Code,
    after: &Code,
) -> Vec<GroundTruthViolation> {
    let mut violations = Vec::new();
    for (before_leaf, after_leaf) in pinned_removed_lexemes(context, before, after) {
        if !before_leaf.is_named() || !after_leaf.is_named() {
            continue;
        }
        // Two wrappers are left out: of one kind they are invariant 20's, and of two kinds they are
        // two roles, not one element (`static` -> `const`, see `wrapped_tokens_are_paired`).
        if wraps_one_token(before_leaf) && wraps_one_token(after_leaf) {
            continue;
        }
        let Some(before_parent) = before_leaf.parent() else {
            continue;
        };
        // Cross-kind pairs only: `Update` requires equal kinds, so a cross-kind pair has no
        // schema representation, while a same-kind delete+insert is a decision the author was
        // entitled to make.
        if before_leaf.kind() == after_leaf.kind() {
            continue;
        }
        violations.push(GroundTruthViolation::new(
            18,
            None,
            format!(
                "{} holds {} `{}` on before row {} and {} `{}` on after row {}, but the mapping \
                 deletes one and inserts the other - the parents are matched and nothing else can \
                 occupy that position, so the two are the same element",
                field_of(before_parent, before_leaf).map_or_else(
                    || before_parent.kind().to_string(),
                    |field| format!("{}.{field}", before_parent.kind()),
                ),
                before_leaf.kind(),
                before_leaf
                    .utf8_text(before.contents.as_bytes())
                    .unwrap_or("<unreadable>"),
                row_of(&before.contents, before_leaf.start_byte()),
                after_leaf.kind(),
                after_leaf
                    .utf8_text(after.contents.as_bytes())
                    .unwrap_or("<unreadable>"),
                row_of(&after.contents, after_leaf.start_byte()),
            ),
            vec![
                ViolationSite {
                    side: 0,
                    span: span_of_node(before_leaf),
                },
                ViolationSite {
                    side: 1,
                    span: span_of_node(after_leaf),
                },
            ],
        ));
    }
    violations
}

/// Invariant 20: a node that is nothing but one unnamed token, in a position a matched pair pins
/// ([`pinned_counterpart`]), is paired. The mapping can break that two ways, both reported:
///
/// * **The node is matched and its token deleted and inserted.** Matching `null` with `null`
///   already says the element persists, and the token is all of it.
/// * **The node is deleted and inserted whole.** Its parents are matched and nothing else can
///   occupy the position, so `NULL` -> `nullptr` is one element changing its text.
///
/// Unlike invariant 18 this holds for equal kinds too: `null` against `null` is the case it exists
/// for. What makes a same-kind delete+insert a judgment there (a renamed field of `a.b`) is a name
/// the author may call unrelated; a node that is only a keyword-like token has no identity beside
/// its position. Nodes of that shape: C/C++ `null`, Rust `boolean_literal`, C++
/// `access_specifier`. The corpus had none of either break when this was added (2026-09-30,
/// `pinned_lexeme_census`); a leaf against a wrapped token (`0` -> `nullptr`) is invariant 18's.
///
/// **Same kind only.** Two wrappers of different kinds are two different roles, not one element:
/// `static auto width{...}` -> `const auto w = ...` removes a storage class and adds a type
/// qualifier in the one position of a declaration's specifiers that elimination pins
/// (`cpp-microsoft-terminal-funny-code-comment`). Neither this rule nor 18 checks that pair.
fn wrapped_tokens_are_paired(
    context: &TreeContext,
    before: &Code,
    after: &Code,
) -> Vec<GroundTruthViolation> {
    let mut violations = Vec::new();
    for (before_node, after_node) in pinned_removed_lexemes(context, before, after) {
        let whole = wraps_one_token(before_node) && wraps_one_token(after_node);
        let token_of_matched = |token: Node| {
            !token.is_named()
                && token.parent().is_some_and(|parent| {
                    lexeme_token(parent).is_some_and(|t| t.id() == token.id())
                })
        };
        let inside = token_of_matched(before_node) && token_of_matched(after_node);
        if !whole && !inside {
            continue;
        }
        // The wrappers' kinds: the nodes themselves, or the matched parents of the two tokens.
        let wrapper_kinds = if whole {
            (Some(before_node.kind()), Some(after_node.kind()))
        } else {
            (
                before_node.parent().map(|parent| parent.kind()),
                after_node.parent().map(|parent| parent.kind()),
            )
        };
        if wrapper_kinds.0 != wrapper_kinds.1 {
            continue;
        }
        let before_token = lexeme_token(before_node).unwrap_or(before_node);
        let after_token = lexeme_token(after_node).unwrap_or(after_node);
        let text = |node: Node, contents: &str| {
            node.utf8_text(contents.as_bytes())
                .unwrap_or("<unreadable>")
                .to_string()
        };
        let wrapper_kind = if whole {
            before_node.kind()
        } else {
            before_token.parent().map_or("?", |parent| parent.kind())
        };
        let how = if whole {
            "deletes the one and inserts the other whole - their parents are matched and nothing \
             else can occupy that position"
        } else {
            "pairs the two but deletes one token and inserts the other - the node is nothing but \
             its token"
        };
        violations.push(GroundTruthViolation::new(
            20,
            None,
            format!(
                "`{wrapper_kind}` reads `{}` on before row {} and `{}` on after row {}, and the \
                 mapping {how}, so `{}` -> `{}` is one element changing its text",
                text(before_token, &before.contents),
                row_of(&before.contents, before_token.start_byte()),
                text(after_token, &after.contents),
                row_of(&after.contents, after_token.start_byte()),
                text(before_token, &before.contents),
                text(after_token, &after.contents),
            ),
            vec![
                ViolationSite {
                    side: 0,
                    span: span_of_node(before_token),
                },
                ViolationSite {
                    side: 1,
                    span: span_of_node(after_token),
                },
            ],
        ));
    }
    violations
}

// ─────────────────────────────────────────────────────────────────────────────────────────────
// Invariants 21-23: what a painting says about a token against what the tree mapping says
// ─────────────────────────────────────────────────────────────────────────────────────────────

/// Every span of `named`'s `Match` entries as byte ranges, per side.
fn match_spans(named: &NamedTextMapping, codes: [&Code; 2]) -> Vec<[Vec<(usize, usize)>; 2]> {
    named
        .mapping
        .entries
        .iter()
        .filter(|entry| entry.operation == super::HumanTextOperation::Match)
        .map(|entry| {
            let bytes = |side: usize, spans: &[HumanTextSpan]| {
                spans
                    .iter()
                    .filter_map(|span| {
                        let contents = &codes[side].contents;
                        Some((
                            super::byte_offset(contents, span.start_row, span.start_column)?,
                            super::byte_offset(contents, span.end_row, span.end_column)?,
                        ))
                    })
                    .collect()
            };
            [bytes(0, &entry.before), bytes(1, &entry.after)]
        })
        .collect()
}

/// Collects one violation per painting and rule: a count, the first token, the rows, and sites.
struct Tally {
    count: usize,
    first: String,
    rows: [Vec<usize>; 2],
    sites: Vec<ViolationSite>,
}

impl Tally {
    fn new() -> Self {
        Self {
            count: 0,
            first: String::new(),
            rows: [Vec::new(), Vec::new()],
            sites: Vec::new(),
        }
    }

    fn add(&mut self, side: usize, leaf: Node, contents: &str) {
        if self.count == 0 {
            self.first = leaf_text(leaf, contents);
        }
        self.count += 1;
        self.rows[side].push(row_of(contents, leaf.start_byte()));
        if self.sites.len() < MAX_SITES {
            self.sites.push(ViolationSite {
                side,
                span: span_of_node(leaf),
            });
        }
    }
}

/// Invariant 21: a token painted as one `Update` span of its own is not deleted or inserted by the
/// tree mapping. The painting says the token became the other side's; the mapping says it is gone
/// (`&` -> `*`, `as` -> `as_if`, `cpp-ladybird-refactor-variables-if-changes`).
///
/// Only a span that is exactly the token: a byte of a larger edited span may well be new - `val` in
/// `width: Double` -> `val width: Double` (`kotlin-refactor-function`). Punctuation included; the
/// corpus had no false hit when this was added (2026-10-01, `mapping_painting_census`).
fn painted_updates_are_not_removed(
    named: &NamedTextMapping,
    labels: &PaintedLabels,
    context: &TreeContext,
    before: &Code,
    after: &Code,
) -> Vec<GroundTruthViolation> {
    let codes = [before, after];
    let mut exact: [std::collections::HashSet<(usize, usize)>; 2] = Default::default();
    for spans in match_spans(named, codes) {
        for side in 0..2 {
            exact[side].extend(spans[side].iter().copied());
        }
    }
    let mut tally = Tally::new();
    for side in 0..2 {
        for leaf in &context.leaves[side] {
            if !is_visible_leaf(*leaf, &codes[side].contents)
                || !exact[side].contains(&(leaf.start_byte(), leaf.end_byte()))
                || whole_leaf_label(&labels[side], *leaf) != Some(Some(TextLabel::Update))
                || context.status(*leaf, side) != LeafStatus::Removed
            {
                continue;
            }
            tally.add(side, *leaf, &codes[side].contents);
        }
    }
    if tally.count == 0 {
        return Vec::new();
    }
    vec![GroundTruthViolation::new(
        21,
        Some(&named.name),
        format!(
            "painting '{}' paints {} token(s) as an update of their own that the tree mapping \
             deletes or inserts, on {} - the first is `{}`; an update says the token became the \
             other side's, an unmatched node says it is gone",
            named.name,
            tally.count,
            site_rows(&tally.rows),
            tally.first,
        ),
        tally.sites,
    )]
}

/// Invariant 22: a named leaf the tree mapping pairs with an identical leaf is not painted wholly
/// `Delete` (before) or `Insert` (after), whatever its partner's painting - invariant 10 asks for
/// both. `active_view_box` is painted new on after row 206 of
/// `cpp-ladybird-refactor-variables-if-changes` while the mapping moves it there.
///
/// Named leaves only: which of two identical delimiters survives is each ground truth's choice. A
/// partner that reads differently is not this rule's: whether a paired replacement (`nextLineTabStop`
/// -> `0`) may be painted gone and new is an open convention.
fn identical_pairs_are_not_painted_removed(
    painting: &str,
    labels: &PaintedLabels,
    context: &TreeContext,
    before: &Code,
    after: &Code,
) -> Vec<GroundTruthViolation> {
    let codes = [before, after];
    let mut tally = Tally::new();
    for side in 0..2 {
        let removed = if side == 0 {
            TextLabel::Delete
        } else {
            TextLabel::Insert
        };
        for leaf in &context.leaves[side] {
            let contents = &codes[side].contents;
            if !is_visible_leaf(*leaf, contents)
                || !is_named_leaf(*leaf, contents)
                || whole_leaf_label(&labels[side], *leaf) != Some(Some(removed))
                || !matches!(context.status(*leaf, side), LeafStatus::Same(_))
            {
                continue;
            }
            tally.add(side, *leaf, contents);
        }
    }
    if tally.count == 0 {
        return Vec::new();
    }
    vec![GroundTruthViolation::new(
        22,
        Some(painting),
        format!(
            "painting '{painting}' paints {} leaf/leaves wholly deleted or inserted that the tree \
             mapping pairs with an identical leaf, on {} - the first is `{}`",
            tally.count,
            site_rows(&tally.rows),
            tally.first,
        ),
        tally.sites,
    )]
}

/// Invariant 23: a named leaf inside a painted `Match` has its tree-mapping partner inside, or
/// overlapping, that `Match`'s spans on the other side: the painting pairs the two places, and the
/// mapping may not pair the leaf with a third. `parent` on after row 550 of
/// `cpp-ladybird-refactor-variables-if-changes` is painted moved from there while the mapping
/// renames it from `parent_node` on before row 527.
///
/// Overlap, not containment: Minimal paints part of a token (`Linked` inserted and `HashMap`
/// matched in `HashMap` -> `LinkedHashMap`). Named leaves only, as for 22; it also keeps out the
/// alternative paintings of an ambiguous parenthesis ("Full (outer)", "Full (inner)"), of which
/// the mapping can agree with one.
fn painted_matches_hold_the_mapping_partner(
    named: &NamedTextMapping,
    context: &TreeContext,
    before: &Code,
    after: &Code,
) -> Vec<GroundTruthViolation> {
    let codes = [before, after];
    let mut tally = Tally::new();
    for spans in match_spans(named, codes) {
        for side in 0..2 {
            for leaf in &context.leaves[side] {
                let contents = &codes[side].contents;
                let range = leaf.byte_range();
                if !is_visible_leaf(*leaf, contents)
                    || !is_named_leaf(*leaf, contents)
                    || !spans[side]
                        .iter()
                        .any(|&(start, end)| start <= range.start && range.end <= end)
                {
                    continue;
                }
                let partner = match context.status(*leaf, side) {
                    LeafStatus::Same(partner) | LeafStatus::Paired(partner) => partner,
                    _ => continue,
                };
                let theirs = partner.byte_range();
                if spans[1 - side]
                    .iter()
                    .any(|&(start, end)| start < theirs.end && theirs.start < end)
                {
                    continue;
                }
                tally.add(side, *leaf, contents);
            }
        }
    }
    if tally.count == 0 {
        return Vec::new();
    }
    vec![GroundTruthViolation::new(
        23,
        Some(&named.name),
        format!(
            "painting '{}' matches {} leaf/leaves to a place the tree mapping does not pair them \
             with, on {} - the first is `{}`",
            named.name,
            tally.count,
            site_rows(&tally.rows),
            tally.first,
        ),
        tally.sites,
    )]
}

/// Invariant 15: a `MatchButNotIdentical` entry's two subtrees do not read byte-identically with
/// every descendant paired inside. Such an entry could only be satisfied by omnidiff calling an
/// identical subtree not identical, since `check_entry` is strict about the operation. Group
/// members are skipped: the operation describes the whole group.
fn match_but_not_identical_entries_differ(
    context: &TreeContext,
    before: &Code,
    after: &Code,
) -> Vec<GroundTruthViolation> {
    let mut violations = Vec::new();
    let mut pairs: Vec<(usize, usize)> = context
        .caches
        .before_match
        .iter()
        .filter(|(b, a)| {
            context.caches.before_operation.get(*b).copied()
                == Some(super::HumanOperation::MatchButNotIdentical)
                && !context.caches.before_group.contains_key(*b)
                && !context.caches.after_group.contains_key(*a)
        })
        .map(|(b, a)| (*b, *a))
        .collect();
    pairs.sort_by_key(|(b, _)| context.ids[0].get(b).map(|n| n.start_byte()));
    for (b, a) in pairs {
        let (Some(before_node), Some(after_node)) =
            (context.ids[0].get(&b), context.ids[1].get(&a))
        else {
            continue;
        };
        if before_node.kind() != after_node.kind()
            || before.contents[before_node.byte_range()] != after.contents[after_node.byte_range()]
        {
            continue;
        }
        let mut descendants_stay = true;
        let mut stack = vec![*before_node];
        while let Some(node) = stack.pop() {
            if node.id() != before_node.id() {
                if context.caches.before_removed.contains_key(&node.id()) {
                    descendants_stay = false;
                }
                if let Some(partner) = context
                    .caches
                    .before_match
                    .get(&node.id())
                    .and_then(|id| context.ids[1].get(id))
                    && !(after_node.start_byte() <= partner.start_byte()
                        && partner.end_byte() <= after_node.end_byte())
                {
                    descendants_stay = false;
                }
            }
            let mut cursor = node.walk();
            for child in node.children(&mut cursor) {
                stack.push(child);
            }
        }
        if !descendants_stay {
            continue;
        }
        violations.push(GroundTruthViolation::new(
            15,
            None,
            format!(
                "mapping calls {:?} on before row {} MatchButNotIdentical to after row {}, but \
                 the two read byte-identically and every descendant with an entry pairs inside it",
                before_node.kind(),
                row_of(&before.contents, before_node.start_byte()),
                row_of(&after.contents, after_node.start_byte()),
            ),
            vec![
                ViolationSite {
                    side: 0,
                    span: span_of_node(*before_node),
                },
                ViolationSite {
                    side: 1,
                    span: span_of_node(*after_node),
                },
            ],
        ));
    }
    violations
}

// ─────────────────────────────────────────────────────────────────────────────────────────────
// Invariant 16: an identifier the mapping calls edited is painted narrow by Minimal, whole by Full
// ─────────────────────────────────────────────────────────────────────────────────────────────

/// Byte offsets inside an identifier at which a word may be cut: 0, both ends of any run of `_`,
/// and any uppercase letter that begins a word (`fooBar` -> 3; `HTTPServer` -> 0, 4, where an
/// uppercase followed by lowercase ends an acronym). Always ends with the identifier's length.
///
/// Both ends of a `_` run: `open_read_only` -> `open_read_only_with_config` appends text starting
/// *at* the underscore.
pub(crate) fn identifier_word_starts(text: &str) -> Vec<usize> {
    let characters: Vec<(usize, char)> = text.char_indices().collect();
    let mut starts = vec![0usize];
    for (index, &(offset, character)) in characters.iter().enumerate() {
        if index == 0 {
            continue;
        }
        let previous = characters[index - 1].1;
        let next = characters.get(index + 1).map(|&(_, character)| character);
        let underscore_edge = (character == '_') != (previous == '_');
        let starts_a_word = character.is_uppercase()
            && (!previous.is_uppercase() || next.is_some_and(char::is_lowercase));
        if underscore_edge || starts_a_word {
            starts.push(offset);
        }
    }
    starts.push(text.len());
    starts.dedup();
    starts
}

/// The part of `text` that differs from `other`, widened outward to whole identifier words: a
/// highlight split inside a word is not something a reader would draw (`calculateArea` -> `area`
/// widens to the whole of both, `EVENT_NEW_FRAME` -> `SC_EVENT_NEW_FRAME` gives `SC_`).
///
/// An empty span (`start == end`) means every byte of this side survives into the other.
pub(crate) fn differing_affix(text: &str, other: &str) -> (usize, usize) {
    let (prefix, end) = raw_affix(text, other);
    let starts = identifier_word_starts(text);
    let start = starts
        .iter()
        .rev()
        .find(|&&start| start <= prefix)
        .copied()
        .unwrap_or(0);
    let end = starts
        .iter()
        .find(|&&start| start >= end)
        .copied()
        .unwrap_or(text.len());
    (start, end.max(start))
}

/// The bare common-prefix/common-suffix span, before any widening. The common suffix is taken
/// first, placing an ambiguous run as far left as it goes: `last_packet_timestamp` ->
/// `last_filtered_packet_timestamp` yields `_filtered`, which is what the corpus paints.
fn raw_affix(text: &str, other: &str) -> (usize, usize) {
    let suffix: usize = text
        .chars()
        .rev()
        .zip(other.chars().rev())
        .take_while(|(ours, theirs)| ours == theirs)
        .map(|(ours, _)| ours.len_utf8())
        .sum();
    let end = text.len() - suffix;
    let prefix = text[..end]
        .char_indices()
        .zip(other[..other.len() - suffix].char_indices())
        .take_while(|((_, ours), (_, theirs))| ours == theirs)
        .last()
        .map_or(0, |((offset, ours), _)| offset + ours.len_utf8());
    (prefix, end.max(prefix))
}

/// Every span a `Minimal` painting may legitimately mark on this side of a rename: the differing
/// words (the widened span) or the differing characters (the bare affix). The corpus holds both
/// readings, and words alone misfire on case fixes (`PRIU64` -> `PRIu64`). What is rejected is
/// marking the unchanged rest of the identifier.
fn minimal_affix_candidates(text: &str, other: &str) -> Vec<(usize, usize)> {
    let widened = differing_affix(text, other);
    let (start, end) = raw_affix(text, other);
    let mut candidates = vec![widened];
    if (start, end) != widened {
        candidates.push((start, end.max(start)));
    }
    candidates
}

/// A leaf that is an identifier: a named leaf whose text reads as one, and not a keyword. Judged
/// by text shape, not a per-grammar list of kinds.
fn is_identifier_leaf(leaf: Node, contents: &str) -> bool {
    if leaf.child_count() != 0 || !is_named_leaf(leaf, contents) {
        return false;
    }
    let Some(text) = contents.get(leaf.byte_range()) else {
        return false;
    };
    let mut characters = text.chars();
    characters
        .next()
        .is_some_and(|first| first.is_alphabetic() || first == '_' || first == '$')
        && characters
            .all(|character| character.is_alphanumeric() || character == '_' || character == '$')
}

/// **Invariant 16.** When the tree mapping pairs two identifiers that differ, `Minimal` paints
/// only the differing words or characters and `Full` paints the whole identifier on both sides.
///
/// The presets are two conventions (`text_painting_findings.md`, rule 1), and a rename is the edit
/// where they must differ. Only paintings named for a preset are checked: a lone painting is held
/// to both presets, whose halves of this rule contradict each other.
fn identifier_updates_are_painted_by_preset(
    painting: &str,
    painted: &PaintedLabels,
    context: &TreeContext,
    before: &Code,
    after: &Code,
) -> Vec<GroundTruthViolation> {
    let minimal = super::designates_preset(painting, "Minimal");
    let full = super::designates_preset(painting, "Full");
    if !minimal && !full {
        return Vec::new();
    }
    let mut violations = Vec::new();
    for leaf in &context.leaves[0] {
        let LeafStatus::Paired(partner) = context.status(*leaf, 0) else {
            continue;
        };
        if !is_identifier_leaf(*leaf, &before.contents)
            || !is_identifier_leaf(partner, &after.contents)
        {
            continue;
        }
        let (Some(ours), Some(theirs)) = (
            before.contents.get(leaf.byte_range()),
            after.contents.get(partner.byte_range()),
        ) else {
            continue;
        };
        if ours == theirs {
            continue;
        }
        for (side, node, text, other) in [
            (0usize, *leaf, ours, theirs),
            (1usize, partner, theirs, ours),
        ] {
            let contents = if side == 0 {
                &before.contents
            } else {
                &after.contents
            };
            let labels = &painted[side];
            if full {
                if whole_leaf_label(labels, node).is_some_and(|label| label.is_some()) {
                    continue;
                }
                violations.push(GroundTruthViolation::new(
                    16,
                    Some(painting),
                    format!(
                        "painting {painting:?} {} row {} does not paint the whole of {text:?}, \
                         which the mapping pairs with {other:?} - a Full painting marks a renamed \
                         identifier entire on both sides",
                        side_name(side),
                        row_of(contents, node.start_byte()),
                    ),
                    vec![ViolationSite {
                        side,
                        span: span_of_node(node),
                    }],
                ));
                continue;
            }
            let candidates = minimal_affix_candidates(text, other);
            let mut nearest: Option<(usize, usize, Vec<usize>, Vec<usize>)> = None;
            for (start, end) in candidates.iter().copied() {
                let painted_outside: Vec<usize> = (0..text.len())
                    .filter(|offset| !(start..end).contains(offset))
                    .filter(|offset| labels[node.start_byte() + offset].is_some())
                    .map(|offset| node.start_byte() + offset)
                    .collect();
                let unpainted_inside: Vec<usize> = (start..end)
                    .filter(|offset| labels[node.start_byte() + offset].is_none())
                    .map(|offset| node.start_byte() + offset)
                    .collect();
                if painted_outside.is_empty() && unpainted_inside.is_empty() {
                    nearest = None;
                    break;
                }
                let wrong = painted_outside.len() + unpainted_inside.len();
                if nearest
                    .as_ref()
                    .is_none_or(|(_, _, outside, inside)| wrong < outside.len() + inside.len())
                {
                    nearest = Some((start, end, painted_outside, unpainted_inside));
                }
            }
            // Any candidate matching exactly is agreement; the message names the closest one.
            let Some((start, end, painted_outside, unpainted_inside)) = nearest else {
                continue;
            };
            let wanted = if start == end {
                "nothing".to_string()
            } else {
                format!("{:?}", &text[start..end])
            };
            violations.push(GroundTruthViolation::new(
                16,
                Some(painting),
                format!(
                    "painting {painting:?} {} row {} paints {text:?} against {other:?} wrongly for \
                     a Minimal reading - the differing words are {wanted}, and everything else in \
                     the identifier should be left alone",
                    side_name(side),
                    row_of(contents, node.start_byte()),
                ),
                sites_from_offsets(
                    side,
                    contents,
                    &painted_outside
                        .into_iter()
                        .chain(unpainted_inside)
                        .collect::<Vec<usize>>(),
                ),
            ));
        }
    }
    violations
}

// ─────────────────────────────────────────────────────────────────────────────────────────────
// Invariant 17: a boolean that flipped is an edit to one token, not a deletion and an insertion
// ─────────────────────────────────────────────────────────────────────────────────────────────

/// `true` against `false`, either way round.
fn opposite_boolean(text: &str) -> Option<&'static str> {
    match text {
        "true" => Some("false"),
        "false" => Some("true"),
        _ => None,
    }
}

/// **Invariant 17.** A `true` that became a `false` in the same place is one token edited, not a
/// token deleted and another inserted - in the tree mapping and in every painting.
///
/// * **mapping** - a boolean leaf the mapping removes, whose partner subtree (under ancestors the
///   mapping pairs) contains the opposite literal also removed. Correspondence, not
///   co-occurrence: a `true` deleted in one method and a `false` added in another is fine.
/// * **painting** - a boolean pair the mapping pairs, painted `Delete` on one side and `Insert`
///   on the other. Invariant 10 cannot reach these, since the two sides differ.
fn boolean_flips_are_one_edit(
    paintings: &[(&str, PaintedLabels)],
    context: &TreeContext,
    before: &Code,
    after: &Code,
) -> Vec<GroundTruthViolation> {
    let mut violations = Vec::new();
    for leaf in &context.leaves[0] {
        let Some(text) = before.contents.get(leaf.byte_range()) else {
            continue;
        };
        let Some(opposite) = opposite_boolean(text) else {
            continue;
        };

        if let LeafStatus::Paired(partner) = context.status(*leaf, 0)
            && after.contents.get(partner.byte_range()) == Some(opposite)
        {
            for (name, painted) in paintings {
                let ours = whole_leaf_label(&painted[0], *leaf);
                let theirs = whole_leaf_label(&painted[1], partner);
                if ours == Some(Some(TextLabel::Delete)) && theirs == Some(Some(TextLabel::Insert))
                {
                    violations.push(GroundTruthViolation::new(
                        17,
                        Some(name),
                        format!(
                            "painting {name:?} deletes {text:?} on before row {} and inserts \
                             {opposite:?} on after row {}, which the mapping pairs as one edited \
                             token",
                            row_of(&before.contents, leaf.start_byte()),
                            row_of(&after.contents, partner.start_byte()),
                        ),
                        vec![
                            ViolationSite {
                                side: 0,
                                span: span_of_node(*leaf),
                            },
                            ViolationSite {
                                side: 1,
                                span: span_of_node(partner),
                            },
                        ],
                    ));
                }
            }
            continue;
        }

        if !matches!(context.status(*leaf, 0), LeafStatus::Removed) {
            continue;
        }
        // The nearest ancestor the mapping pairs: the flip has to have happened *here*.
        let mut ancestor = Some(*leaf);
        let partner_subtree = loop {
            let Some(node) = ancestor else { break None };
            if let Some(partner) = context
                .caches
                .before_match
                .get(&node.id())
                .and_then(|id| context.ids[1].get(id))
            {
                break Some(*partner);
            }
            ancestor = node.parent();
        };
        let Some(partner_subtree) = partner_subtree else {
            continue;
        };
        let Some(twin) = context.leaves[1]
            .iter()
            .filter(|candidate| {
                partner_subtree.start_byte() <= candidate.start_byte()
                    && candidate.end_byte() <= partner_subtree.end_byte()
            })
            .find(|candidate| {
                after.contents.get(candidate.byte_range()) == Some(opposite)
                    && matches!(context.status(**candidate, 1), LeafStatus::Removed)
            })
        else {
            continue;
        };
        violations.push(GroundTruthViolation::new(
            17,
            None,
            format!(
                "mapping removes {text:?} on before row {} and adds {opposite:?} on after row {} \
                 inside the subtree it pairs with - one flipped literal, which an Update entry on \
                 the two says and a delete plus an insert does not",
                row_of(&before.contents, leaf.start_byte()),
                row_of(&after.contents, twin.start_byte()),
            ),
            vec![
                ViolationSite {
                    side: 0,
                    span: span_of_node(*leaf),
                },
                ViolationSite {
                    side: 1,
                    span: span_of_node(*twin),
                },
            ],
        ));
    }
    violations
}

// ─────────────────────────────────────────────────────────────────────────────────────────────
// Invariant 19: an operator, a boolean or an access modifier is painted whole
// ─────────────────────────────────────────────────────────────────────────────────────────────

/// **Invariant 19.** Every byte of a token in [`WHOLE_TOKENS`] carries the same highlighting, in
/// every painting, on both sides. Each is one symbol to a reader: `<=` becoming `<` is a different
/// comparison, not a surviving `<`; `private` becoming `protected` keeps no `pr`. The presets may
/// disagree about *whether* such a token is painted, never about painting part of one. The list
/// is the renderer's own, which follows the same rule.
fn tokens_are_painted_whole(
    painting: &str,
    painted: &PaintedLabels,
    context: &TreeContext,
    before: &Code,
    after: &Code,
) -> Vec<GroundTruthViolation> {
    let mut violations = Vec::new();
    for (side, code) in [(0usize, before), (1usize, after)] {
        for leaf in &context.leaves[side] {
            let Some(text) = code.contents.get(leaf.byte_range()) else {
                continue;
            };
            if !WHOLE_TOKENS.contains(&text) || whole_leaf_label(&painted[side], *leaf).is_some() {
                continue;
            }
            violations.push(GroundTruthViolation::new(
                19,
                Some(painting),
                format!(
                    "painting '{painting}' paints only part of `{text}` on {} row {}",
                    side_name(side),
                    row_of(&code.contents, leaf.start_byte()),
                ),
                vec![ViolationSite {
                    side,
                    span: span_of_node(*leaf),
                }],
            ));
        }
    }
    violations
}

// ─────────────────────────────────────────────────────────────────────────────────────────────
// The assertions the per-fixture tests call
// ─────────────────────────────────────────────────────────────────────────────────────────────

/// Asserts `name`'s ground truth contradicts itself in no way at all.
pub fn assert_ground_truth_invariants(name: &str) -> Result<()> {
    assert_ground_truth_invariants_with_known_violations(name, 0)
}

/// [`assert_ground_truth_invariants`] for a fixture with `expected` known violations.
///
/// **Exact, unlike the mapping and painting clamps**: those bound a distance, while this counts
/// specific contradictions, each described above the call. An over-estimate would stop checking
/// the moment one is repaired; the failure names the number to write instead.
pub fn assert_ground_truth_invariants_with_known_violations(
    name: &str,
    expected: usize,
) -> Result<()> {
    let violations = ground_truth_invariant_violations(name)?;
    let listed = violation_messages(&violations).join("\n  ");
    if violations.len() == expected {
        return Ok(());
    }
    if violations.len() < expected {
        anyhow::bail!(
            "'{name}' now breaks {} of its own ground-truth invariants, not the {expected} \
             recorded here - if that is a repair, record {} and update the note above this call \
             to describe what is left:\n  {listed}",
            violations.len(),
            violations.len(),
        );
    }
    anyhow::bail!(
        "'{name}' breaks {} of its own ground-truth invariants, more than the {expected} recorded \
         here:\n  {listed}",
        violations.len(),
    )
}

/// Each violation's message, numbered by the rule it comes from - what a failure prints.
pub fn violation_messages(violations: &[GroundTruthViolation]) -> Vec<String> {
    violations.iter().map(ToString::to_string).collect()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::code::{Code, Language};
    use crate::test::helper::human_mapping::{
        HumanMapping, HumanMappingEntry, HumanOperation, HumanTextEntry, HumanTextMapping,
        HumanTextOperation,
    };
    use crate::test::helper::path_for_node;

    #[test]
    fn identifier_words_split_on_case_and_underscores() {
        assert_eq!(identifier_word_starts("fooBar"), vec![0, 3, 6]);
        assert_eq!(
            identifier_word_starts("SC_EVENT_NEW_FRAME"),
            vec![0, 2, 3, 8, 9, 12, 13, 18]
        );
        // An acronym is one word, and hands off to the next at the capital before a lowercase.
        assert_eq!(identifier_word_starts("XMLHttpRequest"), vec![0, 3, 7, 14]);
        assert_eq!(identifier_word_starts("lowercase"), vec![0, 9]);
        assert_eq!(identifier_word_starts(""), vec![0]);
    }

    #[test]
    fn a_pure_prefix_insertion_paints_only_the_new_words() {
        // The shape `c-genymobile-scrcpy-rename-defines` renames five times over.
        assert_eq!(
            differing_affix("SC_EVENT_NEW_FRAME", "EVENT_NEW_FRAME"),
            (0, 3)
        );
        // An ambiguous run goes as far left as it will go: `_filtered` after `last`, not
        // `filtered_` after `last_`, as rust-gyulyvgc-sniffnet-rename-one-identifier paints it.
        assert_eq!(
            differing_affix("last_filtered_packet_timestamp", "last_packet_timestamp"),
            (4, 13)
        );
        let (start, end) =
            differing_affix("last_packet_timestamp", "last_filtered_packet_timestamp");
        assert_eq!(
            start, end,
            "the side that only lost it has nothing to paint"
        );
        // The appended text starts *at* the underscore, and the highlight stays that tight
        // rather than widening back to the previous word.
        assert_eq!(
            differing_affix("open_read_only_with_config", "open_read_only"),
            (14, 26)
        );
        // ... and nothing at all on the side that only lost it.
        let (start, end) = differing_affix("EVENT_NEW_FRAME", "SC_EVENT_NEW_FRAME");
        assert_eq!(start, end, "the unchanged side has no differing words");
    }

    #[test]
    fn a_single_word_identifier_accepts_the_bare_affix_or_the_whole_token() {
        // `align` -> `halign` and `v` -> `value` have nothing to orient on, so both readings pass.
        let candidates = minimal_affix_candidates("halign", "align");
        assert!(candidates.contains(&(0, 1)), "the added `h` alone");
        assert!(candidates.contains(&(0, 6)), "or the whole token");
        let candidates = minimal_affix_candidates("value", "v");
        assert!(candidates.contains(&(1, 5)));
        assert!(candidates.contains(&(0, 5)));
        // With a boundary to orient on, the word and the characters both pass.
        assert_eq!(
            minimal_affix_candidates("getDeclaredConstructors", "getDeclaredConstructor"),
            vec![(11, 23), (22, 23)]
        );
    }

    #[test]
    fn a_shared_run_inside_a_word_does_not_split_it() {
        // The bare shared suffix "rea" falls inside a word, so widening takes both whole.
        assert_eq!(differing_affix("calculateArea", "area"), (0, 13));
        assert_eq!(differing_affix("area", "calculateArea"), (0, 4));
        // A suffix added at a word boundary stays narrow.
        assert_eq!(differing_affix("ReplaceAll", "Replace"), (7, 10));
    }

    fn rust(source: &str) -> Code {
        Code::from_string(source, &Language::Rust)
    }

    fn span(
        start_row: usize,
        start_column: usize,
        end_row: usize,
        end_column: usize,
    ) -> HumanTextSpan {
        HumanTextSpan {
            start_row,
            start_column,
            end_row,
            end_column,
        }
    }

    /// A mapping carrying one named painting and nothing else - enough for the two painting
    /// invariants, which never look at `entries`.
    fn painted(paintings: Vec<(&str, Vec<HumanTextEntry>)>) -> HumanMapping {
        HumanMapping {
            text_mappings: paintings
                .into_iter()
                .map(|(name, entries)| NamedTextMapping {
                    name: name.to_string(),
                    mapping: HumanTextMapping { entries },
                })
                .collect(),
            ..Default::default()
        }
    }

    /// A `Delete` of `count` bytes from column `at` of the first row.
    fn deleted(at: usize, count: usize) -> HumanTextEntry {
        HumanTextEntry {
            operation: HumanTextOperation::Delete,
            before: vec![span(0, at, 0, at + count)],
            after: Vec::new(),
        }
    }

    fn violations(mapping: &HumanMapping, before: &Code, after: &Code) -> Vec<String> {
        ground_truth_invariant_violations_for(mapping, before, after)
            .expect("checks run")
            .into_iter()
            .map(|violation| violation.message)
            .collect()
    }

    // ── Invariant 8 ─────────────────────────────────────────────────────────────────────────

    /// A `Match` over the same columns of both sides - byte-identical, so it resolves to `Move`.
    fn moved(at: usize, count: usize) -> HumanTextEntry {
        HumanTextEntry {
            operation: HumanTextOperation::Match,
            before: vec![span(0, at, 0, at + count)],
            after: vec![span(0, at, 0, at + count)],
        }
    }

    fn survival_violations(mapping: &HumanMapping, before: &Code, after: &Code) -> Vec<String> {
        violations(mapping, before, after)
            .into_iter()
            .filter(|v| v.contains("survive under one preset"))
            .collect()
    }

    #[test]
    fn a_byte_moved_under_one_preset_and_deleted_under_the_other_is_reported() {
        let source = rust("let value = 1;\n");
        let mapping = painted(vec![
            ("Minimal", vec![moved(4, 5)]),
            ("Full", vec![deleted(4, 5)]),
        ]);

        let reported = survival_violations(&mapping, &source, &source);
        assert_eq!(reported.len(), 1, "got {reported:?}");
        assert!(reported[0].contains("5 byte(s)"), "got {reported:?}");
    }

    /// The pair the presets are *expected* to differ on: `Full` widening a `Move` into the `Update`
    /// that contains it. Both readings agree the code survived, so there is nothing to report.
    #[test]
    fn a_move_widened_into_an_update_is_not_a_contradiction() {
        let before = rust("let value = 1;\n");
        let after = rust("let value = 2;\n");
        let updated = HumanTextEntry {
            operation: HumanTextOperation::Match,
            before: vec![span(0, 4, 0, 13)],
            after: vec![span(0, 4, 0, 13)],
        };
        let mapping = painted(vec![
            ("Minimal", vec![moved(4, 5)]),
            ("Full", vec![updated]),
        ]);

        assert!(
            survival_violations(&mapping, &before, &after).is_empty(),
            "a widening changes the colour, not whether the code is there"
        );
    }

    /// Alternatives are a disjunction: one `Full` reading contradicting a `Minimal` says nothing
    /// while another agrees with it.
    #[test]
    fn a_minimal_consistent_with_some_full_alternative_is_not_reported() {
        let source = rust("let value = 1;\n");
        let mapping = painted(vec![
            ("Minimal", vec![moved(4, 5)]),
            ("Full (left)", vec![deleted(4, 5)]),
            ("Full (right)", vec![moved(4, 5)]),
        ]);

        assert!(
            survival_violations(&mapping, &source, &source).is_empty(),
            "'Full (right)' agrees, which is all a disjunction needs"
        );
    }

    // ── Invariant 7 ─────────────────────────────────────────────────────────────────────────

    #[test]
    fn two_ranges_claiming_the_same_byte_are_reported() {
        let before = rust("let value = 1;\n");
        let mapping = painted(vec![(
            "Only one solution",
            vec![deleted(4, 5), deleted(8, 3)],
        )]);

        let all = violations(&mapping, &before, &before);
        let reported: Vec<&String> = all
            .iter()
            .filter(|v| v.contains("already claimed"))
            .collect();
        assert_eq!(reported.len(), 1, "got {reported:?}");
        assert!(reported[0].contains("range 1"), "got {reported:?}");
    }

    /// A range ending at column 0 of the next row swallows the break, and nothing paints a line
    /// terminator.
    #[test]
    fn two_ranges_meeting_at_a_line_break_do_not_overlap() {
        let before = rust("let x = 1;\nlet y = 2;\n");
        let first = HumanTextEntry {
            operation: HumanTextOperation::Delete,
            before: vec![span(0, 0, 1, 0)],
            after: Vec::new(),
        };
        let second = HumanTextEntry {
            operation: HumanTextOperation::Delete,
            before: vec![span(1, 0, 1, 10)],
            after: Vec::new(),
        };
        let mapping = painted(vec![("Only one solution", vec![first, second])]);

        assert!(
            !violations(&mapping, &before, &before)
                .iter()
                .any(|v| v.contains("already claimed")),
            "sharing only the newline is not an overlap"
        );
    }

    /// A Windows break is two bytes, and neither is painted.
    #[test]
    fn a_crlf_break_between_two_ranges_is_not_an_overlap() {
        let before = rust("let x = 1;\r\nlet y = 2;\r\n");
        let first = HumanTextEntry {
            operation: HumanTextOperation::Delete,
            before: vec![span(0, 0, 1, 0)],
            after: Vec::new(),
        };
        let second = HumanTextEntry {
            operation: HumanTextOperation::Delete,
            before: vec![span(1, 0, 1, 10)],
            after: Vec::new(),
        };
        let mapping = painted(vec![("Only one solution", vec![first, second])]);

        assert!(
            !violations(&mapping, &before, &before)
                .iter()
                .any(|v| v.contains("already claimed")),
            "the CR belongs to the terminator, not to either range"
        );
    }

    /// Two paintings are alternatives, not conjuncts, so one may claim a byte the other claims.
    #[test]
    fn two_paintings_may_claim_the_same_byte_as_each_other() {
        let before = rust("let value = 1;\n");
        let mapping = painted(vec![
            ("Minimal", vec![deleted(4, 5)]),
            ("Full", vec![deleted(0, 9)]),
        ]);

        assert!(
            !violations(&mapping, &before, &before)
                .iter()
                .any(|v| v.contains("already claimed")),
            "the rule is within one painting, not across them"
        );
    }

    // ── Invariant 1 ─────────────────────────────────────────────────────────────────────────

    #[test]
    fn a_painted_run_that_ends_on_a_trailing_space_is_reported() {
        let before = rust("let x = 1;  \n");
        let after = rust("\n");
        // `1;  ` - one column past the semicolon, into the trailing spaces.
        let mapping = painted(vec![("Only one solution", vec![deleted(8, 4)])]);

        let found = violations(&mapping, &before, &after);
        assert_eq!(found.len(), 1, "got {found:#?}");
        assert!(found[0].contains("not on a visible character"), "{found:?}");
    }

    #[test]
    fn a_painted_run_that_ends_on_the_last_visible_character_is_accepted() {
        let before = rust("let x = 1;  \n");
        let after = rust("\n");
        let mapping = painted(vec![("Only one solution", vec![deleted(8, 2)])]);

        assert!(violations(&mapping, &before, &after).is_empty());
    }

    /// A run stopping on a space with visible text still to come on the row is an ordinary edit
    /// (go-gin-gonic-gin-whitespace-in-comment).
    #[test]
    fn a_painted_run_that_ends_on_a_mid_row_space_is_accepted() {
        let before = rust("let x = 1;  // a  b\n");
        let after = rust("\n");
        // `a ` at columns 15..17 ends on the space at 16, with `b` still to come. It holds a
        // visible character, so the all-whitespace exemption does not mask the mid-row check.
        let mapping = painted(vec![("Only one solution", vec![deleted(15, 2)])]);

        assert!(
            violations(&mapping, &before, &after).is_empty(),
            "a mid-row space is not trailing whitespace"
        );
    }

    /// A run with no visible character is exempt, as a blank row is (a commit stripping trailing
    /// spaces).
    #[test]
    fn a_painted_run_that_is_entirely_whitespace_is_exempt() {
        let before = rust("let x = 1;  \n");
        let after = rust("let x = 1;\n");
        // Just the two trailing spaces: trailing, but with nothing visible inside the run.
        let mapping = painted(vec![("Only one solution", vec![deleted(10, 2)])]);

        assert!(
            violations(&mapping, &before, &after).is_empty(),
            "a run that is all whitespace has no visible character it could end on"
        );
    }

    #[test]
    fn a_row_with_nothing_visible_on_it_is_exempt() {
        // The painted row is all whitespace, so nothing on it could legally end a run.
        let before = rust("fn f() {\n    \n}\n");
        let after = rust("fn f() {\n}\n");
        let mapping = painted(vec![(
            "Only one solution",
            vec![HumanTextEntry {
                operation: HumanTextOperation::Delete,
                before: vec![span(1, 0, 1, 4)],
                after: Vec::new(),
            }],
        )]);

        assert!(violations(&mapping, &before, &after).is_empty());
    }

    // ── Invariant 2 ─────────────────────────────────────────────────────────────────────────

    #[test]
    fn a_minimal_painting_reaching_past_its_full_counterpart_is_reported() {
        let before = rust("let x = 1;\n");
        let after = rust("let x = 2;\n");
        let update = |from: usize, to: usize| HumanTextEntry {
            operation: HumanTextOperation::Match,
            before: vec![span(0, from, 0, to)],
            after: vec![span(0, from, 0, to)],
        };
        let mapping = painted(vec![
            ("Minimal", vec![update(4, 9)]),
            ("Full", vec![update(8, 9)]),
        ]);

        let found = violations(&mapping, &before, &after);
        assert_eq!(found.len(), 1, "got {found:#?}");
        assert!(found[0].contains("leaves unpainted"), "{found:?}");
    }

    #[test]
    fn a_full_painting_wider_than_its_minimal_counterpart_is_the_expected_shape() {
        let before = rust("let x = 1;\n");
        let after = rust("let x = 2;\n");
        let update = |from: usize, to: usize| HumanTextEntry {
            operation: HumanTextOperation::Match,
            before: vec![span(0, from, 0, to)],
            after: vec![span(0, from, 0, to)],
        };
        let mapping = painted(vec![
            ("Minimal", vec![update(8, 9)]),
            ("Full", vec![update(4, 9)]),
        ]);

        assert!(violations(&mapping, &before, &after).is_empty());
    }

    #[test]
    fn a_single_painting_answers_for_both_presets_so_there_is_nothing_to_compare() {
        let before = rust("let x = 1;\n");
        let after = rust("let x = 2;\n");
        let mapping = painted(vec![(
            "Only one solution",
            vec![HumanTextEntry {
                operation: HumanTextOperation::Match,
                before: vec![span(0, 8, 0, 9)],
                after: vec![span(0, 8, 0, 9)],
            }],
        )]);

        assert!(violations(&mapping, &before, &after).is_empty());
    }

    // ── Invariant 3, the painted half ───────────────────────────────────────────────────────

    #[test]
    fn a_painting_that_marks_one_half_of_a_pair_is_not_a_violation() {
        // Asked of the tree mapping alone: a painting may say the `{` went and the `}` stayed.
        let before = rust("fn f() { g(); }\n");
        let after = rust("\n");
        let mapping = painted(vec![("Only one solution", vec![deleted(7, 1)])]);

        assert!(violations(&mapping, &before, &after).is_empty());
    }

    #[test]
    fn only_a_leaf_whose_kind_is_its_own_text_is_a_delimiter() {
        // The second `(` is a `string_content` leaf that merely reads `(`, not a delimiter.
        let code = rust("fn f() { g(\"(\"); }\n");
        let pairs = delimiter_pairs(code.ast.as_ref().unwrap().root_node(), &code.contents);

        let mut kinds: Vec<(&str, usize)> = pairs
            .iter()
            .map(|(open, _)| (open.kind(), open.start_position().column))
            .collect();
        // Reported in stack order; only the set of pairs is the contract.
        kinds.sort_by_key(|(_, column)| *column);
        assert_eq!(
            kinds,
            vec![("(", 4), ("{", 7), ("(", 10)],
            "the `(` at column 12 is inside a string literal and must not be paired"
        );
    }

    // ── Invariant 9 ─────────────────────────────────────────────────────────────────────────

    fn survival_across_records(mapping: &HumanMapping, before: &Code, after: &Code) -> Vec<String> {
        violations(mapping, before, after)
            .into_iter()
            .filter(|v| v.contains("the tree mapping leaves unmatched"))
            .collect()
    }

    /// Label vectors rather than a built mapping: a synthetic pair contrived to make `TextDiff`
    /// emit a `Delete` would test the renderer instead of the rule.
    fn labels(before_len: usize, after_len: usize) -> PaintedLabels {
        [vec![None; before_len], vec![None; after_len]]
    }

    /// An `unmatched_bytes` mask saying every byte is unmatched - the gate held open.
    fn all_unmatched(before_len: usize, after_len: usize) -> [Vec<bool>; 2] {
        [vec![true; before_len], vec![true; after_len]]
    }

    #[test]
    fn a_painted_move_over_a_node_the_mapping_deletes_is_reported() {
        let source = rust("let value = 1;\n");
        let mut painted = labels(source.contents.len(), source.contents.len());
        let mut tree = labels(source.contents.len(), source.contents.len());
        for offset in 4..9 {
            painted[0][offset] = Some(TextLabel::Move);
            tree[0][offset] = Some(TextLabel::Delete);
        }

        let unmatched = all_unmatched(source.contents.len(), source.contents.len());
        let reported =
            move_against_unmatched("Minimal", &painted, &tree, &unmatched, &source, &source);
        assert_eq!(reported.len(), 1, "got {reported:#?}");
        assert!(
            reported[0].message.contains("5 byte(s) Move"),
            "got {reported:#?}"
        );
        assert!(reported[0].message.contains("Delete"), "got {reported:#?}");
        assert_eq!(reported[0].invariant, 9);
        // The five bytes are contiguous, so they collapse to one site rather than five.
        assert_eq!(
            reported[0].sites,
            vec![site_on_row(0, 0, 4, 9)],
            "got {reported:#?}"
        );
    }

    #[test]
    fn a_painted_move_over_a_node_the_mapping_inserts_is_reported() {
        let source = rust("let value = 1;\n");
        let mut painted = labels(source.contents.len(), source.contents.len());
        let mut tree = labels(source.contents.len(), source.contents.len());
        painted[1][4] = Some(TextLabel::Move);
        tree[1][4] = Some(TextLabel::Insert);

        let unmatched = all_unmatched(source.contents.len(), source.contents.len());
        let reported =
            move_against_unmatched("Full", &painted, &tree, &unmatched, &source, &source);
        assert_eq!(reported.len(), 1, "got {reported:#?}");
        assert!(reported[0].message.contains("after"), "got {reported:#?}");
        assert_eq!(reported[0].sites, vec![site_on_row(1, 0, 4, 5)]);
    }

    /// The renderer says these bytes were deleted, but they sit in a node the mapping *matched*: a
    /// character edited out of a surviving leaf (`rust-rust-lang-rust-update-comment`).
    #[test]
    fn a_painted_move_the_renderer_deletes_from_inside_a_matched_node_is_not_reported() {
        let source = rust("let value = 1;\n");
        let mut painted = labels(source.contents.len(), source.contents.len());
        let mut tree = labels(source.contents.len(), source.contents.len());
        for offset in 4..9 {
            painted[0][offset] = Some(TextLabel::Move);
            tree[0][offset] = Some(TextLabel::Delete);
        }
        // Everything else is as in `a_painted_move_over_a_node_the_mapping_deletes_is_reported`,
        // which reports it; the mask is the only difference.
        let unmatched = [
            vec![false; source.contents.len()],
            vec![false; source.contents.len()],
        ];
        assert!(
            move_against_unmatched("Minimal", &painted, &tree, &unmatched, &source, &source)
                .is_empty(),
            "a tree-side Delete inside a matched node is the renderer, not a missing counterpart"
        );
    }

    /// The smallest node containing a byte decides: a matched node inside a deleted subtree reads
    /// as matched, while whitespace between that subtree's children keeps the deleted answer.
    #[test]
    fn unmatched_bytes_lets_a_matched_node_override_the_subtree_deleted_around_it() {
        let before = rust("fn f() { g(); }\n");
        let root = before.ast.as_ref().unwrap().root_node();
        let find = |text: &str| {
            let mut stack = vec![root];
            while let Some(node) = stack.pop() {
                if node.child_count() == 0 && &before.contents[node.byte_range()] == text {
                    return node;
                }
                let mut cursor = node.walk();
                for child in node.children(&mut cursor) {
                    stack.push(child);
                }
            }
            panic!("no leaf reads {text:?}");
        };
        let block = find("{").parent().expect("the brace's block");
        assert_eq!(block.kind(), "block");
        let call = find("g");

        let mut caches = Caches::default();
        // The whole block deleted, children included - so everything under it inherits the mark -
        // and one leaf inside it matched anyway, which is the case being drawn.
        caches.before_removed.insert(block.id(), true);
        caches.before_match.insert(call.id(), call.id());

        let mask = unmatched_bytes(root, before.contents.len(), 0, &[], &caches);
        assert!(
            mask[block.start_byte()],
            "the deleted block's own brace inherits the mark"
        );
        assert!(
            mask[block.start_byte() + 1],
            "and so does the space after it, which no node of its own covers"
        );
        assert!(
            !mask[call.start_byte()],
            "but the leaf the mapping matched does not"
        );
        assert!(
            !mask[0],
            "and nothing outside the block is touched - `fn` is unmarked, which is not unmatched"
        );
    }

    /// Not reported: a tree-side `Move` comes from `TextDiff::from`'s column-shift heuristic, so
    /// against a painted `Delete` it measures the renderer.
    #[test]
    fn a_painted_delete_over_a_node_the_renderer_calls_moved_is_not_reported() {
        let source = rust("let value = 1;\n");
        let mut painted = labels(source.contents.len(), source.contents.len());
        let mut tree = labels(source.contents.len(), source.contents.len());
        painted[0][4] = Some(TextLabel::Delete);
        tree[0][4] = Some(TextLabel::Move);

        assert!(
            move_against_unmatched(
                "Minimal",
                &painted,
                &tree,
                &all_unmatched(source.contents.len(), source.contents.len()),
                &source,
                &source
            )
            .is_empty(),
            "only a painted Move against an unmatched node is a contradiction"
        );
    }

    /// The two records differing about *granularity* is the ordinary case, not a contradiction.
    #[test]
    fn a_painted_move_the_mapping_calls_updated_is_not_reported() {
        let source = rust("let value = 1;\n");
        let mut painted = labels(source.contents.len(), source.contents.len());
        let mut tree = labels(source.contents.len(), source.contents.len());
        painted[0][4] = Some(TextLabel::Move);
        tree[0][4] = Some(TextLabel::Update);

        assert!(
            move_against_unmatched(
                "Minimal",
                &painted,
                &tree,
                &all_unmatched(source.contents.len(), source.contents.len()),
                &source,
                &source
            )
            .is_empty(),
            "an Update says the node survived too"
        );
    }

    /// A fixture with one ground truth and not the other has nothing to compare.
    #[test]
    fn a_fixture_with_no_tree_mapping_is_skipped() {
        let source = rust("fn f() { g(); }\n");
        let mapping = painted(vec![(
            "Only one solution",
            vec![HumanTextEntry {
                operation: HumanTextOperation::Match,
                before: vec![span(0, 9, 0, 10)],
                after: vec![span(0, 9, 0, 10)],
            }],
        )]);

        assert!(survival_across_records(&mapping, &source, &source).is_empty());
    }

    // ── Invariant 3, the mapped half ────────────────────────────────────────────────────────

    /// Every before node paired with the identically-positioned after node, except the nodes whose
    /// text is `mark_deleted`, which are recorded as deletions instead.
    fn mapping_with_deleted_text(before: &Code, after: &Code, mark_deleted: &str) -> HumanMapping {
        let before_root = before.ast.as_ref().unwrap().root_node();
        let after_root = after.ast.as_ref().unwrap().root_node();
        let mut entries = Vec::new();
        let mut stack = vec![(before_root, after_root)];
        while let Some((b, a)) = stack.pop() {
            let (before_path, after_path) = (path_for_node(b), path_for_node(a));
            if &before.contents[b.byte_range()] == mark_deleted {
                entries.push(HumanMappingEntry {
                    operation: HumanOperation::Delete,
                    before_path: Some(before_path),
                    after_path: None,
                });
            } else {
                entries.push(HumanMappingEntry {
                    operation: HumanOperation::Identical,
                    before_path: Some(before_path),
                    after_path: Some(after_path),
                });
            }
            for index in 0..b.child_count().min(a.child_count()) {
                stack.push((b.child(index).unwrap(), a.child(index).unwrap()));
            }
        }
        HumanMapping {
            entries,
            ..Default::default()
        }
    }

    #[test]
    fn a_deleted_paren_whose_partner_is_matched_is_reported() {
        let before = rust("fn f() { g(); }\n");
        let after = before.clone();
        let mut after = rust(&after.contents);
        after.ensure_parsed().unwrap();
        let mapping = mapping_with_deleted_text(&before, &after, "(");

        let found = violations(&mapping, &before, &after);
        assert!(
            found
                .iter()
                .any(|v| v.contains("as deleted but its matching")),
            "got {found:#?}"
        );
    }

    /// Every leaf in `code` whose text is exactly `text` and whose parent is `parent`, in document
    /// order. The parent is what keeps `fn f()`'s own parentheses out of a group about a call's.
    fn leaves_reading<'a>(code: &'a Code, text: &str, parent: &str) -> Vec<Node<'a>> {
        let root = code.ast.as_ref().unwrap().root_node();
        let mut found = Vec::new();
        let mut stack = vec![root];
        while let Some(node) = stack.pop() {
            if node.child_count() == 0
                && &code.contents[node.byte_range()] == text
                && node
                    .parent()
                    .is_some_and(|node_parent| node_parent.kind() == parent)
            {
                found.push(node);
            }
            let mut cursor = node.walk();
            for child in node.children(&mut cursor) {
                stack.push(child);
            }
        }
        found.sort_by_key(Node::start_byte);
        found
    }

    #[test]
    fn a_delimiter_whose_group_leaves_it_free_contradicts_nothing() {
        // One call becomes two nested calls: 1:2 groups for `(` and for `)`. Pairing outer with
        // outer is consistent, but `representative_entries` sorts by start byte and takes the
        // outer opener with the *inner* closer, splitting both pairs.
        let before = rust("fn f() { g(x); }\n");
        let after = rust("fn f() { g(h(x)); }\n");

        let mut groups = Vec::new();
        for delimiter in ["(", ")"] {
            groups.push(super::super::MultiMapGroup {
                before_paths: leaves_reading(&before, delimiter, "arguments")
                    .iter()
                    .map(|node| path_for_node(*node))
                    .collect(),
                after_paths: leaves_reading(&after, delimiter, "arguments")
                    .iter()
                    .map(|node| path_for_node(*node))
                    .collect(),
                operation: HumanOperation::Identical,
                with_children: false,
                pairing: super::super::GroupPairing::AnyOneToOne,
            });
        }
        assert_eq!(groups[0].before_paths.len(), 1);
        assert_eq!(
            groups[0].after_paths.len(),
            2,
            "the after side nests two calls"
        );

        let mapping = HumanMapping {
            groups,
            ..Default::default()
        };

        assert!(
            violations(&mapping, &before, &after).is_empty(),
            "a member the group could leave over states nothing to contradict"
        );
    }

    #[test]
    fn an_all_to_all_group_member_is_a_claim_under_every_reading() {
        // One statement duplicated under an all-to-all group: a leaf inside either copy has a
        // twin, so nothing is undecided and nothing is objected to.
        let before = rust("fn f() { g(); }\n");
        let after = rust("fn f() { g(); g(); }\n");
        let before_root = before.ast.as_ref().unwrap().root_node();
        let after_root = after.ast.as_ref().unwrap().root_node();
        fn statements<'t>(root: Node<'t>) -> Vec<Node<'t>> {
            let body = root
                .child(0)
                .and_then(|f| f.child_by_field_name("body"))
                .expect("fn f has a body");
            let mut cursor = body.walk();
            body.named_children(&mut cursor).collect()
        }
        let before_statements = statements(before_root);
        let after_statements = statements(after_root);
        assert_eq!((before_statements.len(), after_statements.len()), (1, 2));

        let group = |pairing| super::super::MultiMapGroup {
            before_paths: before_statements
                .iter()
                .map(|n| path_for_node(*n))
                .collect(),
            after_paths: after_statements.iter().map(|n| path_for_node(*n)).collect(),
            operation: HumanOperation::Identical,
            with_children: true,
            pairing,
        };
        fn leaf_of<'t>(statement: Node<'t>) -> Node<'t> {
            let mut node = statement;
            while let Some(first) = node.child(0) {
                node = first;
            }
            node
        }

        let open = HumanMapping {
            groups: vec![group(super::super::GroupPairing::AnyOneToOne)],
            ..Default::default()
        };
        let context = TreeContext::build(&open, before_root, after_root);
        let undecided = (0..2)
            .filter(|i| {
                matches!(
                    context.status(leaf_of(after_statements[*i]), 1),
                    LeafStatus::Undecided
                )
            })
            .count();
        assert_eq!(
            undecided, 1,
            "one copy is the leftover the group leaves open"
        );

        let all = HumanMapping {
            groups: vec![group(super::super::GroupPairing::AllToAll)],
            ..Default::default()
        };
        let context = TreeContext::build(&all, before_root, after_root);
        for statement in &after_statements {
            assert!(
                matches!(context.status(leaf_of(*statement), 1), LeafStatus::Same(_)),
                "every copy's leaf has a twin in the original"
            );
        }
        assert!(
            violations(&all, &before, &after).is_empty(),
            "{:#?}",
            violations(&all, &before, &after)
        );
    }

    #[test]
    fn a_delimiter_its_group_pins_is_still_checked() {
        // A 1:1 group matches its only member under every pairing it admits, so "matched" here is
        // a claim the group really makes - and an entry deleting the partner contradicts it.
        let before = rust("fn f() { g(); }\n");
        let after = rust("fn f() { g(); }\n");

        let open = leaves_reading(&before, "(", "arguments");
        let after_open = leaves_reading(&after, "(", "arguments");
        let close = leaves_reading(&before, ")", "arguments");
        let mapping = HumanMapping {
            entries: vec![HumanMappingEntry {
                operation: HumanOperation::Delete,
                before_path: Some(path_for_node(close[0])),
                after_path: None,
            }],
            groups: vec![super::super::MultiMapGroup {
                before_paths: vec![path_for_node(open[0])],
                after_paths: vec![path_for_node(after_open[0])],
                operation: HumanOperation::Identical,
                with_children: false,
                pairing: super::super::GroupPairing::AnyOneToOne,
            }],
            ..Default::default()
        };

        let found = violations(&mapping, &before, &after);
        assert!(
            found
                .iter()
                .any(|v| v.contains("as matched but its matching")),
            "got {found:#?}"
        );
    }

    #[test]
    fn a_mapping_that_says_nothing_about_a_delimiter_contradicts_nothing() {
        // No entries at all: every node is `Unmarked`, so no pair has two claims to compare.
        let before = rust("fn f() { g(); }\n");
        let after = rust("fn f() { g(); }\n");

        assert!(violations(&HumanMapping::default(), &before, &after).is_empty());
    }

    #[test]
    fn a_pair_with_a_parse_error_between_its_halves_is_skipped() {
        // tree-sitter recovers from the stray `@` by inventing structure; whatever braces it pairs
        // across that region are not pairs anybody wrote.
        let before = rust("fn f() { @ }\n");
        let after = rust("fn f() { @ }\n");
        assert!(
            !error_ranges(before.ast.as_ref().unwrap().root_node()).is_empty(),
            "this test is only meaningful if the source really does fail to parse"
        );
        let mapping = mapping_with_deleted_text(&before, &after, "{");

        assert!(
            violations(&mapping, &before, &after).is_empty(),
            "a pair straddling an ERROR must not be checked"
        );
    }

    // ── The assertion wrappers ──────────────────────────────────────────────────────────────

    #[test]
    fn the_delimiter_table_pairs_every_opener_with_at_least_one_closer() {
        for (open, closers) in DELIMITERS {
            assert!(!closers.is_empty(), "{open} has no closer");
            assert!(closers.iter().all(|closer| is_closer(closer)));
            assert!(closers_of(open).is_some());
        }
    }

    // ── Invariants 10-15 ────────────────────────────────────────────────────────────────────

    /// A mapping built from the two texts alone: equal subtrees are `Identical`, differing leaves
    /// of one kind are `Update`, differing interior nodes are `MatchButNotIdentical` with their
    /// children paired by index, and leftover children are `Delete`/`Insert`.
    fn mapping_by_text(before: &Code, after: &Code) -> HumanMapping {
        fn walk(b: Node, a: Node, before: &str, after: &str, entries: &mut Vec<HumanMappingEntry>) {
            let entry = |operation, b: Option<Node>, a: Option<Node>| HumanMappingEntry {
                operation,
                before_path: b.map(path_for_node),
                after_path: a.map(path_for_node),
            };
            if before[b.byte_range()] == after[a.byte_range()] {
                entries.push(entry(HumanOperation::Identical, Some(b), Some(a)));
                return;
            }
            if b.child_count() == 0 && a.child_count() == 0 {
                entries.push(entry(HumanOperation::Update, Some(b), Some(a)));
                return;
            }
            entries.push(entry(
                HumanOperation::MatchButNotIdentical,
                Some(b),
                Some(a),
            ));
            let shared = b.child_count().min(a.child_count());
            for index in 0..shared {
                walk(
                    b.child(index).unwrap(),
                    a.child(index).unwrap(),
                    before,
                    after,
                    entries,
                );
            }
            for index in shared..b.child_count() {
                entries.push(entry(
                    HumanOperation::DeleteWithChildren,
                    Some(b.child(index).unwrap()),
                    None,
                ));
            }
            for index in shared..a.child_count() {
                entries.push(entry(
                    HumanOperation::InsertWithChildren,
                    None,
                    Some(a.child(index).unwrap()),
                ));
            }
        }
        let mut entries = Vec::new();
        walk(
            before.ast.as_ref().unwrap().root_node(),
            after.ast.as_ref().unwrap().root_node(),
            &before.contents,
            &after.contents,
            &mut entries,
        );
        HumanMapping {
            entries,
            ..Default::default()
        }
    }

    fn with_painting(
        mut mapping: HumanMapping,
        name: &str,
        entries: Vec<HumanTextEntry>,
    ) -> HumanMapping {
        mapping.text_mappings.push(NamedTextMapping {
            name: name.to_string(),
            mapping: HumanTextMapping { entries },
        });
        mapping
    }

    fn inserted(at: usize, count: usize) -> HumanTextEntry {
        HumanTextEntry {
            operation: HumanTextOperation::Insert,
            before: Vec::new(),
            after: vec![span(0, at, 0, at + count)],
        }
    }

    fn matched(before: (usize, usize), after: (usize, usize)) -> HumanTextEntry {
        HumanTextEntry {
            operation: HumanTextOperation::Match,
            before: vec![span(0, before.0, 0, before.1)],
            after: vec![span(0, after.0, 0, after.1)],
        }
    }

    fn violations_mentioning(
        mapping: &HumanMapping,
        before: &Code,
        after: &Code,
        phrase: &str,
    ) -> Vec<String> {
        violations(mapping, before, after)
            .into_iter()
            .filter(|v| v.contains(phrase))
            .collect()
    }

    #[test]
    fn a_paired_leaf_painted_gone_and_new_is_reported() {
        let (before, after) = (rust("let x = 1;\n"), rust("let x = 1;\n"));
        let mapping = with_painting(
            mapping_by_text(&before, &after),
            "Full",
            vec![deleted(4, 1), inserted(4, 1)],
        );
        let found = violations_mentioning(
            &mapping,
            &before,
            &after,
            "gone on one side and new on the other",
        );
        assert_eq!(found.len(), 1, "{found:?}");
        assert!(
            found[0].contains("on before row 1 and after row 1 - the first is `x`"),
            "{found:?}"
        );
    }

    #[test]
    fn a_paired_leaf_painted_gone_on_one_side_only_is_not_reported() {
        let (before, after) = (rust("let x = 1;\n"), rust("let x = 1;\n"));
        let mapping = with_painting(
            mapping_by_text(&before, &after),
            "Full",
            vec![deleted(4, 1)],
        );
        assert!(violations_mentioning(&mapping, &before, &after, "gone on one side").is_empty());
    }

    #[test]
    fn a_removed_named_leaf_nobody_painted_is_reported_and_punctuation_is_not() {
        let (before, after) = (rust("f(x, y);\n"), rust("f(x);\n"));
        let mapping = with_painting(mapping_by_text(&before, &after), "Full", Vec::new());
        let found =
            violations_mentioning(&mapping, &before, &after, "removed leaf/leaves unpainted");
        assert_eq!(found.len(), 1, "{found:?}");
        assert!(
            found[0].contains(
                "before leaves 1 removed leaf/leaves unpainted on row 1, the first \"identifier\" `y`"
            ),
            "{found:?}"
        );
    }

    #[test]
    fn a_removed_leaf_with_one_painted_byte_is_not_reported() {
        let (before, after) = (rust("f(x, y);\n"), rust("f(x);\n"));
        let mapping = with_painting(
            mapping_by_text(&before, &after),
            "Full",
            vec![deleted(3, 3)],
        );
        assert!(
            violations_mentioning(&mapping, &before, &after, "removed leaf/leaves unpainted")
                .is_empty()
        );
    }

    #[test]
    fn an_edited_leaf_painted_on_neither_side_is_reported() {
        let (before, after) = (rust("let x = 1;\n"), rust("let x = 2;\n"));
        let mapping = with_painting(mapping_by_text(&before, &after), "Minimal", Vec::new());
        let found = violations_mentioning(&mapping, &before, &after, "edited leaf/leaves");
        assert_eq!(found.len(), 1, "{found:?}");
        assert!(
            found[0].contains("on before row 1 and after row 1 - the first is `1` becoming `2`"),
            "{found:?}"
        );
    }

    #[test]
    fn an_edited_leaf_painted_on_one_side_is_enough() {
        let (before, after) = (rust("let x = 1;\n"), rust("let x = 2;\n"));
        let mapping = with_painting(
            mapping_by_text(&before, &after),
            "Minimal",
            vec![inserted(8, 1)],
        );
        assert!(violations_mentioning(&mapping, &before, &after, "edited leaf/leaves").is_empty());
    }

    #[test]
    fn a_painted_edit_over_an_all_identical_mapping_is_reported() {
        let (before, after) = (rust("let x = 1;\n"), rust("let x = 2;\n"));
        let mapping = with_painting(
            mapping_by_text(&before, &before),
            "Minimal",
            vec![matched((8, 9), (8, 9))],
        );
        let found = violations_mentioning(
            &mapping,
            &before,
            &after,
            "every entry of the tree mapping is Identical",
        );
        assert_eq!(found.len(), 1, "{found:?}");
    }

    #[test]
    fn a_whitespace_only_painting_over_an_all_identical_mapping_is_not_reported() {
        let (before, after) = (rust("let x = 1;\n"), rust("let x =  1;\n"));
        let mapping = with_painting(
            mapping_by_text(&before, &after),
            "Minimal",
            vec![matched((6, 9), (6, 10))],
        );
        assert!(
            violations_mentioning(&mapping, &before, &after, "every entry of the tree mapping")
                .is_empty()
        );
    }

    #[test]
    fn an_identical_entry_over_differing_tokens_is_reported() {
        let (before, after) = (rust("let x = 1;\n"), rust("let y = 1;\n"));
        // The mapping built from `before` alone pairs every node with itself by path, so it is
        // all `Identical` - and wrong about the root once the after side reads `y`.
        let mapping = mapping_by_text(&before, &before);
        let found = violations_mentioning(&mapping, &before, &after, "tokens differ");
        assert!(!found.is_empty(), "{found:?}");
        assert!(found[0].contains("`x` against `y`"), "{found:?}");
    }

    #[test]
    fn an_identical_entry_over_a_whitespace_difference_is_not_reported() {
        let (before, after) = (rust("let x = 1;\n"), rust("let x =  1;\n"));
        let mapping = mapping_by_text(&before, &before);
        assert!(violations_mentioning(&mapping, &before, &after, "tokens differ").is_empty());
    }

    #[test]
    fn a_match_but_not_identical_over_byte_identical_subtrees_is_reported() {
        let (before, after) = (rust("let x = 1;\n"), rust("let x = 1;\n"));
        let mut mapping = mapping_by_text(&before, &after);
        mapping.entries[0].operation = HumanOperation::MatchButNotIdentical;
        let found = violations_mentioning(&mapping, &before, &after, "read byte-identically");
        assert_eq!(found.len(), 1, "{found:?}");
    }

    #[test]
    fn a_match_but_not_identical_whose_subtrees_differ_is_the_expected_shape() {
        let (before, after) = (rust("let x = 1;\n"), rust("let x = 2;\n"));
        let mapping = mapping_by_text(&before, &after);
        assert!(
            violations_mentioning(&mapping, &before, &after, "read byte-identically").is_empty()
        );
    }

    // ── Invariant 20 ────────────────────────────────────────────────────────────────────────

    fn c(source: &str) -> Code {
        Code::from_string(source, &Language::C)
    }

    fn first_of_kind<'tree>(node: Node<'tree>, kind: &str) -> Option<Node<'tree>> {
        if node.kind() == kind {
            return Some(node);
        }
        let mut cursor = node.walk();
        let children: Vec<Node<'tree>> = node.children(&mut cursor).collect();
        children
            .into_iter()
            .find_map(|child| first_of_kind(child, kind))
    }

    fn wrapped_token_violations(
        mapping: &HumanMapping,
        before: &Code,
        after: &Code,
    ) -> Vec<String> {
        ground_truth_invariant_violations_for(mapping, before, after)
            .expect("checks run")
            .into_iter()
            .filter(|violation| violation.invariant == 20)
            .map(|violation| violation.message)
            .collect()
    }

    /// `mapping` without the entries on `before` or `after` or any node under them, plus `added`.
    fn replacing(
        mut mapping: HumanMapping,
        before: Node,
        after: Node,
        added: Vec<HumanMappingEntry>,
    ) -> HumanMapping {
        let (before_path, after_path) = (path_for_node(before), path_for_node(after));
        mapping.entries.retain(|entry| {
            !entry
                .before_path
                .as_ref()
                .is_some_and(|path| path.starts_with(&before_path))
                && !entry
                    .after_path
                    .as_ref()
                    .is_some_and(|path| path.starts_with(&after_path))
        });
        mapping.entries.extend(added);
        mapping
    }

    fn entry(
        operation: HumanOperation,
        before: Option<Node>,
        after: Option<Node>,
    ) -> HumanMappingEntry {
        HumanMappingEntry {
            operation,
            before_path: before.map(path_for_node),
            after_path: after.map(path_for_node),
        }
    }

    #[test]
    fn null_to_nullptr_paired_by_text_is_the_expected_shape() {
        let (before, after) = (c("int *p = NULL;\n"), c("int *p = nullptr;\n"));
        let mapping = mapping_by_text(&before, &after);
        assert!(wrapped_token_violations(&mapping, &before, &after).is_empty());
    }

    #[test]
    fn a_matched_null_whose_token_is_deleted_and_inserted_is_reported() {
        let (before, after) = (c("int *p = NULL;\n"), c("int *p = nullptr;\n"));
        let before_null = first_of_kind(before.ast.as_ref().unwrap().root_node(), "null").unwrap();
        let after_null = first_of_kind(after.ast.as_ref().unwrap().root_node(), "null").unwrap();
        let (before_token, after_token) =
            (before_null.child(0).unwrap(), after_null.child(0).unwrap());
        let mapping = replacing(
            mapping_by_text(&before, &after),
            before_token,
            after_token,
            vec![
                entry(HumanOperation::Delete, Some(before_token), None),
                entry(HumanOperation::Insert, None, Some(after_token)),
            ],
        );
        let found = wrapped_token_violations(&mapping, &before, &after);
        assert_eq!(found.len(), 1, "{found:?}");
        assert!(
            found[0].contains("`null` reads `NULL` on before row 1 and `nullptr` on after row 1"),
            "{found:?}"
        );
        assert!(found[0].contains("nothing but its token"), "{found:?}");
    }

    #[test]
    fn a_null_deleted_and_inserted_whole_in_a_pinned_position_is_reported() {
        let (before, after) = (c("int *p = NULL;\n"), c("int *p = nullptr;\n"));
        let before_null = first_of_kind(before.ast.as_ref().unwrap().root_node(), "null").unwrap();
        let after_null = first_of_kind(after.ast.as_ref().unwrap().root_node(), "null").unwrap();
        let mapping = replacing(
            mapping_by_text(&before, &after),
            before_null,
            after_null,
            vec![
                entry(HumanOperation::DeleteWithChildren, Some(before_null), None),
                entry(HumanOperation::InsertWithChildren, None, Some(after_null)),
            ],
        );
        let found = wrapped_token_violations(&mapping, &before, &after);
        assert_eq!(found.len(), 1, "{found:?}");
        assert!(found[0].contains("inserts the other whole"), "{found:?}");
    }

    /// `static` -> `const` is a storage class removed beside a type qualifier added: two wrappers
    /// of different kinds are two roles, so neither invariant 20 nor 18 pairs them
    /// (`cpp-microsoft-terminal-funny-code-comment`).
    #[test]
    fn wrappers_of_different_kinds_are_not_one_element() {
        let (before, after) = (c("static int x = 1;\n"), c("const int x = 1;\n"));
        let before_static = first_of_kind(
            before.ast.as_ref().unwrap().root_node(),
            "storage_class_specifier",
        )
        .unwrap();
        let after_const =
            first_of_kind(after.ast.as_ref().unwrap().root_node(), "type_qualifier").unwrap();
        assert_eq!(
            (before_static.child_count(), after_const.child_count()),
            (1, 1),
            "the premise: both are wrappers around one token"
        );
        let mapping = replacing(
            mapping_by_text(&before, &after),
            before_static,
            after_const,
            vec![
                entry(
                    HumanOperation::DeleteWithChildren,
                    Some(before_static),
                    None,
                ),
                entry(HumanOperation::InsertWithChildren, None, Some(after_const)),
            ],
        );
        let reported: Vec<String> =
            ground_truth_invariant_violations_for(&mapping, &before, &after)
                .expect("checks run")
                .into_iter()
                .filter(|violation| matches!(violation.invariant, 18 | 20))
                .map(|violation| violation.message)
                .collect();
        assert!(reported.is_empty(), "{reported:?}");
    }

    /// A Rust `line_comment`'s only child is its `//`, but the comment reads more than that token,
    /// so pairing the comment says nothing about the `//` (`rust-algorithm-change`).
    #[test]
    fn a_node_reading_more_than_its_only_token_is_not_a_wrapper() {
        let (before, after) = (rust("// a\nfn f() {}\n"), rust("// b\nfn f() {}\n"));
        let before_comment =
            first_of_kind(before.ast.as_ref().unwrap().root_node(), "line_comment").unwrap();
        let after_comment =
            first_of_kind(after.ast.as_ref().unwrap().root_node(), "line_comment").unwrap();
        assert_eq!(
            before_comment.child_count(),
            1,
            "the premise: `//` is its only child"
        );
        let (before_token, after_token) = (
            before_comment.child(0).unwrap(),
            after_comment.child(0).unwrap(),
        );
        let mapping = replacing(
            mapping_by_text(&before, &after),
            before_token,
            after_token,
            vec![
                entry(HumanOperation::Delete, Some(before_token), None),
                entry(HumanOperation::Insert, None, Some(after_token)),
            ],
        );
        assert!(wrapped_token_violations(&mapping, &before, &after).is_empty());
    }

    /// `0` -> `nullptr` is a leaf against a wrapped token: invariant 18's shape, not this one's.
    #[test]
    fn a_leaf_against_a_wrapped_token_is_invariant_18s() {
        let (before, after) = (c("int *p = 0;\n"), c("int *p = nullptr;\n"));
        let before_zero =
            first_of_kind(before.ast.as_ref().unwrap().root_node(), "number_literal").unwrap();
        let after_null = first_of_kind(after.ast.as_ref().unwrap().root_node(), "null").unwrap();
        let mapping = replacing(
            mapping_by_text(&before, &after),
            before_zero,
            after_null,
            vec![
                entry(HumanOperation::Delete, Some(before_zero), None),
                entry(HumanOperation::InsertWithChildren, None, Some(after_null)),
            ],
        );
        assert!(wrapped_token_violations(&mapping, &before, &after).is_empty());
        let found: Vec<String> = ground_truth_invariant_violations_for(&mapping, &before, &after)
            .expect("checks run")
            .into_iter()
            .filter(|violation| violation.invariant == 18)
            .map(|violation| violation.message)
            .collect();
        assert_eq!(found.len(), 1, "{found:?}");
        assert!(
            found[0].contains("holds number_literal `0` on before row 1 and null `nullptr`"),
            "{found:?}"
        );
    }

    // ── Invariants 21-23 ────────────────────────────────────────────────────────────────────

    fn numbered(mapping: &HumanMapping, before: &Code, after: &Code, rule: u8) -> Vec<String> {
        ground_truth_invariant_violations_for(mapping, before, after)
            .expect("checks run")
            .into_iter()
            .filter(|violation| violation.invariant == rule)
            .map(|violation| violation.message)
            .collect()
    }

    /// `let v = a + b;` -> `let v = a - b;`, the operator at column 10 on both sides.
    fn operator_swap() -> (Code, Code) {
        (rust("let v = a + b;\n"), rust("let v = a - b;\n"))
    }

    #[test]
    fn a_token_painted_as_its_own_update_but_deleted_and_inserted_is_reported() {
        let (before, after) = operator_swap();
        let plus = first_of_kind(before.ast.as_ref().unwrap().root_node(), "+").unwrap();
        let minus = first_of_kind(after.ast.as_ref().unwrap().root_node(), "-").unwrap();
        let mapping = replacing(
            mapping_by_text(&before, &after),
            plus,
            minus,
            vec![
                entry(HumanOperation::Delete, Some(plus), None),
                entry(HumanOperation::Insert, None, Some(minus)),
            ],
        );
        let mapping = with_painting(mapping, "Minimal", vec![matched((10, 11), (10, 11))]);
        let found = numbered(&mapping, &before, &after, 21);
        assert_eq!(found.len(), 1, "{found:?}");
        assert!(found[0].contains("the first is `+`"), "{found:?}");
    }

    #[test]
    fn a_token_painted_as_its_own_update_and_paired_is_the_expected_shape() {
        let (before, after) = operator_swap();
        let mapping = with_painting(
            mapping_by_text(&before, &after),
            "Minimal",
            vec![matched((10, 11), (10, 11))],
        );
        assert!(numbered(&mapping, &before, &after, 21).is_empty());
    }

    #[test]
    fn an_identical_pair_painted_new_on_one_side_is_reported_and_punctuation_is_not() {
        let source = rust("let v = a + b;\n");
        let mapping = with_painting(
            mapping_by_text(&source, &source),
            "Minimal",
            vec![inserted(8, 1), inserted(13, 1)],
        );
        let found = numbered(&mapping, &source, &source, 22);
        assert_eq!(found.len(), 1, "{found:?}");
        assert!(
            found[0].contains("1 leaf/leaves"),
            "only `a`, not `;`: {found:?}"
        );
        assert!(found[0].contains("the first is `a`"), "{found:?}");
    }

    #[test]
    fn a_painted_match_pairing_a_leaf_elsewhere_than_the_mapping_is_reported() {
        let source = rust("let v = a + b;\n");
        // The painting says `a` became `b`; the mapping keeps `a` as `a`.
        let mapping = with_painting(
            mapping_by_text(&source, &source),
            "Minimal",
            vec![matched((8, 9), (12, 13))],
        );
        let found = numbered(&mapping, &source, &source, 23);
        assert_eq!(found.len(), 1, "{found:?}");
        assert!(found[0].contains("the first is `a`"), "{found:?}");

        let agreeing = with_painting(
            mapping_by_text(&source, &source),
            "Minimal",
            vec![matched((8, 9), (8, 9))],
        );
        assert!(numbered(&agreeing, &source, &source, 23).is_empty());
    }
}