silcrow 0.2.1

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

use crate::follow::FollowIndex;
use crate::list_tty;
use crate::marker;
use crate::parse::{self, PointerKind, Scan, Target};
use crate::policy::TestPaths;
use crate::span;
use crate::span_lang;
use crate::walk;

mod review;
mod structure;
mod ungoverned;

/// How `diff` prints its review.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Form {
    /// JSON, under `--json`.
    Json,
    /// The markdown review packet, as is.
    Markdown,
    /// The patches alone, through delta or the pager on a TTY.
    Tty,
}

impl Form {
    /// The form the flags name, else the patches alone.
    pub fn chosen(json: bool, markdown: bool) -> Self {
        // ยง t0jfkh0n1@az0xw
        match (json, markdown) {
            (true, _) => Form::Json,
            (_, true) => Form::Markdown,
            _ => Form::Tty,
        }
    }
}

pub fn run(
    ws: &crate::workspace::Workspace,
    projects: &[&crate::workspace::ProjectRef],
    all: bool,
    rev: Option<String>,
    laws: &[String],
    verbose: bool,
    form: Form,
) -> Result<()> {
    let history = (form == Form::Json).then(|| crate::meta::History::start(&ws.root));
    let review = gather(ws, projects, all, rev, laws, verbose)?;
    match (form, history) {
        (_, Some(history)) => {
            let ids: Vec<&str> = review.rules.iter().map(|rule| local_id(&rule.id)).collect();
            print!("{}", review::review_json(&review, &history.declared(&ids)));
            Ok(())
        }
        (Form::Tty, None) if !review.holds_nothing() => {
            emit_diff_stream(&review::review_tty(&review))
        }
        _ => {
            print!("{}", review::review_markdown(&review));
            Ok(())
        }
    }
}

/// The `diff --md` packet of every project of `projects` against `base`, whether it holds a
/// law or a change of the Silcrow block, and the lines that name its shared causes for the
/// summary above it, as a comparing `check` prints it.
pub fn packet(
    ws: &crate::workspace::Workspace,
    projects: &[&crate::workspace::ProjectRef],
    base: &str,
) -> Result<(String, bool, String)> {
    // ยง j44p1s9z8.k@1anp4
    let review = gather(ws, projects, true, Some(base.to_string()), &[], false)?;
    let holds = !review.rules.is_empty() || !review.block.is_empty();
    Ok((
        review::review_markdown(&review),
        holds,
        review::shared_summary(&review),
    ))
}

fn gather(
    ws: &crate::workspace::Workspace,
    projects: &[&crate::workspace::ProjectRef],
    all: bool,
    rev: Option<String>,
    laws: &[String],
    verbose: bool,
) -> Result<review::Review> {
    // ยง cme63msgx.b@hevk5
    let Some(first) = projects.first() else {
        bail!("silcrow diff found no project to read");
    };
    let base_ref = resolve_base(ws, &first.dir, rev)?;
    let mut pieces = Vec::new();
    for project in projects {
        pieces.push(project_piece(ws, project, &base_ref, laws, verbose)?);
    }
    // ยง cme63msgx.d@fncez
    let declared: BTreeSet<&String> = pieces.iter().flat_map(|piece| &piece.declared).collect();
    let unknown: Vec<&String> = laws.iter().filter(|law| !declared.contains(law)).collect();
    if !unknown.is_empty() {
        let names: Vec<String> = unknown.iter().map(|law| format!("`{law}`")).collect();
        bail!(
            "--law {} names no law or clause that either side of the comparison against {base_ref} declares",
            names.join(", ")
        );
    }
    // ยง end cme63msgx.d
    if !all {
        // ยง n4fbh9vd4.f@r6nxz
        let unread: BTreeSet<&String> = pieces.iter().flat_map(|piece| &piece.unread).collect();
        if !unread.is_empty() {
            let names: Vec<String> = unread.iter().map(|key| format!("`{key}`")).collect();
            eprintln!(
                "Nested project(s) {} differ from {base_ref} and this diff does not read them. Run `silcrow diff --all` to read every project.",
                names.join(", ")
            );
        }
    }
    let folded: usize = pieces.iter().map(|piece| piece.folded).sum();
    let block: Vec<BlockRow> = pieces
        .iter()
        .flat_map(|piece| {
            piece.block.iter().map(|(attr, old, new)| BlockRow {
                path: format!("{}AGENTS.md", piece.shown),
                attr,
                old: old.clone(),
                new: new.clone(),
            })
        })
        .collect();
    let mut rules = Vec::new();
    let mut ungoverned = Vec::new();
    for mut piece in pieces {
        ungoverned.append(&mut piece.ungoverned);
        if piece.changes.is_empty() {
            continue;
        }
        let root = piece.root.as_path();
        let new_rev = diff_ends(root, &base_ref)?.new_rev;
        let stable = collect_stable_markers(root, new_rev.as_deref(), &piece.changes)?;
        piece.changes.extend(stable);
        piece.changes.sort();
        piece.changes.dedup();
        fill_file_map(root, new_rev.as_deref(), &piece.changes, &mut piece.files);
        let follow = match piece.follow {
            Some(follow) => follow,
            None => new_side_follow(root, &base_ref)?,
        };
        let callers = drift_callers(&piece.changes, &follow);
        let docs = crate::walk::Project::at(root)?.docs;
        let shown = Shown {
            prefix: &piece.shown,
            key: &piece.key,
            docs: &docs,
        };
        rules.extend(review::law_entries(
            &piece.changes,
            &piece.files,
            &follow,
            &callers,
            &shown,
        ));
    }
    Ok(review::Review::gather(
        base_ref,
        laws.to_vec(),
        folded,
        block,
        rules,
        ungoverned,
    ))
}

/// An attribute of a project's Silcrow block that the two sides write differently.
struct BlockRow {
    /// The `AGENTS.md` of the project, from the workspace root.
    path: String,
    attr: &'static str,
    old: Option<String>,
    new: Option<String>,
}

const BLOCK_HEADING: &str = "Silcrow block changed";

/// One project's diff: its changes, addressed and pathed as the project reads them, and what
/// rendering them needs.
struct Piece {
    root: PathBuf,
    changes: Vec<Change>,
    folded: usize,
    files: FileMap,
    follow: Option<FollowIndex>,
    /// The path of the project from the workspace root, `/`-ended, empty for the root.
    shown: String,
    /// The qualifier of the project's own addresses, `None` for the root.
    key: Option<String>,
    /// The nested projects the comparison touched that are diffed from their own directory.
    unread: BTreeSet<String>,
    /// Each attribute of the project's Silcrow block the two sides write differently.
    block: Vec<(&'static str, Option<String>, Option<String>)>,
    /// The hunks no marker covers and no pin reads, paths from the workspace root.
    ungoverned: Vec<ungoverned::FileHunks>,
    /// Every law and clause address either side declares, struck ones included, as the
    /// workspace root reads them.
    declared: BTreeSet<String>,
}

fn project_piece(
    ws: &crate::workspace::Workspace,
    project: &crate::workspace::ProjectRef,
    base_ref: &str,
    laws: &[String],
    verbose: bool,
) -> Result<Piece> {
    // ยง n4fbh9vd4.d@h61x2
    let root = project.dir.as_path();
    let key = (project.key != ".").then(|| project.key.clone());
    let kept = |change: &Change| {
        let address = qualify(&key, &change.address);
        // A clause kept alone still reads as part of the remint of its law.
        laws.is_empty()
            || laws.iter().any(|want| {
                keep_address(&address, want)
                    || (change.kind == Kind::Reminted && split_address(want).0 == address)
            })
    };
    let paths = changed_paths(root, base_ref)?;
    let (old, new, markers, files) = scan_sides(ws, root, base_ref, &paths)?;
    let declared: BTreeSet<String> = [&old, &new]
        .into_iter()
        .flat_map(|scan| &scan.laws)
        .flat_map(|law| {
            let letters = law.clauses.iter().filter_map(|c| c.letter.as_ref());
            std::iter::once(law.id.clone()).chain(letters.map(|l| format!("{}.{l}", law.id)))
        })
        .map(|address| qualify(&key, &address))
        .collect();
    let mut changes = collect_law_changes(&old, &new);
    changes.extend(collect_deleted(&old, &new));
    changes.extend(collect_pointer_changes(&old, &new));
    changes.extend(markers);
    changes.retain(|change| kept(change));
    changes.sort();
    changes.dedup();
    let (folded, sides);
    (changes, folded, sides) = sort_markers(ws, root, base_ref, changes, &files, verbose)?;
    let marked: BTreeSet<String> = changes
        .iter()
        .flat_map(|change| [change.address.clone(), split_address(&change.address).0])
        .collect();
    let recalled = recalls(&new, &marked, &changes);
    changes.extend(recalled);
    changes.retain(|change| kept(change));
    changes.sort();
    changes.dedup();
    let ends = diff_ends(root, base_ref)?;
    let block = match laws.is_empty() {
        false => Vec::new(),
        true => {
            let old = crate::published::agents_at(root, &ends.old_rev)?;
            let new = match &ends.new_rev {
                Some(rev) => crate::published::agents_at(root, rev)?,
                None => read_worktree(root, Path::new("AGENTS.md")),
            };
            crate::published::block_changes(old.as_deref(), new.as_deref())
        }
    };
    let owners = Owners::read(ws, root, &ends)?;
    let unread = nested_touched(project, &paths, &owners);
    // Paths read from the workspace root, so a nested project's files never read as another's.
    let shown = shown_prefix(ws, root);
    let ungoverned = match laws.is_empty() {
        false => Vec::new(),
        true => {
            let renamed: BTreeMap<String, String> = paths
                .iter()
                .filter(|t| t.old != t.new)
                .map(|t| (path_of(&t.old), path_of(&t.new)))
                .collect();
            let notes = [
                ungoverned::note_lines(&old, &renamed),
                ungoverned::note_lines(&new, &BTreeMap::new()),
            ];
            let governed = ungoverned::governed(&files, sides.as_ref(), notes, &renamed);
            let held: BTreeSet<String> = paths
                .iter()
                .filter(|t| {
                    owners.of(&t.old, false) != Owner::Other
                        || owners.of(&t.new, true) != Owner::Other
                })
                .map(|t| path_of(&t.new))
                .collect();
            let mut hunks = ungoverned::ungoverned(
                root,
                base_ref,
                ends.new_rev.is_none(),
                |file| held.contains(&file.path),
                &governed,
            )?;
            for file in &mut hunks {
                for path in [&mut file.old_path, &mut file.new_path]
                    .into_iter()
                    .flatten()
                {
                    *path = format!("{shown}{path}");
                }
                file.path = format!("{shown}{}", file.path);
            }
            hunks
        }
    };
    Ok(Piece {
        root: root.to_path_buf(),
        changes,
        folded: folded.len(),
        files,
        follow: sides.map(|[_, new]| new.follow),
        shown,
        key,
        unread,
        block,
        ungoverned,
        declared,
    })
}

/// The nested projects, keyed from the workspace root, whose files the comparison `paths` of
/// `project` touched and that only a run in their own directory reads.
fn nested_touched(
    project: &crate::workspace::ProjectRef,
    paths: &[Touched],
    owners: &Owners,
) -> BTreeSet<String> {
    paths
        .iter()
        .flat_map(|touched| {
            [
                owners.other_of(&touched.old, false),
                owners.other_of(&touched.new, true),
            ]
        })
        .flatten()
        .map(|dir| path_of(&crate::workspace::in_workspace(&project.key, &dir)))
        .collect()
}

/// `address` as the workspace reads it: an unqualified one of a nested project under that
/// project's key, one qualified by the root's key unqualified.
fn qualify(key: &Option<String>, address: &str) -> String {
    match (address.split_once(':'), key) {
        (Some((".", local)), _) => local.to_string(),
        (Some(_), _) | (None, None) => address.to_string(),
        (None, Some(key)) => format!("{key}:{address}"),
    }
}

/// What a path relative to `root` is prefixed with to read from the workspace root.
fn shown_prefix(ws: &crate::workspace::Workspace, root: &Path) -> String {
    // ยง t0jfkh0n1@cv1vm
    match root.strip_prefix(&ws.root) {
        Ok(rel) if !rel.as_os_str().is_empty() => format!("{}/", path_of(rel)),
        _ => String::new(),
    }
}

/// The pins `diff` against `base` folds into its remint line, keyed by the path and the line
/// the compared side holds each at, with the digest the comparison point held there.
pub fn folded_pins(
    ws: &crate::workspace::Workspace,
    root: &Path,
    base: &str,
) -> Result<BTreeMap<(PathBuf, usize), String>> {
    // ยง n4fbh9vd4.d@3r582
    let paths = changed_paths(root, base)?;
    let (_, _, markers, files) = scan_sides(ws, root, base, &paths)?;
    let (_, folded, _) = sort_markers(ws, root, base, markers, &files, false)?;
    let mut out = BTreeMap::new();
    for change in folded {
        let (Some(path), Some(line), Some(old)) =
            (change.new_path, change.lines[1], change.old_text.as_deref())
        else {
            continue;
        };
        let digest = crate::marker::entry_for(old, &change.address).and_then(|pin| pin.digest);
        if let Some(digest) = digest {
            out.insert((PathBuf::from(path), line), digest);
        }
    }
    Ok(out)
}

/// The one line a hash scheme remint collapses to, beside whatever else changed.
fn remint_line(pinned: usize) -> String {
    // ยง n4fbh9vd4.d@5w2qn
    format!("  scheme   span digest remint ({pinned} pinned markers)")
}

fn nest_changes(changes: &[Change]) -> BTreeMap<String, NestedLaw> {
    // ยง yjrm4q97t@g12j1
    let mut laws: BTreeMap<String, NestedLaw> = BTreeMap::new();
    for change in changes {
        let (id, letter) = split_address(&change.address);
        let law = laws.entry(id).or_default();
        match (change.kind, letter) {
            (Kind::Marker | Kind::Drift | Kind::Accepted, Some(letter)) => {
                law.clauses
                    .entry(letter)
                    .or_default()
                    .markers
                    .push(change.clone());
            }
            (Kind::Marker | Kind::Drift | Kind::Accepted, None) => law.markers.push(change.clone()),
            (_, Some(letter)) => {
                law.clauses
                    .entry(letter)
                    .or_default()
                    .changes
                    .push(change.clone());
            }
            (_, None) => law.changes.push(change.clone()),
        }
    }
    laws
}

fn collect_stable_markers(
    root: &Path,
    new_rev: Option<&str>,
    changes: &[Change],
) -> Result<Vec<Change>> {
    // ยง yjrm4q97t.a@9hz85
    // A recall is context: the law it names gains no unchanged pin from it.
    let addresses: BTreeSet<String> = changes
        .iter()
        .filter(|c| c.kind != Kind::Recall)
        .map(|c| c.address.clone())
        .collect();
    if addresses.is_empty() {
        return Ok(Vec::new());
    }
    let mut out = Vec::new();
    let rels = new_side_paths(root, new_rev)?;
    for (rel, text) in rels.iter().zip(read_new_sides(root, new_rev, &rels)) {
        let rel_s = path_of(rel);
        let Some(text) = text else {
            continue;
        };
        for row in span::marker_rows(rel, &text, None) {
            for marker in row.markers {
                let addr = marker.display();
                if !addresses.contains(&addr) || marker_listed(changes, &addr, &rel_s) {
                    continue;
                }
                let bit = row.line.trim().to_string();
                out.push(Change {
                    address: addr,
                    kind: Kind::Marker,
                    old_path: Some(rel_s.clone()),
                    new_path: Some(rel_s.clone()),
                    old_text: Some(bit.clone()),
                    new_text: Some(bit),
                    callees: Vec::new(),
                    lines: [None, None],
                    why: None,
                });
            }
        }
    }
    Ok(out)
}

/// The follow index of the compared side, so a boundary drift can name its callers.
fn new_side_follow(root: &Path, base_ref: &str) -> Result<FollowIndex> {
    let new_rev = diff_ends(root, base_ref)?.new_rev;
    let sources = side_sources(&new_side_paths(root, new_rev.as_deref())?, |rels| {
        read_new_sides(root, new_rev.as_deref(), rels)
    });
    Ok(FollowIndex::from_sources(
        &sources,
        &crate::policy::TestPaths::at(root)?,
    ))
}

/// The code files of a tested language among `paths`, each with its text as `read` gives it.
/// A file `read` has no text for is left out.
fn side_sources(
    paths: &[PathBuf],
    read: impl Fn(&[PathBuf]) -> Vec<Option<String>>,
) -> Vec<(PathBuf, String)> {
    let rels: Vec<PathBuf> = paths
        .iter()
        .filter(|rel| crate::follow::reads_path(rel))
        .cloned()
        .collect();
    let texts = read(&rels);
    rels.into_iter()
        .zip(texts)
        .filter_map(|(rel, text)| Some((rel, text?)))
        .collect()
}

/// The code files of the compared side, relative to `root`: those of the worktree, or those
/// the right end of a range holds.
fn new_side_paths(root: &Path, new_rev: Option<&str>) -> Result<Vec<PathBuf>> {
    // ยง cme63msgx.b@wnbeb
    let Some(rev) = new_rev else {
        return Ok(walk::code_files(root)?
            .iter()
            .map(|path| path.strip_prefix(root).unwrap_or(path).to_path_buf())
            .collect());
    };
    let project = walk::Project::at(root)?;
    let listed = git_lines(root, &["ls-tree", "-r", "--name-only", rev, "--", "."])?;
    Ok(listed
        .into_iter()
        .filter(|rel| walk::walks_to(&project, rel))
        .collect())
}

fn fill_file_map(root: &Path, new_rev: Option<&str>, changes: &[Change], files: &mut FileMap) {
    let missing: BTreeSet<&String> = changes
        .iter()
        .filter(|change| change.is_marker())
        .flat_map(|change| [&change.old_path, &change.new_path].into_iter().flatten())
        .filter(|path| !files.contains_key(*path))
        .collect();
    let rels: Vec<PathBuf> = missing
        .iter()
        .map(|path| PathBuf::from(path.as_str()))
        .collect();
    for (path, text) in missing
        .into_iter()
        .zip(read_new_sides(root, new_rev, &rels))
    {
        files.insert(path.clone(), (text.clone(), text));
    }
}

fn marker_listed(changes: &[Change], address: &str, path: &str) -> bool {
    changes.iter().any(|change| {
        change.is_marker()
            && change.address == address
            && (change.new_path.as_deref() == Some(path)
                || change.old_path.as_deref() == Some(path))
    })
}

/// The laws whose spans reach a drifted boundary without following it, keyed by the path and
/// the line of its pin on the compared side.
type Callers = BTreeMap<(String, usize), Vec<String>>;

fn drift_callers(changes: &[Change], follow: &FollowIndex) -> Callers {
    // ยง jncrstyg1.b@1g7fn
    changes
        .iter()
        .filter(|c| matches!(c.kind, Kind::Drift | Kind::Accepted))
        .filter_map(|c| Some((c.new_path.as_deref()?, c.lines[1]?)))
        .filter_map(|(path, line)| {
            let callers = follow.caller_laws(Path::new(path), line);
            (!callers.is_empty()).then(|| ((path.to_string(), line), callers))
        })
        .collect()
}

/// Whether a marker change leaves a pin of the comparison point unpaired: removed, moved
/// away or bare now, which a comparing `check` names.
fn lost_pin(change: &Change) -> bool {
    let pinned = |text: &Option<String>| text.as_deref().is_some_and(|t| t.lines().any(is_pinned));
    pinned(&change.old_text) && !pinned(&change.new_text)
}

#[derive(Default)]
struct NestedLaw {
    changes: Vec<Change>,
    clauses: BTreeMap<String, NestedClause>,
    markers: Vec<Change>,
}

#[derive(Default)]
struct NestedClause {
    changes: Vec<Change>,
    markers: Vec<Change>,
}

/// The id of a law key without its project qualifier.
fn local_id(id: &str) -> &str {
    id.rsplit_once(':').map_or(id, |(_, local)| local)
}

/// `[<projectpath>:]<id>[.<letter>]` as its law and its letter. A project path may hold a dot.
fn split_address(address: &str) -> (String, Option<String>) {
    let local = address.rfind(':').map_or(0, |at| at + 1);
    match address[local..].split_once('.') {
        Some((id, letter)) => (
            format!("{}{id}", &address[..local]),
            Some(letter.to_string()),
        ),
        None => (address.to_string(), None),
    }
}

fn json_escape(value: &str) -> String {
    serde_json::Value::from(value).to_string()
}

/// The right end of the range `rev` names, `None` when it names a revision compared against
/// the worktree.
pub fn range_end(rev: Option<&str>) -> Option<String> {
    // ยง j38jtk0t2.b@7e2zh
    let rev = rev?;
    let at = rev
        .find("...")
        .map(|at| at + 3)
        .or(rev.find("..").map(|at| at + 2))?;
    Some(match rev[at..].trim() {
        "" => "HEAD".to_string(),
        end => end.to_string(),
    })
}

/// The one revision or range the arguments of `diff` name, as `git diff` reads them: two
/// revisions are the two ends of a range.
pub fn revision(revs: &[String]) -> Result<Option<String>> {
    // ยง cme63msgx.a@61ta9
    match revs {
        [] => Ok(None),
        [rev] => Ok(Some(rev.clone())),
        [a, b] if a.contains("..") || b.contains("..") => {
            bail!("silcrow diff takes one range or two revisions, not `{a}` and `{b}`")
        }
        [a, b] => Ok(Some(format!("{a}..{b}"))),
        _ => bail!("silcrow diff takes at most two revisions"),
    }
}

/// Fails an end of `rev` that names no commit: naming `--law` when it reads as a law address,
/// else with git's own message and the arguments `diff` takes. Outside git, `ensure_git` names
/// the repository it needs.
pub fn refuse_unresolved(root: &Path, rev: Option<&str>) -> Result<()> {
    // ยง cme63msgx.a@2fp6n
    if !git_ok(root, &["rev-parse", "--is-inside-work-tree"]) {
        return Ok(());
    }
    for end in rev.into_iter().flat_map(|r| r.split("..")) {
        let end = end.trim_start_matches('.');
        let commit = format!("{end}^{{commit}}");
        if end.is_empty() || git_ok(root, &["rev-parse", "--verify", "--quiet", &commit]) {
            continue;
        }
        let id = end.split_once('.').map_or(end, |(id, _)| id);
        if crate::hash::is_crockford_id(id) {
            bail!(
                "`{end}` names no revision, and reads as a law address: run `silcrow diff --law {end}` to keep one law or clause"
            );
        }
        let out = crate::workspace::git(root)
            .args(["log", "-1", "--format=", end, "--"])
            .output()
            .context("git log")?;
        bail!(
            "{}\n`silcrow diff` takes revisions as `git diff` does: none, `<rev>`, `<a> <b>`, `<a>..<b>` or `<a>...<b>`.",
            String::from_utf8_lossy(&out.stderr).trim()
        );
    }
    Ok(())
}

fn keep_address(address: &str, want: &str) -> bool {
    // ยง yjrm4q97t@tk6pk
    if address == want {
        return true;
    }
    if want.contains('.') {
        return false;
    }
    split_address(address).0 == want
}

fn resolve_base(
    ws: &crate::workspace::Workspace,
    root: &Path,
    explicit: Option<String>,
) -> Result<String> {
    // ยง cme63msgx.a@4j6ad
    if let Some(r) = explicit {
        ensure_git(root)?;
        return Ok(r);
    }
    ensure_git(root)?;
    Ok(ws.base_ref("HEAD")?.unwrap_or_else(|| "HEAD".to_string()))
}

fn ensure_git(root: &Path) -> Result<()> {
    if !git_ok(root, &["rev-parse", "--is-inside-work-tree"]) {
        bail!("silcrow diff needs a git repository");
    }
    crate::published::require_history(root)
}

/// A path the comparison touched, as the comparison point names it and as the compared side
/// does. They differ only for a rename.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
struct Touched {
    old: PathBuf,
    new: PathBuf,
}

fn changed_paths(root: &Path, base: &str) -> Result<Vec<Touched>> {
    // ยง cme63msgx.b@9ft7g
    // ยง cme63msgx.c@q7zr0
    // A project below the toplevel reads its own paths, relative to its own directory.
    let status = git_stdout(
        root,
        &[
            "diff",
            "--relative",
            "--name-status",
            "--find-renames",
            "--diff-filter=ACDMR",
            base,
        ],
    )?;
    let mut paths = Vec::new();
    for line in status.lines().filter(|l| !l.is_empty()) {
        let fields: Vec<&str> = line.split('\t').collect();
        match fields[..] {
            [kind, old, new] if kind.starts_with('R') || kind.starts_with('C') => {
                paths.push(Touched {
                    old: PathBuf::from(old),
                    new: PathBuf::from(new),
                })
            }
            [_, path] => paths.push(Touched {
                old: PathBuf::from(path),
                new: PathBuf::from(path),
            }),
            _ => bail!("git diff --name-status: malformed line {line:?}"),
        }
    }
    // ยง end cme63msgx.c
    for path in git_lines(root, &["ls-files", "--others", "--exclude-standard"])? {
        paths.push(Touched {
            old: path.clone(),
            new: path,
        });
    }
    paths.sort();
    paths.dedup();
    Ok(paths)
}

/// Each file `git diff` reads as changed since `base`, untracked ones included, from its path
/// there to its path now. They differ only for a rename.
pub fn touched(root: &Path, base: &str) -> Result<BTreeMap<PathBuf, PathBuf>> {
    Ok(changed_paths(root, base)?
        .into_iter()
        .map(|touched| (touched.old, touched.new))
        .collect())
}

type FileMap = BTreeMap<String, (Option<String>, Option<String>)>;

/// The nested projects each side holds, relative to `root`, and the key each would qualify its
/// addresses with.
struct Owners {
    old: Vec<PathBuf>,
    new: Vec<PathBuf>,
    own_key: String,
}

/// Who a file of one side belongs to in this diff.
#[derive(Debug, Clone, PartialEq, Eq)]
enum Owner {
    /// The project `diff` runs in.
    Own,
    /// A nested project the comparison point holds and the compared side does not, under the
    /// key its addresses carry here.
    Vanished(PathBuf, String),
    /// A nested project the side holds that is diffed from its own directory.
    Other,
}

impl Owners {
    fn read(ws: &crate::workspace::Workspace, root: &Path, ends: &DiffEnds) -> Result<Self> {
        let old = crate::published::projects_at(root, &ends.old_rev)?;
        let new = match &ends.new_rev {
            Some(rev) => crate::published::projects_at(root, rev)?,
            None => ws
                .projects
                .iter()
                .filter_map(|project| project.dir.strip_prefix(root).ok())
                .filter(|rel| !rel.as_os_str().is_empty())
                .map(Path::to_path_buf)
                .collect(),
        };
        let own_key = ws
            .projects
            .iter()
            .find(|project| project.dir == root)
            .map(|project| project.key.clone())
            .with_context(|| format!("{} is no project of the workspace", root.display()))?;
        Ok(Self { old, new, own_key })
    }

    /// The owner of `rel` on the comparison side, or with `new` on the compared side: the
    /// deepest project that holds it.
    fn of(&self, rel: &Path, new: bool) -> Owner {
        let nested = if new { &self.new } else { &self.old };
        let deepest = nested
            .iter()
            .filter(|dir| rel.starts_with(dir))
            .max_by_key(|dir| dir.components().count());
        match deepest {
            None => Owner::Own,
            Some(dir) if new || self.new.contains(dir) => Owner::Other,
            Some(dir) => {
                let key = crate::workspace::in_workspace(&self.own_key, dir);
                Owner::Vanished(dir.clone(), path_of(&key))
            }
        }
    }

    /// The nested project that holds `rel` on that side and is diffed from its own directory.
    fn other_of(&self, rel: &Path, new: bool) -> Option<PathBuf> {
        let nested = if new { &self.new } else { &self.old };
        match self.of(rel, new) {
            Owner::Other => nested
                .iter()
                .filter(|dir| rel.starts_with(dir))
                .max_by_key(|dir| dir.components().count())
                .cloned(),
            _ => None,
        }
    }

    /// The nested projects the comparison point holds and the compared side does not, unless
    /// one the compared side still holds encloses them: that one's diff reads them.
    fn vanished(&self) -> Vec<PathBuf> {
        self.old
            .iter()
            .filter(|dir| {
                !dir.ancestors()
                    .any(|up| self.new.iter().any(|kept| kept == up))
            })
            .cloned()
            .collect()
    }
}

/// The decision notes of the project at `dir`, relative to `root`, as one side holds them:
/// the files the `notes` list of its own `AGENTS.md` matches on that side, outside every
/// project nested in it, each with its text.
fn side_notes(root: &Path, rev: Option<&str>, dir: &Path) -> Result<Vec<(PathBuf, String)>> {
    // ยง n4fbh9vd4.f@t666x
    let read = |rels: &[PathBuf]| match rev {
        Some(rev) => git_show_all(root, rev, rels),
        None => rels.iter().map(|rel| read_worktree(root, rel)).collect(),
    };
    let agents = read(&[dir.join("AGENTS.md")]).pop().flatten();
    let notes = match rev {
        Some(_) => walk::Notes::at_commit(agents.as_deref()),
        None => walk::Notes::from_agents(agents.as_deref()),
    }
    .map_err(|e| anyhow::anyhow!("{}: {e}", dir.join("AGENTS.md").display()))?;
    let dir: PathBuf = dir
        .components()
        .filter(|c| !matches!(c, std::path::Component::CurDir))
        .collect();
    let listed: Vec<PathBuf> = match rev {
        Some(rev) => {
            // ยง r4dndth75.b@c458v
            let spec = if dir.as_os_str().is_empty() {
                ".".to_string()
            } else {
                path_of(&dir)
            };
            let listed = git_lines(root, &["ls-tree", "-r", "--name-only", rev, "--", &spec])?;
            let own = dir.join("AGENTS.md");
            let agents: Vec<PathBuf> = listed
                .iter()
                .filter(|rel| rel.file_name().is_some_and(|n| n == "AGENTS.md") && **rel != own)
                .cloned()
                .collect();
            let nested: Vec<PathBuf> = agents
                .iter()
                .zip(read(&agents))
                .filter(|(_, text)| text.as_deref().is_some_and(crate::scheme::has_block))
                .filter_map(|(rel, _)| rel.parent().map(Path::to_path_buf))
                .collect();
            listed
                .into_iter()
                .filter(|rel| !nested.iter().any(|n| rel.starts_with(n)))
                .collect()
        }
        None => walk::decision_files(&root.join(&dir))?
            .into_iter()
            .map(|path| path.strip_prefix(root).unwrap_or(&path).to_path_buf())
            .collect(),
    };
    let rels: Vec<PathBuf> = listed
        .into_iter()
        .filter(|rel| rel.strip_prefix(&dir).is_ok_and(|rel| notes.holds(rel)))
        .collect();
    let texts = read(&rels);
    Ok(rels
        .into_iter()
        .zip(texts)
        .filter_map(|(rel, text)| Some((rel, text?)))
        .collect())
}

/// The laws and cites of the notes `notes` that `owner` holds, each address qualified by the
/// key of a vanished project, so the same id in two projects never pairs.
fn scan_owned(
    notes: &[(PathBuf, String)],
    owner: &Owner,
    owner_of: impl Fn(&Path) -> Owner,
) -> Scan {
    let mut scan = Scan::default();
    for (rel, text) in notes.iter().filter(|(rel, _)| owner_of(rel) == *owner) {
        merge_scan(&mut scan, parse::scan_text(rel, text));
    }
    if let Owner::Vanished(_, key) = owner {
        for law in &mut scan.laws {
            law.id = format!("{key}:{}", law.id);
            for alias in &mut law.aliases {
                *alias = format!("{key}:{alias}");
            }
        }
        for ptr in &mut scan.pointers {
            ptr.project.get_or_insert_with(|| key.clone());
        }
    }
    scan
}

/// The laws of both sides, the marker changes, and the text of each touched code file on both
/// sides. A renamed code file is keyed by its new path, so its pins are weighed in place.
fn scan_sides(
    ws: &crate::workspace::Workspace,
    root: &Path,
    base: &str,
    paths: &[Touched],
) -> Result<(Scan, Scan, Vec<Change>, FileMap)> {
    let ends = diff_ends(root, base)?;
    let owners = Owners::read(ws, root, &ends)?;
    // ยง n4fbh9vd4.f@ed0kq
    let mut old = Scan::default();
    let mut new = Scan::default();
    let mut old_notes = BTreeSet::new();
    let mut new_notes = BTreeSet::new();
    let mut read_side = |rev: Option<&str>, dir: &Path, owner: Owner, is_new: bool| -> Result<()> {
        let notes = side_notes(root, rev, dir)?;
        let scan = scan_owned(&notes, &owner, |rel| owners.of(rel, is_new));
        let (into, seen) = if is_new {
            (&mut new, &mut new_notes)
        } else {
            (&mut old, &mut old_notes)
        };
        seen.extend(notes.into_iter().map(|(rel, _)| rel));
        merge_scan(into, scan);
        Ok(())
    };
    read_side(Some(&ends.old_rev), Path::new(""), Owner::Own, false)?;
    for dir in owners.vanished() {
        let owner = owners.of(&dir.join("AGENTS.md"), false);
        read_side(Some(&ends.old_rev), &dir, owner, false)?;
    }
    read_side(ends.new_rev.as_deref(), Path::new(""), Owner::Own, true)?;
    // ยง end n4fbh9vd4.f
    let remint = reminted(&old, &new);
    // ยง cme63msgx.c@3afzp
    let mut marker_changes = Vec::new();
    let mut files = FileMap::new();
    let old_paths: Vec<PathBuf> = paths.iter().map(|touched| touched.old.clone()).collect();
    let new_paths: Vec<PathBuf> = paths.iter().map(|touched| touched.new.clone()).collect();
    let olds = git_show_all(root, &ends.old_rev, &old_paths);
    let news = read_new_sides(root, ends.new_rev.as_deref(), &new_paths);
    for ((touched, old_text), new_text) in paths.iter().zip(olds).zip(news) {
        let old_owner = owners.of(&touched.old, false);
        let new_owner = owners.of(&touched.new, true);
        let old_text = old_text
            .filter(|_| old_owner != Owner::Other && !old_notes.contains(&touched.old))
            .map(|text| match &old_owner {
                Owner::Own => as_reminted(&touched.old, text, &remint),
                _ => text,
            });
        let new_text =
            new_text.filter(|_| new_owner != Owner::Other && !new_notes.contains(&touched.new));
        if old_text.is_none() && new_text.is_none() {
            continue;
        }
        let keys = [qualifier(&old_owner), qualifier(&new_owner)];
        let rel = &touched.new;
        marker_changes.extend(marker_diff(
            rel,
            [old_text.as_deref(), new_text.as_deref()],
            keys,
        ));
        files.insert(path_of(rel), (old_text, new_text));
    }
    // ยง end cme63msgx.c
    Ok((old, new, marker_changes, files))
}

/// The project key an unqualified marker of a file `owner` holds carries in this diff.
fn qualifier(owner: &Owner) -> Option<&str> {
    match owner {
        Owner::Vanished(_, key) => Some(key),
        _ => None,
    }
}

struct DiffEnds {
    old_rev: String,
    /// `None` means read the worktree (single-ref comparison).
    new_rev: Option<String>,
}

fn diff_ends(root: &Path, base: &str) -> Result<DiffEnds> {
    // ยง cme63msgx.b@2wvmp
    let end = |side: &str| match side.trim() {
        "" => "HEAD".to_string(),
        side => side.to_string(),
    };
    if let Some(pos) = base.find("...") {
        let (left, right) = (end(&base[..pos]), end(&base[pos + 3..]));
        let old_rev = git_stdout(root, &["merge-base", &left, &right])?;
        return Ok(DiffEnds {
            old_rev,
            new_rev: Some(right),
        });
    }
    if let Some(pos) = base.find("..") {
        return Ok(DiffEnds {
            old_rev: end(&base[..pos]),
            new_rev: Some(end(&base[pos + 2..])),
        });
    }
    Ok(DiffEnds {
        old_rev: base.to_string(),
        new_rev: None,
    })
}

/// The compared side of each of `rels`: the worktree, or the right end of a range.
fn read_new_sides(root: &Path, rev: Option<&str>, rels: &[PathBuf]) -> Vec<Option<String>> {
    // ยง cme63msgx.b@srtc1
    match rev {
        None => rels.iter().map(|rel| read_worktree(root, rel)).collect(),
        Some(rev) => git_show_all(root, rev, rels),
    }
}

fn merge_scan(into: &mut Scan, from: Scan) {
    into.laws.extend(from.laws);
    into.pointers.extend(from.pointers);
    into.form_errors.extend(from.form_errors);
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
enum Kind {
    Declared,
    Retired,
    /// The head of a law whose old id the compared side keeps as an alias anchor of it: its text
    /// on both sides, and the old id in its `why`, after `REMINTED_FROM`.
    Reminted,
    /// Struck or a tombstone at the comparison point, and gone: a published retirement removed.
    Removed,
    /// Active at the comparison point, and gone with no strike and no alias anchor keeping it.
    Deleted,
    Moved,
    Amended,
    Clause,
    /// A clause declared on a letter the comparison point held struck, a burned letter reused,
    /// or a law active again on an id it held struck.
    Reused,
    Cite,
    Marker,
    /// A marker over a changed span that kept its pin: its span on both sides.
    Drift,
    /// A drift whose pin digest moved, so an `accept` took the change: its span on both sides.
    Accepted,
    /// The unchanged text of a clause, recalled beside a drift.
    Recall,
    /// A law or a clause that is a draft on one side and owes its markers on the other, or that
    /// is new as a draft: its text on each side reads `draft` or `owed`.
    Draft,
    /// A law head that is a public promise on one side and plain on the other.
    Public,
    /// The context of a law, the prose between its head and its clauses, on each side.
    Context,
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
struct Change {
    address: String,
    kind: Kind,
    old_path: Option<String>,
    new_path: Option<String>,
    old_text: Option<String>,
    new_text: Option<String>,
    /// On a drift, each followed callee whose span reads differently on the two sides.
    callees: Vec<CalleeDiff>,
    /// The 1-based line of a marker on each side, when known, so two pins written alike in
    /// one file are each weighed at their own span.
    lines: [Option<usize>; 2],
    /// Why a drift reads as it does when its span and callees do not show it.
    why: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
struct CalleeDiff {
    name: String,
    path: String,
    old: Option<String>,
    new: Option<String>,
    /// Why a callee the comparison point followed is followed no longer.
    why: Option<String>,
    /// For a stretch the pin reads beyond its span rather than a callee, what it is: `name` is
    /// then its label and `path` the span's file.
    read: Option<span_lang::Read>,
}

impl Change {
    fn kind_name(&self) -> &'static str {
        match self.kind {
            Kind::Declared => "declared",
            Kind::Retired => "retired",
            Kind::Reminted => "reminted",
            Kind::Removed => "removed",
            Kind::Deleted => "deleted",
            Kind::Moved => "moved",
            Kind::Amended => "amended",
            Kind::Clause => "clause",
            Kind::Reused => "reused",
            Kind::Cite => "cite",
            Kind::Marker => "marker",
            Kind::Drift => "drift",
            Kind::Accepted => "accepted",
            Kind::Recall => "recall",
            Kind::Draft => "draft",
            Kind::Public => "public",
            Kind::Context => "context",
        }
    }

    fn is_marker(&self) -> bool {
        matches!(self.kind, Kind::Marker | Kind::Drift | Kind::Accepted)
    }
}

fn collect_law_changes<'a>(old: &'a Scan, new: &'a Scan) -> Vec<Change> {
    // ยง n4fbh9vd4@3pm44
    let old_laws = index_laws(old);
    let new_laws = index_laws(new);
    let carried = carried_ids(new);
    let remint = reminted(old, new);
    let mut ids: BTreeSet<&str> = BTreeSet::new();
    ids.extend(old_laws.keys().copied());
    ids.extend(new_laws.keys().copied());
    let mut out = Vec::new();
    for id in ids {
        // ยง n4fbh9vd4.a@4hjpv
        // A struck law is read as absent, so a strike is a retirement.
        let live =
            |laws: &BTreeMap<&str, &'a parse::Law>| laws.get(id).copied().filter(|l| !l.struck);
        let was = remint
            .iter()
            .find(|(_, now)| now.as_str() == id)
            .and_then(|(was, _)| Some((was, *old_laws.get(was.as_str())?)));
        match (live(&old_laws), live(&new_laws), was) {
            (Some(_), None, _) if remint.contains_key(id) => {}
            (None, Some(n), Some((was, o))) => {
                let shown = |law: &parse::Law| match attached_moved(&o.body, &n.body) {
                    true => law.pin_text(),
                    false => law.name.clone(),
                };
                out.push(Change {
                    address: id.to_string(),
                    kind: Kind::Reminted,
                    old_path: Some(path_of(&o.loc.path)),
                    new_path: Some(path_of(&n.loc.path)),
                    old_text: Some(shown(o)),
                    new_text: Some(shown(n)),
                    callees: Vec::new(),
                    lines: [None, None],
                    why: Some(format!("{REMINTED_FROM}{was}.")),
                });
                out.extend(clause_changes(id, o, n));
                out.extend(draft_changes(id, Some(o), n));
                out.extend(public_change(id, o, n));
                out.extend(context_change(id, Some(o), n, false));
            }
            (None, Some(n), None) => {
                let mut law = whole_law(id, n, None);
                if let Some(struck) = old_laws.get(id) {
                    // ยง zrj8yeg6g.d@1ssem
                    law[0] = Change {
                        kind: Kind::Reused,
                        old_path: Some(path_of(&struck.loc.path)),
                        old_text: Some(format!("~~{}~~", struck.name)),
                        new_text: Some(format!(
                            "{}\nRevives ยง {id}, struck at the comparison point: a marker or a cite of the retired law now names it again.",
                            n.name
                        )),
                        ..law[0].clone()
                    };
                    // A clause the struck law held reads against its last published text.
                    let (held, now) = (index_clauses(struck), index_clauses(n));
                    for change in law.iter_mut().skip(1) {
                        let letter = change.address.rsplit('.').next().unwrap_or_default();
                        let (Some(was), Some(is)) =
                            (held.get(letter).filter(|c| !c.struck), now.get(letter))
                        else {
                            continue;
                        };
                        let canon = |c: &parse::Clause| crate::hash::pin_canon(&c.pin_body());
                        if canon(was) != canon(is) {
                            change.old_path = Some(path_of(&was.loc.path));
                            change.old_text = Some(was.text.clone());
                        }
                    }
                }
                out.extend(law);
                out.extend(draft_changes(id, old_laws.get(id).copied(), n));
                out.extend(context_change(id, old_laws.get(id).copied(), n, false));
            }
            (Some(o), None, _) if carried.contains(id) => {
                out.extend(whole_law(id, o, Some(Kind::Retired)))
            }
            (Some(o), None, _) => out.extend(whole_law(id, o, Some(Kind::Deleted))),
            (Some(o), Some(n), _) => {
                let op = path_of(&o.loc.path);
                let np = path_of(&n.loc.path);
                let head_shown = op != np || o.name != n.name || attached_moved(&o.body, &n.body);
                out.extend(context_change(id, Some(o), n, !head_shown));
                if op != np {
                    out.push(Change {
                        address: id.to_string(),
                        kind: Kind::Moved,
                        old_path: Some(op.clone()),
                        new_path: Some(np.clone()),
                        old_text: Some(o.name.clone()),
                        new_text: Some(n.name.clone()),
                        callees: Vec::new(),
                        lines: [None, None],
                        why: None,
                    });
                } else if o.name != n.name || attached_moved(&o.body, &n.body) {
                    // ยง n4fbh9vd4.c@6zdmr
                    let shown = |law: &parse::Law| match attached_moved(&o.body, &n.body) {
                        true => law.pin_text(),
                        false => law.name.clone(),
                    };
                    out.push(Change {
                        address: id.to_string(),
                        kind: Kind::Amended,
                        old_path: Some(op.clone()),
                        new_path: Some(np.clone()),
                        old_text: Some(shown(o)),
                        new_text: Some(shown(n)),
                        callees: Vec::new(),
                        lines: [None, None],
                        why: None,
                    });
                }
                out.extend(clause_changes(id, o, n));
                out.extend(draft_changes(id, Some(o), n));
                out.extend(public_change(id, o, n));
            }
            (None, None, _) => {}
        }
    }
    out
}

/// Each address of `new`, active, whose draft state the comparison point does not share: made a
/// draft, no longer one, or new as one, with its text on each side. A struck law at the point
/// holds no state.
fn draft_changes(id: &str, old: Option<&parse::Law>, new: &parse::Law) -> Vec<Change> {
    // ยง n4fbh9vd4.g@wxcq6
    let old = old.filter(|law| !law.struck);
    let change = |address: String, was: Option<(bool, &str)>, is: (bool, &str), path: &Path| {
        let why = match (was.map(|w| w.0), is.0) {
            (Some(false), true) => DRAFT_MADE,
            (Some(true), false) => DRAFT_DROPPED,
            (None, true) => DRAFT_NEW,
            _ => return None,
        };
        Some(Change {
            address,
            kind: Kind::Draft,
            old_path: was.map(|_| path_of(path)),
            new_path: Some(path_of(path)),
            old_text: was.map(|w| w.1.to_string()),
            new_text: Some(is.1.to_string()),
            callees: Vec::new(),
            lines: [None, None],
            why: Some(why.to_string()),
        })
    };
    fn head(law: &parse::Law) -> (bool, &str) {
        (law.draft, law.name.as_str())
    }
    let mut out: Vec<Change> = change(id.to_string(), old.map(head), head(new), &new.loc.path)
        .into_iter()
        .collect();
    for clause in new.clauses.iter().filter(|c| !c.struck) {
        let Some(letter) = &clause.letter else {
            continue;
        };
        let was = old.and_then(|law| {
            law.clauses
                .iter()
                .find(|c| c.letter.as_ref() == Some(letter) && !c.struck)
                .map(|c| (c.draft, c.text.as_str()))
        });
        out.extend(change(
            format!("{id}.{letter}"),
            was,
            (clause.draft, clause.text.as_str()),
            &clause.loc.path,
        ));
    }
    out
}

/// The head of `new` whose `!` the comparison point, holding `old` active, did not write: made a
/// public promise, or made plain.
fn public_change(id: &str, old: &parse::Law, new: &parse::Law) -> Option<Change> {
    // ยง n4fbh9vd4.h@pdvdh
    let why = match (old.public, new.public) {
        (false, true) => PUBLIC_MADE,
        (true, false) => PUBLIC_DROPPED,
        _ => return None,
    };
    Some(Change {
        address: id.to_string(),
        kind: Kind::Public,
        old_path: Some(path_of(&old.loc.path)),
        new_path: Some(path_of(&new.loc.path)),
        old_text: Some(old.name.clone()),
        new_text: Some(new.name.clone()),
        callees: Vec::new(),
        lines: [None, None],
        why: Some(why.to_string()),
    })
}

/// The context of `new` when it reads otherwise than that of `old`, a law the comparison point
/// may not hold, and with `recall` the unchanged head beside it, so the reviewer reads the law
/// the context stands under.
fn context_change(
    id: &str,
    old: Option<&parse::Law>,
    new: &parse::Law,
    recall: bool,
) -> Vec<Change> {
    // ยง n4fbh9vd4.i@0agbk
    let was = old.map_or("", |law| law.context.as_str());
    if !attached_moved(was, &new.context) {
        return Vec::new();
    }
    let text = |context: &str| (!context.is_empty()).then(|| context.to_string());
    let mut out = vec![Change {
        address: id.to_string(),
        kind: Kind::Context,
        old_path: old.map(|law| path_of(&law.loc.path)),
        new_path: Some(path_of(&new.loc.path)),
        old_text: text(was),
        new_text: text(&new.context),
        callees: Vec::new(),
        lines: [None, None],
        why: Some(CONTEXT_MOVED.to_string()),
    }];
    if recall {
        out.push(Change {
            kind: Kind::Recall,
            old_text: Some(new.pin_text()),
            new_text: Some(new.pin_text()),
            why: None,
            ..out[0].clone()
        });
    }
    out
}

pub(crate) const CONTEXT_MOVED: &str =
    "Its context changed: the prose between its head and its clauses, which binds nothing and no pin hashes, reads otherwise.";

pub(crate) const PUBLIC_MADE: &str =
    "Made a public promise: it owes a documentation marker in a file the `docs` list matches.";
pub(crate) const PUBLIC_DROPPED: &str = "Made plain: it owes no documentation marker.";
pub(crate) const DRAFT_MADE: &str = "Made a draft: it owes no marker and is not pinned.";
pub(crate) const DRAFT_DROPPED: &str = "No longer a draft: it owes its markers.";
pub(crate) const DRAFT_NEW: &str = "A draft: it owes no marker and is not pinned.";

/// The ids and alias anchors the laws of a side carry.
fn carried_ids(scan: &Scan) -> BTreeSet<&str> {
    scan.laws
        .iter()
        .flat_map(|law| std::iter::once(&law.id).chain(&law.aliases))
        .map(String::as_str)
        .collect()
}

/// What the head of a reminted law says of the id it replaced, the old id after it.
pub(crate) const REMINTED_FROM: &str = "Reminted from ยง ";

/// Each law id active at the comparison point that the compared side declares no more and keeps
/// as an alias anchor of a head the point did not hold, with that head's id: a remint. A head
/// that keeps two such ids merged two laws, and reads as no remint.
fn reminted(old: &Scan, new: &Scan) -> BTreeMap<String, String> {
    // ยง n4fbh9vd4.a@2wzfj
    let old_ids: BTreeSet<&str> = old.laws.iter().map(|law| law.id.as_str()).collect();
    let old_live: BTreeSet<&str> = old
        .laws
        .iter()
        .filter(|law| !law.struck)
        .map(|law| law.id.as_str())
        .collect();
    let new_ids: BTreeSet<&str> = new.laws.iter().map(|law| law.id.as_str()).collect();
    let mut out = BTreeMap::new();
    for law in new.laws.iter().filter(|law| !law.struck) {
        if old_ids.contains(law.id.as_str()) {
            continue;
        }
        let was: Vec<&String> = law
            .aliases
            .iter()
            .filter(|alias| old_live.contains(alias.as_str()) && !new_ids.contains(alias.as_str()))
            .collect();
        if let [was] = was.as_slice() {
            out.insert((*was).clone(), law.id.clone());
        }
    }
    out
}

/// `text` with each unqualified marker and end that names a reminted id written under the id
/// that replaced it, so the comparison point reads the pins of a remint under the address the
/// compared side carries and weighs each as one pin, not as one lost beside one added.
fn as_reminted(rel: &Path, text: String, remint: &BTreeMap<String, String>) -> String {
    // ยง n4fbh9vd4.a@1v57e
    let rows: BTreeSet<usize> = span::marker_rows(rel, &text, None)
        .into_iter()
        .filter(|row| {
            row.markers
                .iter()
                .chain(&row.end)
                .any(|m| m.project.is_none() && remint.contains_key(&m.id))
        })
        .map(|row| row.idx)
        .collect();
    if rows.is_empty() {
        return text;
    }
    let token = |c: char| c.is_ascii_alphanumeric() || c == ':' || c == '/';
    text.split_inclusive('\n')
        .enumerate()
        .map(|(idx, line)| {
            if !rows.contains(&idx) {
                return line.to_string();
            }
            let mut line = line.to_string();
            for (was, now) in remint {
                let mut at = 0;
                while let Some(found) = line[at..].find(was.as_str()).map(|i| i + at) {
                    let end = found + was.len();
                    let alone = !line[..found].ends_with(token) && !line[end..].starts_with(token);
                    if alone {
                        line.replace_range(found..end, now);
                    }
                    at = found + 1;
                }
            }
            line
        })
        .collect()
}

/// A law active on one side only, with each of its active clauses: retired or deleted from
/// the comparison point, as `gone` names, or declared on the compared side when it is `None`.
/// A deleted law shows its full last text, and every clause it held.
fn whole_law(id: &str, law: &parse::Law, gone: Option<Kind>) -> Vec<Change> {
    // ยง n4fbh9vd4.a@tg70m
    let side = |path: &Path, text: &str| {
        let (path, text) = (Some(path_of(path)), Some(text.to_string()));
        if gone.is_some() {
            (path, None, text, None)
        } else {
            (None, path, None, text)
        }
    };
    let deleted = gone == Some(Kind::Deleted);
    let text = if deleted {
        last_text(law)
    } else {
        law.name.clone()
    };
    let (old_path, new_path, old_text, new_text) = side(&law.loc.path, &text);
    let mut out = vec![Change {
        address: id.to_string(),
        kind: gone.unwrap_or(Kind::Declared),
        old_path,
        new_path,
        old_text,
        new_text,
        callees: Vec::new(),
        lines: [None, None],
        why: None,
    }];
    for clause in law
        .clauses
        .iter()
        .filter(|clause| deleted || !clause.struck)
    {
        let Some(letter) = &clause.letter else {
            continue;
        };
        let text = if deleted {
            clause_last_text(clause)
        } else {
            clause.text.clone()
        };
        let (old_path, new_path, old_text, new_text) = side(&clause.loc.path, &text);
        out.push(Change {
            address: format!("{id}.{letter}"),
            kind: gone.unwrap_or(Kind::Clause),
            old_path,
            new_path,
            old_text,
            new_text,
            callees: Vec::new(),
            lines: [None, None],
            why: None,
        });
    }
    out
}

/// The text a law last read as: its head, struck as written, and the body under it.
fn last_text(law: &parse::Law) -> String {
    let head = if law.struck {
        format!("~~{}~~", law.name)
    } else {
        law.name.clone()
    };
    if law.body.is_empty() {
        head
    } else {
        format!("{head}\n{}", law.body)
    }
}

/// The text a clause last read as: its item, struck or as a tombstone, and its attached body.
fn clause_last_text(clause: &parse::Clause) -> String {
    if clause.body.is_empty() {
        clause.text.clone()
    } else {
        clause.body.clone()
    }
}

/// What the comparison point wrote and the compared side deleted, beyond the active laws and
/// clauses `collect_law_changes` retires or deletes: a struck law, a struck or tombstoned
/// clause, and an alias anchor no law carries any more. What the comparison point held struck
/// is removed, with its full last text, and an alias anchor of an active law is deleted.
fn collect_deleted(old: &Scan, new: &Scan) -> Vec<Change> {
    // ยง n4fbh9vd4.b@ywhht
    let new_laws = index_laws(new);
    let carried = carried_ids(new);
    let remint = reminted(old, new);
    let gone_as = |kind: Kind, address: String, path: &Path, text: String| Change {
        address,
        kind,
        old_path: Some(path_of(path)),
        new_path: None,
        old_text: Some(text),
        new_text: None,
        callees: Vec::new(),
        lines: [None, None],
        why: None,
    };
    let mut out = Vec::new();
    for law in &old.laws {
        let alias_kind = if law.struck {
            Kind::Removed
        } else {
            Kind::Deleted
        };
        for alias in law.aliases.iter().filter(|a| !carried.contains(a.as_str())) {
            let text = format!("Alias anchor of ยง {}.", law.id);
            out.push(gone_as(alias_kind, alias.clone(), &law.loc.path, text));
        }
        let id = remint.get(&law.id).unwrap_or(&law.id);
        let Some(now) = new_laws.get(id.as_str()) else {
            if law.struck {
                out.push(gone_as(
                    Kind::Removed,
                    law.id.clone(),
                    &law.loc.path,
                    last_text(law),
                ));
            }
            // An active law deleted lists its struck clauses with its active ones; a reworded
            // one keeps them under its new id, retired as before.
            let kind = if law.struck {
                Kind::Removed
            } else if carried.contains(law.id.as_str()) {
                Kind::Retired
            } else {
                continue;
            };
            for clause in law.clauses.iter().filter(|c| law.struck || c.struck) {
                if let Some(letter) = &clause.letter {
                    let address = format!("{}.{letter}", law.id);
                    let text = if kind == Kind::Retired {
                        clause.text.clone()
                    } else {
                        clause_last_text(clause)
                    };
                    out.push(gone_as(kind, address, &clause.loc.path, text));
                }
            }
            continue;
        };
        for clause in &law.clauses {
            let Some(letter) = &clause.letter else {
                continue;
            };
            let gone = !now
                .clauses
                .iter()
                .any(|c| c.letter.as_ref() == Some(letter));
            if gone && (law.struck || clause.struck) {
                let address = format!("{id}.{letter}");
                let text = clause_last_text(clause);
                out.push(gone_as(Kind::Removed, address, &clause.loc.path, text));
            }
        }
    }
    out
}

fn clause_changes<'a>(id: &str, old: &'a parse::Law, new: &'a parse::Law) -> Vec<Change> {
    let old_map = index_clauses(old);
    let new_map = index_clauses(new);
    let mut letters: BTreeSet<&str> = BTreeSet::new();
    letters.extend(old_map.keys().copied());
    letters.extend(new_map.keys().copied());
    let mut out = Vec::new();
    for letter in letters {
        // ยง n4fbh9vd4.a@30kvy
        let address = format!("{id}.{letter}");
        let live = |clauses: &BTreeMap<&str, &'a parse::Clause>| {
            clauses.get(letter).copied().filter(|c| !c.struck)
        };
        match (live(&old_map), live(&new_map)) {
            (None, Some(n)) if old_map.contains_key(letter) => out.push(Change {
                address,
                kind: Kind::Reused,
                old_path: Some(path_of(&old_map[letter].loc.path)),
                new_path: Some(path_of(&n.loc.path)),
                old_text: Some(format!("~~{}~~", old_map[letter].text)),
                new_text: Some(format!(
                    "{}\nReuses ({letter}), burned at the comparison point: a marker of the struck clause now names this one.",
                    n.text
                )),
                callees: Vec::new(),
                lines: [None, None],
                why: None,
            }),
            (None, Some(n)) => out.push(Change {
                address,
                kind: Kind::Clause,
                old_path: None,
                new_path: Some(path_of(&n.loc.path)),
                old_text: None,
                new_text: Some(n.text.clone()),
                callees: Vec::new(),
                lines: [None, None],
                why: None,
            }),
            // ยง n4fbh9vd4.b@njnd3
            (Some(o), None) if !new_map.contains_key(letter) => out.push(Change {
                address,
                kind: Kind::Deleted,
                old_path: Some(path_of(&o.loc.path)),
                new_path: None,
                old_text: Some(clause_last_text(o)),
                new_text: None,
                callees: Vec::new(),
                lines: [None, None],
                why: None,
            }),
            // ยง end n4fbh9vd4.b
            (Some(o), None) => out.push(Change {
                address,
                kind: Kind::Retired,
                old_path: Some(path_of(&o.loc.path)),
                new_path: None,
                old_text: Some(o.text.clone()),
                new_text: None,
                callees: Vec::new(),
                lines: [None, None],
                why: None,
            }),
            (Some(o), Some(n))
                if o.text != n.text || attached_moved(&o.pin_body(), &n.pin_body()) =>
            {
                // ยง n4fbh9vd4.c@kcgk3
                // A row clause reads under its header with its letter cell, so it aligns with it.
                let shown = |clause: &parse::Clause| {
                    match attached_moved(&o.pin_body(), &n.pin_body()) {
                        true if !clause.header.is_empty() => {
                            format!("{}\n{}", clause.header, clause.text)
                        }
                        true => clause.pin_body(),
                        false => clause.text.clone(),
                    }
                };
                out.push(Change {
                    address,
                    kind: Kind::Clause,
                    old_path: Some(path_of(&o.loc.path)),
                    new_path: Some(path_of(&n.loc.path)),
                    old_text: Some(shown(o)),
                    new_text: Some(shown(n)),
                    callees: Vec::new(),
                    lines: [None, None],
                    why: None,
                })
            }
            _ => {}
        }
    }
    out
}

/// Whether the text attached under a head, or a clause pin binds, reads otherwise on the two
/// sides as a pin reads it, whitespace collapsed.
fn attached_moved(old: &str, new: &str) -> bool {
    crate::hash::pin_canon(old) != crate::hash::pin_canon(new)
}

fn collect_pointer_changes(old: &Scan, new: &Scan) -> Vec<Change> {
    // ยง n4fbh9vd4@37c8g
    let remint = reminted(old, new);
    // A pointer the remint rewrote in place moved nothing for the reviewer.
    let old_set: BTreeSet<PointerKey> = pointer_keys(old)
        .into_iter()
        .map(|mut key| {
            let (id, letter) = split_address(&key.address);
            if let Some(now) = remint.get(&id) {
                key.line = key.line.replace(&id, now);
                key.address = match letter {
                    Some(letter) => format!("{now}.{letter}"),
                    None => now.clone(),
                };
            }
            key
        })
        .collect();
    let new_set = pointer_keys(new);
    let mut out = Vec::new();
    for key in old_set.difference(&new_set) {
        out.push(Change {
            address: key.address.clone(),
            kind: pointer_kind(key.kind),
            old_path: Some(key.path.clone()),
            new_path: None,
            old_text: Some(key.line.clone()),
            new_text: None,
            callees: Vec::new(),
            lines: [None, None],
            why: None,
        });
    }
    for key in new_set.difference(&old_set) {
        out.push(Change {
            address: key.address.clone(),
            kind: pointer_kind(key.kind),
            old_path: None,
            new_path: Some(key.path.clone()),
            old_text: None,
            new_text: Some(key.line.clone()),
            callees: Vec::new(),
            lines: [None, None],
            why: None,
        });
    }
    out
}

fn pointer_kind(kind: PointerKind) -> Kind {
    match kind {
        PointerKind::Implements => Kind::Marker,
        PointerKind::Cite => Kind::Cite,
    }
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
struct PointerKey {
    kind: PointerKind,
    address: String,
    path: String,
    line: String,
}

fn pointer_keys(scan: &Scan) -> BTreeSet<PointerKey> {
    scan.pointers
        .iter()
        .map(|ptr| {
            let local = match &ptr.target {
                Target::Stable {
                    id,
                    letter: Some(letter),
                } => format!("{id}.{letter}"),
                Target::Stable { id, letter: None } => id.clone(),
                Target::Display { clause, .. } => match clause {
                    Some(letter) => format!("{}.{}", ptr.name, letter),
                    None => ptr.name.clone(),
                },
            };
            let address = match &ptr.project {
                Some(project) => format!("{project}:{local}"),
                None => local,
            };
            PointerKey {
                kind: ptr.kind,
                address,
                path: path_of(&ptr.loc.path),
                line: format!("{:?} ยง {}", ptr.kind, ptr.name),
            }
        })
        .collect()
}

/// The marker changes of one file, `[old, new]` its two sides, each unqualified marker of a side
/// qualified by that side's key when it has one.
fn marker_diff(
    path: &Path,
    [old, new]: [Option<&str>; 2],
    [old_key, new_key]: [Option<&str>; 2],
) -> Vec<Change> {
    // ยง n4fbh9vd4@g8tep
    let old_map = marker_pins(path, old.unwrap_or(""), old_key);
    let new_map = marker_pins(path, new.unwrap_or(""), new_key);
    let rel = path_of(path);
    let mut keys = BTreeSet::new();
    keys.extend(old_map.keys().cloned());
    keys.extend(new_map.keys().cloned());
    let parsed = [std::cell::OnceCell::new(), std::cell::OnceCell::new()];
    let punched = |side: usize, line: usize| -> Option<String> {
        let text = [old, new][side]?;
        if span_lang::lang_for_path(path).is_none() {
            return extract_punched(path, text, line);
        }
        let markers = parsed[side].get_or_init(|| {
            span::CodeFile::new(path.to_path_buf(), text.to_string()).span_markers()
        });
        punched_in(text, markers, line).map(|(span, _, _)| span)
    };
    let mut out = Vec::new();
    let change = |key: &str, old: Option<(usize, &str)>, new: Option<(usize, &str)>| Change {
        address: key.to_string(),
        kind: Kind::Marker,
        old_path: old.map(|_| rel.clone()),
        new_path: new.map(|_| rel.clone()),
        old_text: old.map(|(_, text)| text.to_string()),
        new_text: new.map(|(_, text)| text.to_string()),
        callees: Vec::new(),
        lines: [old.map(|(line, _)| line), new.map(|(line, _)| line)],
        why: None,
    };
    for key in keys {
        let mut old_left = old_map.get(&key).cloned().unwrap_or_default();
        let mut new_left = new_map.get(&key).cloned().unwrap_or_default();
        let mut shared = Vec::new();
        old_left.retain(|(line, text)| {
            match new_left.iter().position(|(_, other)| other == text) {
                Some(at) => {
                    shared.push((*line, new_left.remove(at).0, text.clone()));
                    false
                }
                None => true,
            }
        });
        for (old_line, new_line, text) in shared {
            // ยง n4fbh9vd4.c@h0dd4
            // A pin that kept its token is weighed by `sort_markers`, callees included.
            if is_pinned(&text) || span_moved(path, old, new, old_line, new_line) {
                out.push(change(
                    &key,
                    Some((old_line, &text)),
                    Some((new_line, &text)),
                ));
            }
        }
        // Pairing reads spans only when it has a choice to make, since each side parses once.
        let choice = !old_left.is_empty()
            && !new_left.is_empty()
            && (old_left.len(), new_left.len()) != (1, 1);
        let spans = |side: usize, left: &[(usize, String)]| -> Vec<Option<String>> {
            left.iter()
                .map(|(line, _)| choice.then(|| punched(side, *line)).flatten())
                .collect()
        };
        let (old_spans, new_spans) = (spans(0, &old_left), spans(1, &new_left));
        for (o, n) in pair_spans(&old_spans, &new_spans) {
            out.push(change(
                &key,
                o.map(|i| (old_left[i].0, old_left[i].1.as_str())),
                n.map(|j| (new_left[j].0, new_left[j].1.as_str())),
            ));
        }
    }
    out
}

/// Pairs the pins of one address on the two sides of a file: first each pin whose span reads
/// the same but for digests, then the rest in file order when as many remain on each side.
/// Any other pin stands alone, removed or added.
fn pair_spans(
    old: &[Option<String>],
    new: &[Option<String>],
) -> Vec<(Option<usize>, Option<usize>)> {
    // ยง yjrm4q97t.a@zk3cp
    let mut pairs = Vec::new();
    let mut new_free: Vec<usize> = (0..new.len()).collect();
    let mut old_free = Vec::new();
    for (i, span) in old.iter().enumerate() {
        let same = span.as_ref().and_then(|span| {
            let span = strip_digests(span);
            new_free
                .iter()
                .position(|&j| new[j].as_ref().is_some_and(|n| strip_digests(n) == span))
        });
        match same {
            Some(at) => pairs.push((Some(i), Some(new_free.remove(at)))),
            None => old_free.push(i),
        }
    }
    if old_free.len() == new_free.len() {
        pairs.extend(
            old_free
                .into_iter()
                .zip(new_free)
                .map(|(i, j)| (Some(i), Some(j))),
        );
    } else {
        pairs.extend(old_free.into_iter().map(|i| (Some(i), None)));
        pairs.extend(new_free.into_iter().map(|j| (None, Some(j))));
    }
    pairs.sort_by_key(|&(i, j)| (j, i));
    pairs
}

/// Whether the span under a bare marker that kept its text reads differently on the two sides.
fn span_moved(
    path: &Path,
    old: Option<&str>,
    new: Option<&str>,
    old_line: usize,
    new_line: usize,
) -> bool {
    let (Some(old), Some(new)) = (old, new) else {
        return false;
    };
    let old_span = extract_punched(path, old, old_line);
    old_span.is_some() && old_span != extract_punched(path, new, new_line)
}

fn is_pinned(line: &str) -> bool {
    marker::markers_in_line(line)
        .iter()
        .any(|marker| marker.digest.is_some())
}

/// Each address's markers in file order: the 1-based line and the trimmed marker line.
/// A marker-shaped line inside a markdown fence is an example, not a marker, as `check` reads it.
fn marker_pins(
    path: &Path,
    text: &str,
    key: Option<&str>,
) -> BTreeMap<String, Vec<(usize, String)>> {
    let mut out: BTreeMap<String, Vec<(usize, String)>> = BTreeMap::new();
    for row in span::marker_rows(path, text, None) {
        for marker in row.markers {
            out.entry(qualified(marker, key))
                .or_default()
                .push((row.idx + 1, row.line.trim().to_string()));
        }
    }
    out
}

/// The address of `marker`, an unqualified one under `key` when given.
fn qualified(mut marker: marker::MarkerAddr, key: Option<&str>) -> String {
    if marker.project.is_none() {
        marker.project = key.map(str::to_string);
    }
    marker.display()
}

fn index_laws(scan: &Scan) -> BTreeMap<&str, &parse::Law> {
    let mut out = BTreeMap::new();
    for law in &scan.laws {
        out.insert(law.id.as_str(), law);
    }
    out
}

fn index_clauses(art: &parse::Law) -> BTreeMap<&str, &parse::Clause> {
    let mut out = BTreeMap::new();
    for al in &art.clauses {
        if let Some(letter) = &al.letter {
            out.insert(letter.as_str(), al);
        }
    }
    out
}

fn path_of(path: &Path) -> String {
    path.to_string_lossy().replace('\\', "/")
}

/// How a project's paths and addresses read from the workspace root.
struct Shown<'a> {
    prefix: &'a str,
    key: &'a Option<String>,
    /// The project's public documentation, where a pin guards a doc section.
    docs: &'a crate::walk::Patterns,
}

/// The review of `changes` alone, as a test reads it.
#[cfg(test)]
fn review_of(
    changes: &[Change],
    files: &FileMap,
    follow: &FollowIndex,
    shown: &str,
) -> review::Review {
    let shown = Shown {
        prefix: shown,
        key: &None,
        docs: &crate::walk::Patterns::default(),
    };
    let rules = review::law_entries(changes, files, follow, &Callers::new(), &shown);
    review::Review::gather("HEAD".into(), Vec::new(), 0, Vec::new(), rules, Vec::new())
}

#[cfg(test)]
fn render_diff(changes: &[Change]) -> String {
    render_diff_with(changes, &BTreeMap::new())
}

#[cfg(test)]
fn render_diff_with(changes: &[Change], files: &FileMap) -> String {
    render_diff_follow(changes, files, &FollowIndex::default(), "")
}

#[cfg(test)]
fn render_diff_follow(
    changes: &[Change],
    files: &FileMap,
    follow: &FollowIndex,
    shown: &str,
) -> String {
    review::review_markdown(&review_of(changes, files, follow, shown))
}

#[cfg(test)]
fn diff_json(root: &Path, changes: &[Change], folded: usize) -> String {
    let mut review = review_of(changes, &FileMap::new(), &FollowIndex::default(), "");
    review.folded = folded;
    let ids: Vec<&str> = review.rules.iter().map(|rule| local_id(&rule.id)).collect();
    review::review_json(&review, &crate::meta::declared(root, &ids))
}

/// The markers of each file of a tested language with their spans, on the comparison side
/// then the compared side, parsed once for every pin of every patch.
type ParsedMap = BTreeMap<String, [Option<Vec<span::SpanMarker>>; 2]>;

fn parse_files(files: &FileMap) -> ParsedMap {
    let mut jobs = Vec::new();
    for (path, (old, new)) in files {
        if span_lang::lang_for_path(Path::new(path)).is_none() {
            continue;
        }
        for (side, text) in [old, new].into_iter().enumerate() {
            if let Some(text) = text {
                jobs.push((path.clone(), side, text.clone()));
            }
        }
    }
    let done = crate::par::map(
        jobs,
        |(_, _, text)| text.len(),
        |(path, side, text)| {
            let markers = span::CodeFile::new(PathBuf::from(&path), text).span_markers();
            (path, side, markers)
        },
    );
    let mut out = ParsedMap::new();
    for (path, side, markers) in done {
        out.entry(path).or_default()[side] = Some(markers);
    }
    out
}

fn joined_notes(first: Option<String>, second: Option<String>) -> Option<String> {
    match (first, second) {
        (Some(first), Some(second)) => Some(format!("{first}\n{second}")),
        (first, second) => first.or(second),
    }
}

/// The lines of the pins of `address` in `rel`. An address qualified with the key of a project
/// that holds `rel`, one the comparison point held and the compared side does not, also names
/// the unqualified pins that project wrote of it.
fn pin_lines(rel: &Path, text: &str, address: &str) -> Vec<usize> {
    let own = address.rsplit_once(':').and_then(|(key, local)| {
        rel.ancestors()
            .skip(1)
            .any(|dir| !dir.as_os_str().is_empty() && Path::new(key).ends_with(dir))
            .then_some(local)
    });
    span::pinned_in_text(rel, text, None)
        .into_iter()
        .filter(|pin| {
            let shown = pin.addr.display();
            shown == address || (pin.addr.project.is_none() && Some(shown.as_str()) == own)
        })
        .map(|pin| pin.line)
        .collect()
}

fn extract_punched(path: &Path, text: &str, marker_line: usize) -> Option<String> {
    // ยง t0jfkh0n1@5rsdr
    let keep = punched_lines(path, text, marker_line)?;
    let mut out = String::new();
    for (idx, line) in text.lines().enumerate() {
        if keep.contains(&(idx + 1)) {
            out.push_str(line);
            out.push('\n');
        }
    }
    Some(out)
}

fn punched_lines(path: &Path, text: &str, marker_line: usize) -> Option<BTreeSet<usize>> {
    // ยง yjrm4q97t.a@eckzv
    let (start, end) = line_span(path, text, marker_line)?;
    let outer = nest_extent(path, text, marker_line)?;
    let mut keep: BTreeSet<usize> = (start..=end).collect();
    for pin in span::pinned_in_text(path, text, None) {
        // ยง rr512n5e2.c@fmafp
        if pin.line == marker_line {
            continue;
        }
        let (Some((inner_start, inner_end)), Some(inner)) = (
            line_span(path, text, pin.line),
            nest_extent(path, text, pin.line),
        ) else {
            continue;
        };
        if span::nests_in(inner, outer) {
            for line in inner_start..=inner_end {
                keep.remove(&line);
            }
        }
    }
    keep.insert(marker_line);
    Some(keep)
}

/// The extent nesting compares: bytes under a tested grammar, lines under the fallback.
fn nest_extent(path: &Path, source: &str, marker_line: usize) -> Option<(usize, usize)> {
    match span_lang::lang_for_path(path) {
        Some(lang) => span_lang::span_bytes(lang, path, source, marker_line),
        None => line_span(path, source, marker_line),
    }
}

fn line_span(path: &Path, source: &str, marker_line: usize) -> Option<(usize, usize)> {
    match span_lang::lang_for_path(path) {
        Some(lang) => {
            let (start, end) = span_lang::span_bytes(lang, path, source, marker_line)?;
            if end <= start {
                return None;
            }
            Some((byte_line(source, start), byte_line(source, end - 1)))
        }
        None => {
            let ends = span::file_ends(path, source);
            if let Some(&end_idx) = ends.pairs.get(&marker_line.checked_sub(1)?) {
                return Some((marker_line + 1, end_idx + 1));
            }
            let last = source.lines().count();
            if marker_line >= last {
                return None;
            }
            Some((marker_line + 1, last))
        }
    }
}

fn byte_line(source: &str, byte: usize) -> usize {
    let byte = byte.min(source.len());
    source.as_bytes()[..byte]
        .iter()
        .filter(|b| **b == b'\n')
        .count()
        + 1
}

/// `old` against `new` as one line each, ` ` for context, `-` and `+` for the rest. Each
/// side is aligned on its own text: a run is context only where both sides read it.
fn aligned_lines(old_lines: &[String], new_lines: &[String]) -> Vec<String> {
    // ยง t0jfkh0n1@xqjqq
    let mut out = Vec::new();
    let mut i = 0;
    let mut j = 0;
    while i < old_lines.len() || j < new_lines.len() {
        if i < old_lines.len() && j < new_lines.len() && old_lines[i] == new_lines[j] {
            out.push(format!(" {}", old_lines[i]));
            i += 1;
            j += 1;
            continue;
        }
        let mut removed = Vec::new();
        let mut added = Vec::new();
        while i < old_lines.len() && (j >= new_lines.len() || old_lines[i] != new_lines[j]) {
            if let Some(pos) = new_lines[j..].iter().position(|l| l == &old_lines[i]) {
                added.extend(new_lines[j..j + pos].iter().map(|l| format!("+{l}")));
                j += pos;
                break;
            }
            removed.push(format!("-{}", old_lines[i]));
            i += 1;
        }
        while j < new_lines.len() && (i >= old_lines.len() || old_lines[i] != new_lines[j]) {
            if let Some(pos) = old_lines[i..].iter().position(|l| l == &new_lines[j]) {
                removed.extend(old_lines[i..i + pos].iter().map(|l| format!("-{l}")));
                i += pos;
                break;
            }
            added.push(format!("+{}", new_lines[j]));
            j += 1;
        }
        if removed.is_empty() && added.is_empty() {
            break;
        }
        out.extend(removed);
        out.extend(added);
    }
    out
}

fn delta_available() -> bool {
    Command::new("delta")
        .arg("--version")
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .status()
        .map(|s| s.success())
        .unwrap_or(false)
}

fn emit_diff_stream(diff: &str) -> Result<()> {
    // ยง t0jfkh0n1@qsd6e
    if diff.is_empty() {
        return Ok(());
    }
    if list_tty::is_tty_stdout() && delta_available() {
        return emit_delta(diff);
    }
    if list_tty::is_tty_stdout() {
        return list_tty::page(diff);
    }
    print!("{diff}");
    Ok(())
}

fn emit_delta(diff: &str) -> Result<()> {
    // ยง t0jfkh0n1@xdngg
    match Command::new("delta")
        .arg("--side-by-side")
        .stdin(Stdio::piped())
        .stdout(Stdio::inherit())
        .stderr(Stdio::inherit())
        .spawn()
    {
        Ok(mut child) => {
            if let Some(mut stdin) = child.stdin.take() {
                stdin.write_all(diff.as_bytes())?;
            }
            let status = child.wait()?;
            if !status.success() {
                print!("{diff}");
            }
            Ok(())
        }
        Err(_) => {
            print!("{diff}");
            Ok(())
        }
    }
}

/// A file behind a nested repository is not the project's, so the worktree holds none there.
fn read_worktree(root: &Path, rel: &Path) -> Option<String> {
    if walk::behind_nested_repo(root, rel) {
        return None;
    }
    std::fs::read_to_string(root.join(rel)).ok()
}

fn git_show(root: &Path, base: &str, rel: &Path) -> Option<String> {
    let spec = format!("{}:./{}", base, rel.to_string_lossy());
    let out = crate::workspace::git(root)
        .args(["show", &spec])
        .output()
        .ok()?;
    if !out.status.success() {
        return None;
    }
    String::from_utf8(out.stdout).ok()
}

/// The text of each of `rels` at `rev`, as `git_show` reads it, through one `git cat-file
/// --batch` rather than one process per file.
fn git_show_all(root: &Path, rev: &str, rels: &[PathBuf]) -> Vec<Option<String>> {
    let specs: Vec<String> = rels
        .iter()
        .map(|rel| format!("{}:./{}", rev, rel.to_string_lossy()))
        .collect();
    // The batch protocol is one name per line.
    if rels.is_empty() || specs.iter().any(|spec| spec.contains('\n')) {
        return rels.iter().map(|rel| git_show(root, rev, rel)).collect();
    }
    let batch = crate::workspace::git(root)
        .args(["cat-file", "--batch"])
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::null())
        .spawn();
    let Ok(mut child) = batch else {
        return rels.iter().map(|rel| git_show(root, rev, rel)).collect();
    };
    let input: String = specs.iter().map(|spec| format!("{spec}\n")).collect();
    let mut stdin = child.stdin.take().expect("piped stdin");
    // Written from another thread: git answers as it reads, and a full pipe would block both.
    let writer = std::thread::spawn(move || stdin.write_all(input.as_bytes()));
    let out = child.wait_with_output();
    let wrote = writer.join().is_ok_and(|wrote| wrote.is_ok());
    let out = match out {
        Ok(out) if wrote && out.status.success() => out.stdout,
        _ => return rels.iter().map(|rel| git_show(root, rev, rel)).collect(),
    };
    let mut rest = out.as_slice();
    rels.iter()
        .map(|rel| {
            let nl = rest.iter().position(|&b| b == b'\n').unwrap_or(rest.len());
            let header = String::from_utf8_lossy(&rest[..nl]).into_owned();
            rest = rest.get(nl + 1..).unwrap_or_default();
            // `<oid> <type> <size>`, or `<name> missing` when `rev` holds no such path.
            let mut fields = header.rsplitn(3, ' ');
            let size: usize = fields.next()?.parse().ok()?;
            let kind = fields.next()?;
            let body = rest.get(..size)?;
            rest = rest.get(size + 1..).unwrap_or_default();
            if kind != "blob" {
                return git_show(root, rev, rel);
            }
            String::from_utf8(body.to_vec()).ok()
        })
        .collect()
}

fn git_ok(root: &Path, args: &[&str]) -> bool {
    crate::workspace::git(root)
        .args(args)
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .status()
        .map(|s| s.success())
        .unwrap_or(false)
}

fn git_stdout(root: &Path, args: &[&str]) -> Result<String> {
    // ยง cme63msgx.a@991cf
    let out = crate::workspace::git(root)
        .args(args)
        .output()
        .with_context(|| format!("git {}", args.join(" ")))?;
    if !out.status.success() {
        bail!(
            "git {} failed: {}",
            args.join(" "),
            String::from_utf8_lossy(&out.stderr)
        );
    }
    Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
}

fn git_lines(root: &Path, args: &[&str]) -> Result<Vec<PathBuf>> {
    let text = git_stdout(root, args)?;
    Ok(text
        .lines()
        .filter(|l| !l.is_empty())
        .map(PathBuf::from)
        .collect())
}

/// The changes kept, the pins folded, and both sides when they were read.
type Sorted = (Vec<Change>, Vec<Change>, Option<[Side; 2]>);

/// Weigh every marker that kept its pin, or changed only its digest, against its span and
/// its followed callees on both sides, and every pin of an unchanged file against its
/// callees. A weighed pin whose span and callees read the same is dropped, or folded into
/// the remint line when its digest moved. Any other is a drift, shown beside its clause.
/// `verbose` keeps the folded ones as markers. Returns the changes kept, the pins folded, and
/// both sides, comparison point first, when they were read.
fn sort_markers(
    ws: &crate::workspace::Workspace,
    root: &Path,
    base_ref: &str,
    changes: Vec<Change>,
    files: &FileMap,
    verbose: bool,
) -> Result<Sorted> {
    // ยง n4fbh9vd4.d@4j08v
    // A pin in a file the comparison did not touch drifts only through a followed callee, which
    // a touched file holds, or through the law or clause text it is pinned to.
    let reworded = changes
        .iter()
        .any(|change| matches!(change.kind, Kind::Amended | Kind::Clause));
    if files.is_empty() && !reworded {
        return Ok((changes, Vec::new(), None));
    }
    let ends = diff_ends(root, base_ref)?;
    let paths = new_side_paths(root, ends.new_rev.as_deref())?;
    let tests = TestPaths::at(root)?;
    let new = Side::of(
        side_sources(&paths, |rels| {
            read_new_sides(root, ends.new_rev.as_deref(), rels)
        }),
        &tests,
        None,
    );
    // ยง cme63msgx.c@zmpn5
    // The comparison point reads a file it held at the path it held it: one moved away that
    // holds no pin, weighed in place only when it has one, and one deleted since.
    let moved_away: BTreeMap<PathBuf, PathBuf> = changed_paths(root, base_ref)?
        .into_iter()
        .filter(|t| t.old != t.new && crate::follow::reads_path(&t.old))
        .filter(|t| {
            files
                .get(&path_of(&t.new))
                .and_then(|(old, _)| old.as_deref())
                .is_some_and(|text| !text.contains('ยง'))
        })
        .map(|t| (t.new, t.old))
        .collect();
    let mut old_sources = side_sources(&paths, |rels| {
        rels.iter()
            .map(|rel| match files.get(&path_of(rel)) {
                _ if moved_away.contains_key(rel) => None,
                Some((old, _)) => old.clone(),
                None => new.files.get(rel).map(|file| file.text.clone()),
            })
            .collect()
    });
    for (now, then) in &moved_away {
        if let Some(text) = files.get(&path_of(now)).and_then(|(old, _)| old.clone()) {
            old_sources.push((then.clone(), text));
        }
    }
    // ยง end cme63msgx.c
    let held: BTreeSet<&PathBuf> = paths.iter().collect();
    for (path, (old, new)) in files {
        let rel = PathBuf::from(path);
        let deleted = new.is_none() && !held.contains(&rel) && crate::follow::reads_path(&rel);
        if let Some(text) = old.clone().filter(|_| deleted) {
            old_sources.push((rel, text));
        }
    }
    let old = Side::of(old_sources, &tests, Some(&new));
    let texts = AddressTexts::new(root, &ends);
    let scheme = SchemeReads::new(ws, root, &ends)?;
    let mut kept = Vec::new();
    let mut folded = Vec::new();
    for change in changes {
        // ยง n4fbh9vd4.c@0f9ev
        if !weighed_pin(&change) {
            kept.push(change);
            continue;
        }
        // A digest that moved with its span, callees and address text unchanged, and that the
        // current scheme reads the same on both sides, is a scheme remint. One whose clause or
        // carrying sentence moved was accepted against new text.
        let digest_moved = change.old_text != change.new_text;
        // A pin that kept its digest over a text that moved no longer holds, and is a drift.
        let text_moved = match digest_moved {
            true => !texts.unchanged(&change.address)?,
            false => texts.changed(&change.address)?,
        };
        let drift = match drift_of(&change, files, &old, &new, text_moved)? {
            None if digest_moved && !scheme.same(&change)? => {
                drift_of(&change, files, &old, &new, true)?.map(|drift| Change {
                    why: Some(UNSHOWN_MOVE.to_string()),
                    ..drift
                })
            }
            None if digest_moved && !scheme.held(&change)? => {
                drift_of(&change, files, &old, &new, true)?.map(|drift| Change {
                    why: Some(RED_AT_BASE.to_string()),
                    ..drift
                })
            }
            drift => drift,
        };
        match drift {
            Some(mut drift) => {
                if text_moved && drift.why.is_none() && unshown(&drift) {
                    drift.why = Some(TEXT_MOVE.to_string());
                }
                kept.push(drift);
            }
            None if digest_moved => {
                if verbose {
                    kept.push(change.clone());
                }
                folded.push(change);
            }
            None => {}
        }
    }
    kept.extend(callee_drifts(files, &old, &new, &texts)?);
    Ok((kept, folded, Some([old, new])))
}

/// Why a drift whose span reads alike names another body or binding for a call it writes.
const REBOUND: &str =
    "A call of the span that reads alike now names another body, or what binds it changed.";
/// Why a drift whose span reads alike moved: a followed callee shown below it changed.
const CALLEE_EDIT: &str = "A callee changed: its patch is below.";
/// Why an accepted drift whose span and callees read alike moved its digest.
const UNSHOWN_MOVE: &str = "The span, the stretches it reads around it and its followed callees read alike, and the digest moved: it also reads the constants it follows, the definitions its links name and the project path, and one of them changed.";
/// Why a pin that did not hold at the comparison point and that the compared side re-pins is
/// an accept, though its span and callees read alike.
const RED_AT_BASE: &str = "The span and its followed callees read alike, and the digest the comparison point wrote did not hold there: what it binds changed there without an accept, and this side re-pins it.";
const TEXT_MOVE: &str =
    "The span and its followed callees read alike: the law or clause text it is pinned to changed.";

/// Whether a drift's span, digests aside, and its followed callees read the same on both sides.
fn unshown(change: &Change) -> bool {
    change.callees.is_empty()
        && change.old_text.as_deref().map(strip_digests)
            == change.new_text.as_deref().map(strip_digests)
}

/// The token the scheme this binary implements reads for a pin on each side, so a digest folds
/// only when that scheme reads one digest from both, as `fix --remint` rewrites one after a
/// scheme change.
/// Each side is read on first need: the comparison point written out to a temporary tree, the
/// compared side read in place or, for a range, written out as well.
struct SchemeReads<'a> {
    ws_root: &'a Path,
    root_rel: PathBuf,
    own_key: String,
    ends: &'a DiffEnds,
    sides: std::cell::RefCell<[Option<SideTokens>; 2]>,
    files: std::cell::RefCell<BTreeMap<(usize, PathBuf), span::PinTokens>>,
    /// The scheme the comparison point records, read on first need.
    recorded: std::cell::OnceCell<Option<crate::scheme::Scheme>>,
}

struct SideTokens {
    _tree: Option<tempfile::TempDir>,
    dir: PathBuf,
    tokens: span::TreeTokens,
}

impl<'a> SchemeReads<'a> {
    fn new(ws: &'a crate::workspace::Workspace, root: &Path, ends: &'a DiffEnds) -> Result<Self> {
        let own_key = ws
            .projects
            .iter()
            .find(|project| project.dir == root)
            .map(|project| project.key.clone())
            .with_context(|| format!("{} is no project of the workspace", root.display()))?;
        Ok(Self {
            ws_root: &ws.root,
            root_rel: root.strip_prefix(&ws.root)?.to_path_buf(),
            own_key,
            ends,
            sides: Default::default(),
            files: Default::default(),
            recorded: Default::default(),
        })
    }

    fn load(&self, side: usize) -> Result<SideTokens> {
        let rev = [
            Some(self.ends.old_rev.as_str()),
            self.ends.new_rev.as_deref(),
        ][side];
        let (tree, top) = match rev {
            Some(rev) => {
                let tree = tempfile::tempdir()?;
                crate::published::write_tree(self.ws_root, rev, tree.path())?;
                let top = tree.path().to_path_buf();
                (Some(tree), top)
            }
            None => (None, self.ws_root.to_path_buf()),
        };
        let dir = top.join(&self.root_rel);
        let scans = crate::workspace::Workspace::at(top)?.law_scans(&self.own_key)?;
        let texts = span::PinTexts::for_project(&parse::scan_root(&dir)?, &scans);
        let tokens = span::TreeTokens::new(&dir, texts)?;
        Ok(SideTokens {
            _tree: tree,
            dir,
            tokens,
        })
    }

    /// The token the scheme reads for the pin written `bit` on the 1-based `line` of `rel`.
    fn token(
        &self,
        side: usize,
        rel: &Path,
        line: usize,
        (bit, address): (&str, &str),
    ) -> Result<Option<String>> {
        if self.sides.borrow()[side].is_none() {
            let loaded = self.load(side)?;
            self.sides.borrow_mut()[side] = Some(loaded);
        }
        let Some(addr) = marker::entry_for(bit, address)
            .and_then(|pin| pin.split_digest())
            .map(|(addr, _)| addr.display())
        else {
            return Ok(None);
        };
        let key = (side, rel.to_path_buf());
        if !self.files.borrow().contains_key(&key) {
            let sides = self.sides.borrow();
            let side = sides[side].as_ref().expect("loaded above");
            let tokens = match std::fs::read_to_string(side.dir.join(rel)) {
                Ok(text) => side.tokens.tokens(rel, &text),
                Err(e) if e.kind() == std::io::ErrorKind::NotFound => span::PinTokens::new(),
                Err(e) => return Err(e.into()),
            };
            self.files.borrow_mut().insert(key.clone(), tokens);
        }
        Ok(self.files.borrow()[&key].get(&(line - 1, addr)).cloned())
    }

    /// Whether the scheme reads, on both sides, the digest the compared side writes.
    fn same(&self, change: &Change) -> Result<bool> {
        // ยง n4fbh9vd4.d@m68cv
        let (
            Some(old_path),
            Some(new_path),
            Some(old_bit),
            Some(new_bit),
            [Some(old_line), Some(new_line)],
        ) = (
            change.old_path.as_deref(),
            change.new_path.as_deref(),
            change.old_text.as_deref(),
            change.new_text.as_deref(),
            change.lines,
        )
        else {
            return Ok(false);
        };
        let address = change.address.as_str();
        let written = marker::entry_for(new_bit, address).and_then(|pin| pin.digest);
        let old = self.token(0, Path::new(old_path), old_line, (old_bit, address))?;
        let new = self.token(1, Path::new(new_path), new_line, (new_bit, address))?;
        Ok(old.is_some() && old == new && new == written)
    }

    /// Whether the digest the comparison point writes held there: the scheme this binary
    /// implements reads it from that side's own code. A comparison point that records another
    /// version of a part a pin reads wrote a digest this binary cannot read, so that pin is taken
    /// as held.
    fn held(&self, change: &Change) -> Result<bool> {
        // ยง n4fbh9vd4.d@ay0fb
        let (Some(old_path), Some(old_bit), Some(old_line)) = (
            change.old_path.as_deref(),
            change.old_text.as_deref(),
            change.lines[0],
        ) else {
            return Ok(false);
        };
        if self.recorded.get().is_none() {
            let read = crate::hook::recorded_scheme_at(self.ws_root, &self.ends.old_rev)?;
            let _ = self.recorded.set(read);
        }
        let recorded = self.recorded.get().and_then(Option::as_ref);
        let parts = crate::scheme::parts_of(Path::new(old_path));
        if recorded.is_some_and(|scheme| {
            !scheme
                .moved(&crate::scheme::Scheme::binary(), &parts)
                .is_empty()
        }) {
            return Ok(true);
        }
        let address = change.address.as_str();
        let written = marker::entry_for(old_bit, address).and_then(|pin| pin.digest);
        let read = self.token(0, Path::new(old_path), old_line, (old_bit, address))?;
        Ok(read.is_some() && read == written)
    }
}

/// The text each address hashes with its span, on each side of the comparison, read per project
/// on demand: the carrying sentence and the lines under the head for a law, the carrying
/// sentence and the clause body for a clause.
struct AddressTexts<'a> {
    root: &'a Path,
    ends: &'a DiffEnds,
    read: std::cell::RefCell<BTreeMap<String, [BTreeMap<String, String>; 2]>>,
}

impl<'a> AddressTexts<'a> {
    fn new(root: &'a Path, ends: &'a DiffEnds) -> Self {
        Self {
            root,
            ends,
            read: Default::default(),
        }
    }

    fn texts(laws: &[parse::Law]) -> BTreeMap<String, String> {
        let mut out = BTreeMap::new();
        for law in laws {
            out.insert(law.id.clone(), law.pin_text());
            for al in &law.clauses {
                if let Some(letter) = &al.letter {
                    out.insert(
                        format!("{}.{letter}", law.id),
                        format!("{}\n{}", law.pin_text(), al.pin_body()),
                    );
                }
            }
        }
        out
    }

    /// Whether `address`, `[<projectpath>:]<id>[.<letter>]`, reads the same text on both sides.
    fn unchanged(&self, address: &str) -> Result<bool> {
        // ยง n4fbh9vd4.d@x945h
        let (project, local) = match address.rsplit_once(':') {
            Some((project, local)) => (project, local),
            None => ("", address),
        };
        let mut read = self.read.borrow_mut();
        if !read.contains_key(project) {
            let dir = match project {
                "" => self.root.to_path_buf(),
                project => {
                    let top =
                        PathBuf::from(git_stdout(self.root, &["rev-parse", "--show-toplevel"])?);
                    if project == "." {
                        top
                    } else {
                        top.join(project)
                    }
                }
            };
            let then = crate::published::at(&dir, &self.ends.old_rev)?;
            let now = match &self.ends.new_rev {
                Some(rev) => crate::published::at(&dir, rev)?.laws().to_vec(),
                None => parse::scan_root(&dir)?.laws,
            };
            read.insert(
                project.to_string(),
                [Self::texts(then.laws()), Self::texts(&now)],
            );
        }
        let [then, now] = &read[project];
        Ok(then
            .get(local)
            .is_some_and(|text| now.get(local) == Some(text)))
    }

    /// Whether `address` reads on both sides, and reads otherwise on the compared one as a pin
    /// reads it.
    fn changed(&self, address: &str) -> Result<bool> {
        self.unchanged(address)?;
        let (project, local) = address.rsplit_once(':').unwrap_or(("", address));
        let [then, now] = &self.read.borrow()[project];
        Ok(then
            .get(local)
            .zip(now.get(local))
            .is_some_and(|(then, now)| attached_moved(then, now)))
    }
}

/// One side of the comparison: its code files, parsed once, and their follow index.
struct Side {
    files: BTreeMap<PathBuf, span::CodeFile>,
    /// The markers of each file with their spans, parsed once rather than once per pin.
    markers: BTreeMap<PathBuf, Vec<span::SpanMarker>>,
    follow: FollowIndex,
}

impl Side {
    /// `reuse` holds files a run already parsed: one whose text is the same is not parsed again.
    fn of(sources: Vec<(PathBuf, String)>, tests: &TestPaths, reuse: Option<&Side>) -> Self {
        let parsed = crate::par::map(
            sources,
            |(_, text)| text.len(),
            |(rel, text)| match reuse.and_then(|side| side.files.get(&rel)) {
                Some(file) if file.text == text => file.clone(),
                // silcrow:skip
                _ => span::CodeFile::new(rel, text),
            },
        );
        let follow = FollowIndex::from_files(&parsed, tests);
        let markers = parsed
            .iter()
            .map(|f| (f.rel.clone(), f.span_markers()))
            .collect();
        let files = parsed.into_iter().map(|f| (f.rel.clone(), f)).collect();
        Self {
            files,
            markers,
            follow,
        }
    }
}

/// One commit as `stats --history` weighs a re-pin against it: its code files parsed with
/// their follow index, and the text each address of its notes pins.
pub struct Tree {
    side: Side,
    texts: BTreeMap<String, String>,
}

impl Tree {
    /// The tree `rev` holds under the project at `root`, read as a side of `diff` reads it.
    pub fn at(root: &Path, rev: &str) -> Result<Self> {
        Self::at_reusing(root, rev, None)
    }

    /// The tree `rev` holds, as `at` reads it, reusing the parse of each file `now` holds with
    /// the same text.
    pub fn at_reusing(root: &Path, rev: &str, now: Option<&Tree>) -> Result<Self> {
        let project = walk::Project::at(root)?;
        // Each entry as `<mode> <type> <blob>\t<path>`, the path as `--name-only` writes it.
        let entries: Vec<(String, PathBuf)> = git_lines(root, &["ls-tree", "-r", rev, "--", "."])?
            .into_iter()
            .filter_map(|line| {
                let text = line.to_string_lossy().into_owned();
                let (meta, path) = text.split_once('\t')?;
                let mut fields = meta.split(' ');
                let (mode, blob) = (fields.next()?, fields.nth(1)?);
                let blob = matches!(mode, "100644" | "100755").then(|| blob.to_string());
                Some((blob.unwrap_or_default(), PathBuf::from(path)))
            })
            .collect();
        let blobs: BTreeMap<&Path, &str> = entries
            .iter()
            .map(|(blob, rel)| (rel.as_path(), blob.as_str()))
            .collect();
        let listed: Vec<PathBuf> = entries.iter().map(|(_, rel)| rel.clone()).collect();
        let code: Vec<PathBuf> = listed
            .iter()
            .filter(|rel| walk::walks_to(&project, rel))
            .cloned()
            .collect();
        // A file `now` holds with the very bytes of the blob `rev` lists is not read from git.
        let held = |rel: &Path| {
            let text = now?.side.files.get(rel)?.text.as_str();
            let blob = blobs.get(rel).filter(|blob| !blob.is_empty())?;
            (crate::workspace::blob_id(text.as_bytes()) == *blob).then(|| text.to_string())
        };
        let sources = side_sources(&code, |rels| {
            let mut texts: Vec<Option<String>> = rels.iter().map(|rel| held(rel)).collect();
            let missing: Vec<PathBuf> = rels
                .iter()
                .zip(&texts)
                .filter(|(_, text)| text.is_none())
                .map(|(rel, _)| rel.clone())
                .collect();
            let mut read = git_show_all(root, rev, &missing).into_iter();
            for text in texts.iter_mut().filter(|text| text.is_none()) {
                *text = read.next().flatten();
            }
            texts
        });
        let notes: Vec<PathBuf> = listed
            .into_iter()
            .filter(|rel| project.is_note(rel))
            .collect();
        let read = git_show_all(root, rev, &notes);
        let notes: Vec<(PathBuf, String)> = notes
            .into_iter()
            .zip(read)
            .filter_map(|(rel, text)| Some((rel, text?)))
            .collect();
        Ok(Self {
            side: Side::of(sources, &TestPaths::at(root)?, now.map(|tree| &tree.side)),
            texts: AddressTexts::texts(&parse::scan_notes(&notes).laws),
        })
    }
}

impl Tree {
    /// The tree a run already read and parsed, with the laws of its notes.
    pub fn of(files: Vec<span::CodeFile>, follow: FollowIndex, laws: &[parse::Law]) -> Self {
        let markers = files
            .iter()
            .map(|f| (f.rel.clone(), f.span_markers()))
            .collect();
        let files = files.into_iter().map(|f| (f.rel.clone(), f)).collect();
        Self {
            side: Side {
                files,
                markers,
                follow,
            },
            texts: AddressTexts::texts(laws),
        }
    }

    /// The text of the file at `rel`.
    pub fn text(&self, rel: &Path) -> Option<&str> {
        self.side.files.get(rel).map(|f| f.text.as_str())
    }

    /// The pin `pin`, digest included, as this tree writes it: its file, its 1-based line and
    /// its marker line trimmed, in `prefer` first. `None` when no marker or several elsewhere
    /// write it.
    pub fn pin(&self, pin: &marker::MarkerAddr, prefer: &Path) -> Option<(PathBuf, usize, String)> {
        let at = |rel: &PathBuf| {
            let hits: Vec<usize> = self
                .side
                .markers
                .get(rel)?
                .iter()
                .filter(|m| &m.addr == pin)
                .map(|m| m.line)
                .collect();
            match hits.as_slice() {
                [line] => Some(*line),
                _ => None,
            }
        };
        let rel = match at(&prefer.to_path_buf()) {
            Some(_) => prefer.to_path_buf(),
            None => {
                let found: Vec<&PathBuf> = self
                    .side
                    .markers
                    .keys()
                    .filter(|rel| at(rel).is_some())
                    .collect();
                match found.as_slice() {
                    [rel] => (*rel).clone(),
                    _ => return None,
                }
            }
        };
        let line = at(&rel)?;
        let bit = self.text(&rel)?.lines().nth(line - 1)?.trim().to_string();
        Some((rel, line, bit))
    }
}

/// A pin on one side of a commit: its file and the text that side holds there, its 1-based
/// line and the marker line as written.
pub struct PinAt<'a> {
    pub path: &'a str,
    pub text: &'a str,
    pub line: usize,
    pub bit: &'a str,
}

/// What moved under a pin between two trees, each read as `diff` reads a drift.
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct Moved {
    pub span: bool,
    pub prefix: bool,
    /// The YAML keys and entries above the span.
    pub above: bool,
    pub callee: bool,
    pub import: bool,
    pub text: bool,
    /// Each followed callee that moved, `name` in `path`.
    pub callees: Vec<(String, String)>,
    /// Each callee no longer followed only because its one declaration, `name` in `path`, left
    /// the cone of the span's file.
    pub left: Vec<(String, String)>,
}

/// For a pin in a file with no tested grammar, which no tree parses: whether its stretch and
/// the text of `address` read otherwise in `new` than in `old`, the text the file held then.
pub fn fallback_moved(
    address: &str,
    (then, old): (&Tree, &str),
    (now, new): (&Tree, PinAt),
) -> Option<(bool, bool)> {
    let rel = Path::new(new.path);
    let old_line = 1 + old.lines().position(|line| line.trim() == new.bit)?;
    let span =
        |text: &str, line: usize| extract_punched(rel, text, line).map(|s| strip_digests(&s));
    let text = |tree: &Tree| tree.texts.get(address).map(|t| crate::hash::pin_canon(t));
    Some((
        span(old, old_line)? != span(new.text, new.line)?,
        text(then) != text(now),
    ))
}

/// What moved under the pin of `address` from `old` to `new`.
pub fn moved(address: &str, old: (&Tree, PinAt), new: (&Tree, PinAt)) -> Result<Moved> {
    // ยง bx4hdwv3s.a@b642q
    let side = |(tree, pin): &(&Tree, PinAt)| {
        span_side(pin.path, pin.text, (Some(pin.line), pin.bit), &tree.side)
    };
    let (then, now) = (side(&old)?, side(&new)?);
    let imports = |span: &SpanSide| -> BTreeSet<String> {
        span.blob
            .lines()
            .filter(|line| line.starts_with("ยงimport "))
            .map(str::to_string)
            .collect()
    };
    let text = |tree: &Tree| tree.texts.get(address).map(|t| crate::hash::pin_canon(t));
    let (left, callees): (Vec<CalleeDiff>, Vec<CalleeDiff>) =
        callee_diffs(&then, &now, new.1.path, &new.0.side.follow)
            .into_iter()
            .partition(|c| c.new.is_none() && now.left.contains_key(&c.name));
    let reads = read_diffs(new.1.path, &then.reads, &now.reads).0;
    let is_above = |d: &CalleeDiff| d.read == Some(span_lang::Read::Above);
    let span = strip_digests(&then.span) != strip_digests(&now.span);
    let prefix = reads.iter().any(|d| !is_above(d));
    let above = reads.iter().any(is_above);
    let import = imports(&then) != imports(&now);
    let text = text(old.0) != text(new.0);
    Ok(Moved {
        span,
        prefix,
        above,
        callee: !callees.is_empty() || !left.is_empty(),
        import,
        text,
        callees: callees.into_iter().map(|c| (c.name, c.path)).collect(),
        left: left
            .into_iter()
            .map(|c| (c.name.clone(), now.left[&c.name].clone()))
            .collect(),
    })
}

/// The span of `change` on both sides, as a drift, unless its bytes and its followed callees
/// read the same on both and `text_moved` is false: then only a scheme change re-pinned it.
fn drift_of(
    change: &Change,
    files: &FileMap,
    old: &Side,
    new: &Side,
    text_moved: bool,
) -> Result<Option<Change>> {
    // ยง n4fbh9vd4.d@tx91h
    let (Some(old_path), Some(new_path), Some(old_bit), Some(new_bit)) = (
        change.old_path.as_deref(),
        change.new_path.as_deref(),
        change.old_text.as_deref(),
        change.new_text.as_deref(),
    ) else {
        bail!("ยง {} cannot be weighed: a side has no pin", change.address);
    };
    // ยง yjrm4q97t.a@v8612
    let old_span = span_side(
        old_path,
        side_text(files, old, old_path, true)?,
        (change.lines[0], old_bit),
        old,
    )?;
    let new_span = span_side(
        new_path,
        side_text(files, new, new_path, false)?,
        (change.lines[1], new_bit),
        new,
    )?;
    let (mut reads, reads_why) = read_diffs(new_path, &old_span.reads, &new_span.reads);
    let callees = callee_diffs(&old_span, &new_span, new_path, &new.follow);
    // ยง end yjrm4q97t.a
    let same_span = strip_digests(&old_span.span) == strip_digests(&new_span.span);
    // ยง n4fbh9vd4.c@1v66k
    // A followed body or constant edited moves the hash its call writes in `names` too, so
    // only names that move while every body shown reads alike are a rebinding.
    let renamed = if !callees.is_empty() {
        same_span.then(|| CALLEE_EDIT.to_string())
    } else {
        (same_span && reads.is_empty() && old_span.names != new_span.names)
            .then(|| REBOUND.to_string())
    };
    if same_span
        && old_span.blob == new_span.blob
        && old_span.binding == new_span.binding
        && callees.is_empty()
        && reads.is_empty()
        && renamed.is_none()
        && !text_moved
    {
        return Ok(None);
    }
    // ยง end n4fbh9vd4.c
    reads.extend(callees);
    // ยง x6knpe5fd@bmvxk
    // `weighed_pin` already holds the two pins equal but for their digests.
    let moved = match (&old_span.binding, &new_span.binding) {
        (Some(then), Some(now)) if then != now => Some(format!(
            "The marker moved from `{}` to `{}`, a construct that reads alike, or that construct was renamed: a comparing `check` pairs a pin only within the constructs that held it.",
            then.join("::"),
            now.join("::")
        )),
        _ => None,
    };
    let kind = if change.old_text == change.new_text && moved.is_none() {
        Kind::Drift
    } else {
        Kind::Accepted
    };
    // ยง end x6knpe5fd
    Ok(Some(Change {
        kind,
        old_text: Some(old_span.span),
        new_text: Some(new_span.span),
        callees: reads,
        why: joined_notes(
            joined_notes(moved.or(change.why.clone()), reads_why),
            renamed,
        ),
        ..change.clone()
    }))
}

/// The pins of the files the comparison did not touch whose followed callees moved, or whose
/// law or clause text did.
fn callee_drifts(
    files: &FileMap,
    old: &Side,
    new: &Side,
    texts: &AddressTexts,
) -> Result<Vec<Change>> {
    // ยง n4fbh9vd4.c@wjkd7
    let mut out = Vec::new();
    for (rel, file) in &new.files {
        let path = path_of(rel);
        if files.contains_key(&path) {
            continue;
        }
        let markers = file.span_markers();
        for marker in &markers {
            if marker.addr.digest.is_none() {
                continue;
            }
            let punch = span::punch_of(&markers, marker.line);
            let text_moved = texts.changed(&marker.addr.display())?;
            let prefix = file.prefix(marker.start, marker.end);
            if !text_moved
                && old
                    .follow
                    .pin_blob(rel, marker.start, marker.end, &punch, &prefix)
                    == new
                        .follow
                        .pin_blob(rel, marker.start, marker.end, &punch, &prefix)
            {
                continue;
            }
            let bit = file
                .text
                .lines()
                .nth(marker.line - 1)
                .map(|line| line.trim().to_string());
            let change = Change {
                address: marker.addr.display(),
                kind: Kind::Marker,
                old_path: Some(path.clone()),
                new_path: Some(path.clone()),
                old_text: bit.clone(),
                new_text: bit,
                callees: Vec::new(),
                lines: [Some(marker.line), Some(marker.line)],
                why: None,
            };
            out.extend(
                drift_of(&change, files, old, new, text_moved)?.map(|mut drift| {
                    if text_moved && drift.why.is_none() && unshown(&drift) {
                        drift.why = Some(TEXT_MOVE.to_string());
                    }
                    drift
                }),
            );
        }
    }
    Ok(out)
}

fn side_text<'a>(files: &'a FileMap, side: &'a Side, path: &str, old: bool) -> Result<&'a str> {
    let text = match files.get(path) {
        Some((before, after)) => if old { before } else { after }.as_deref(),
        None => side
            .files
            .get(Path::new(path))
            .map(|file| file.text.as_str()),
    };
    text.with_context(|| format!("{path} cannot be read on the {} side", side_name(old)))
}

fn side_name(old: bool) -> &'static str {
    if old {
        "comparison"
    } else {
        "compared"
    }
}

struct SpanSide {
    span: String,
    blob: String,
    /// What the shape writes for each call and read of the span, in the order they stand: a
    /// call that reads alike and names another body there is a drift.
    names: Vec<String>,
    /// Name, file, first line and span text of each followed callee.
    callees: Vec<(String, String, usize, String)>,
    /// The names of the constructs around the span, `None` without a grammar.
    binding: Option<Vec<String>>,
    /// Each stretch the pin reads beyond the span: what it is, its lines as shown, and the text
    /// it reads, punched and with its whitespace collapsed.
    reads: Vec<(span_lang::Read, String, String)>,
    /// Each name a call of the span spells that follows nothing only because its one
    /// declaration, in the file given, lies outside the cone of the span's file.
    left: BTreeMap<String, String>,
}

/// Each stretch the span `start..end` of `file` reads beyond itself, as `SpanSide::reads`
/// holds it.
fn read_stretches(
    file: &span::CodeFile,
    start: usize,
    end: usize,
) -> Vec<(span_lang::Read, String, String)> {
    if !file.parsed() {
        return Vec::new();
    }
    file.memo(&("read stretches", start, end), || {
        read_stretches_of(file, start, end)
    })
}

fn read_stretches_of(
    file: &span::CodeFile,
    start: usize,
    end: usize,
) -> Vec<(span_lang::Read, String, String)> {
    // ยง n4fbh9vd4.c@hd75q
    let (Some(lang), Some(tree)) = (file.lang, file.tree()) else {
        return Vec::new();
    };
    let text = file.text.as_str();
    span_lang::read_stretches(lang, text, tree, start, end)
        .into_iter()
        .map(|(read, (from, to, punch))| {
            let punched = |at: usize| punch.iter().any(|&(s, e)| s <= at && at < e);
            let mut read_text = String::new();
            for (at, c) in text[from..to].char_indices() {
                if !punched(from + at) {
                    read_text.push(c);
                }
            }
            let mut shown = String::new();
            let mut at = text[..from].rfind('\n').map_or(0, |nl| nl + 1);
            for line in text[at..].split_inclusive('\n') {
                if at >= to {
                    break;
                }
                let kept = line.char_indices().any(|(i, c)| {
                    !c.is_whitespace() && (from..to).contains(&(at + i)) && !punched(at + i)
                });
                if kept {
                    shown.push_str(line.trim_end_matches(['\n', '\r']));
                    shown.push('\n');
                }
                at += line.len();
            }
            let read_text = strip_digests(&read_text)
                .split_whitespace()
                .collect::<Vec<_>>()
                .join(" ");
            (read, shown, read_text)
        })
        .collect()
}

/// Each kind of stretch the pin reads beyond its span whose text differs between the sides, as
/// a patch of its own on the span's file, and the `why` that names them.
fn read_diffs(
    path: &str,
    old: &[(span_lang::Read, String, String)],
    new: &[(span_lang::Read, String, String)],
) -> (Vec<CalleeDiff>, Option<String>) {
    let by_read = |side: &[(span_lang::Read, String, String)]| {
        let mut out: BTreeMap<span_lang::Read, (String, Vec<String>)> = BTreeMap::new();
        for (read, shown, text) in side {
            let entry = out.entry(*read).or_default();
            entry.0.push_str(shown);
            entry.1.push(text.clone());
        }
        out
    };
    let (old, new) = (by_read(old), by_read(new));
    let reads: BTreeSet<&span_lang::Read> = old.keys().chain(new.keys()).collect();
    let diffs: Vec<CalleeDiff> = reads
        .into_iter()
        .filter(|read| old.get(*read).map(|o| &o.1) != new.get(*read).map(|n| &n.1))
        .map(|read| CalleeDiff {
            name: read_label(*read).to_string(),
            path: path.to_string(),
            old: old.get(read).map(|o| o.0.clone()),
            new: new.get(read).map(|n| n.0.clone()),
            why: None,
            read: Some(*read),
        })
        .collect();
    let why = (!diffs.is_empty()).then(|| {
        let names: Vec<&str> = diffs.iter().map(|d| d.name.as_str()).collect();
        format!(
            "Beyond the span, the digest reads the {}, which changed.",
            names.join(" and the ")
        )
    });
    (diffs, why)
}

/// The key JSON writes for a stretch the pin reads beyond its span.
fn read_key(read: span_lang::Read) -> &'static str {
    use span_lang::Read;
    match read {
        Read::Prefix => "prefix",
        Read::Attribute => "attribute",
        Read::Above => "above",
    }
}

/// How `diff` names a stretch the pin reads beyond its span.
fn read_label(read: span_lang::Read) -> &'static str {
    use span_lang::Read;
    match read {
        Read::Prefix => "code before the span in its function",
        Read::Attribute => "attributes that govern the span",
        Read::Above => "keys and entries above the span",
    }
}

/// The punched span of the marker written `bit` in `text`, its follow blob and its followed
/// callees. A span or a callee that cannot be read is an error, never a fold.
fn span_side(
    path: &str,
    text: &str,
    (at, bit): (Option<usize>, &str),
    side: &Side,
) -> Result<SpanSide> {
    // ยง n4fbh9vd4.e@8zfa8
    let rel = Path::new(path);
    let written = |idx: usize| text.lines().nth(idx).is_some_and(|line| line.trim() == bit);
    let line = match at {
        Some(line) => line.checked_sub(1).filter(|&idx| written(idx)),
        None => text.lines().position(|line| line.trim() == bit),
    }
    .with_context(|| format!("{path}: the pin `{bit}` is not in the file"))?
        + 1;
    let unreadable = || format!("{path}:{line}: the span of `{bit}` cannot be read");
    if span_lang::lang_for_path(rel).is_none() {
        return Ok(SpanSide {
            span: extract_punched(rel, text, line).with_context(unreadable)?,
            blob: String::new(),
            names: Vec::new(),
            callees: Vec::new(),
            binding: None,
            reads: Vec::new(),
            left: BTreeMap::new(),
        });
    }
    let markers = side.markers.get(rel).with_context(unreadable)?;
    let (span, (start, end), punch) = punched_in(text, markers, line).with_context(unreadable)?;
    let file = side.files.get(rel);
    let prefix = file.map_or_else(Vec::new, |file| file.prefix(start, end));
    let followed = side
        .follow
        .followed_callees(rel, start, end, &punch, &prefix);
    let callees = followed
        .into_iter()
        .map(|callee| {
            let text = side.files.get(&callee.path).map(|file| file.text.as_str());
            let at = text
                .and_then(|t| t.get(..callee.start))
                .map_or(1, |before| before.matches('\n').count() + 1);
            let body = text
                .and_then(|t| t.get(callee.start..callee.end))
                .with_context(|| {
                    format!(
                        "{path}:{line}: the callee {} in {} cannot be read",
                        callee.name,
                        callee.path.display()
                    )
                })?;
            Ok((callee.name, path_of(&callee.path), at, body.to_string()))
        })
        .collect::<Result<_>>()?;
    Ok(SpanSide {
        span,
        blob: side.follow.pin_blob(rel, start, end, &punch, &prefix),
        names: side
            .follow
            .name_tokens(rel, start, end, &punch, &prefix)
            .into_iter()
            .collect::<BTreeMap<_, _>>()
            .into_values()
            .collect(),
        callees,
        binding: file.and_then(|file| file.binding(start, end)),
        reads: file.map_or_else(Vec::new, |file| read_stretches(file, start, end)),
        left: side
            .follow
            .outside_cone(rel, start, end, &punch)
            .into_iter()
            .map(|(name, decl)| (name, path_of(&decl)))
            .collect(),
    })
}

type Extent = (usize, usize);

/// The punched span of the marker on `marker_line`, as `extract_punched` reads it, its byte
/// span and the byte extents punched out of it, from markers whose spans are already parsed.
fn punched_in(
    text: &str,
    markers: &[span::SpanMarker],
    marker_line: usize,
) -> Option<(String, Extent, Vec<Extent>)> {
    // ยง yjrm4q97t.a@600zd
    let lines = |(start, end): (usize, usize)| {
        (end > start).then(|| (byte_line(text, start), byte_line(text, end - 1)))
    };
    let outer = markers.iter().find(|l| l.line == marker_line)?;
    let (start, end) = lines((outer.start, outer.end))?;
    let mut keep: BTreeSet<usize> = (start..=end).collect();
    // ยง rr512n5e2.c@z5ba4
    let punch = span::punch_of(markers, marker_line);
    for &inner in &punch {
        if let Some((inner_start, inner_end)) = lines(inner) {
            for line in inner_start..=inner_end {
                keep.remove(&line);
            }
        }
    }
    // ยง end rr512n5e2.c
    keep.insert(marker_line);
    let mut span = String::new();
    for (idx, line) in text.lines().enumerate() {
        if keep.contains(&(idx + 1)) {
            span.push_str(line);
            span.push('\n');
        }
    }
    Some((span, (outer.start, outer.end), punch))
}

/// Each followed callee, by file and name, whose span differs between the sides, or that
/// only one side follows.
fn callee_diffs(
    old_span: &SpanSide,
    new_span: &SpanSide,
    caller: &str,
    follow: &FollowIndex,
) -> Vec<CalleeDiff> {
    let (old, new) = (&old_span.callees[..], &new_span.callees[..]);
    // The declarations of one name in one file show each on its own line, by its line number.
    let index = |side: &[(String, String, usize, String)]| {
        let mut bodies: BTreeMap<(String, String), Vec<(usize, &str)>> = BTreeMap::new();
        for (name, path, at, body) in side {
            bodies
                .entry((path.clone(), name.clone()))
                .or_default()
                .push((*at, body));
        }
        let out: BTreeMap<(String, String), String> = bodies
            .into_iter()
            .map(|(key, bodies)| {
                let text = match bodies.as_slice() {
                    [(_, body)] => body.to_string(),
                    _ => bodies
                        .iter()
                        .map(|(at, body)| format!("{at}: {body}"))
                        .collect::<Vec<_>>()
                        .join("\n"),
                };
                (key, text)
            })
            .collect();
        out
    };
    let (mut old, new) = (index(old), index(new));
    // A callee that left one file for another, the one of its name each side lost and gained,
    // is the same callee: it pairs by name, not by path, as its hash does.
    let only = |a: &BTreeMap<(String, String), String>, b: &BTreeMap<(String, String), String>| {
        let mut by_name: BTreeMap<String, Vec<(String, String)>> = BTreeMap::new();
        for key in a.keys().filter(|k| !b.contains_key(*k)) {
            by_name.entry(key.1.clone()).or_default().push(key.clone());
        }
        by_name
    };
    let (gone, came) = (only(&old, &new), only(&new, &old));
    for (name, from) in gone {
        let to = came.get(&name).map_or(&[][..], Vec::as_slice);
        if let ([from], [to]) = (from.as_slice(), to) {
            if let Some(body) = old.remove(from) {
                old.insert(to.clone(), body);
            }
        }
    }
    let keys: BTreeSet<&(String, String)> = old.keys().chain(new.keys()).collect();
    let read = |bodies: &BTreeMap<(String, String), String>, key: &(String, String)| {
        bodies.get(key).map(|body| strip_digests(body))
    };
    keys.into_iter()
        .filter(|key| read(&old, key) != read(&new, key))
        .map(|(path, name)| CalleeDiff {
            name: name.clone(),
            path: path.clone(),
            old: old.get(&(path.clone(), name.clone())).cloned(),
            new: new.get(&(path.clone(), name.clone())).cloned(),
            why: (!new.contains_key(&(path.clone(), name.clone()))).then(|| {
                match new_span.left.get(name) {
                    Some(decl) => left_cone(name, decl, caller),
                    None => unfollowed(name, follow),
                }
            }),
            read: None,
        })
        .collect()
}

/// Why a span of `caller` follows `name` no more when its one declaration, in `decl`, lies
/// outside the cone of `caller`.
fn left_cone(name: &str, decl: &str, caller: &str) -> String {
    // ยง z0xqn70bp.c@y3b1n
    format!(
        "No longer followed: the one declaration of `{name}`, in {decl}, lies outside the directory of {caller} and its subdirectories, where a call follows a declaration with no mark, and no `follow` or `functional` mark pulls it in."
    )
}

/// Why the compared side, whose follow index is `follow`, follows no function `name` any more.
fn unfollowed(name: &str, follow: &FollowIndex) -> String {
    // ยง n4fbh9vd4.c@mx962
    let mut paths: Vec<String> = follow
        .declarations_of(name)
        .iter()
        .map(|p| path_of(p))
        .collect();
    paths.sort();
    paths.dedup();
    if paths.is_empty() {
        if let Some((path, line)) = follow.swallowing(name) {
            return format!(
                "No longer followed: {} does not parse with the tree-sitter grammar at line {line}, where error recovery may have swallowed a declaration of `{name}`.",
                path_of(path)
            );
        }
        return format!("No longer followed: the compared side declares no `{name}`.");
    }
    format!(
        "No longer followed: `{name}` is still declared in {}, and the span no longer reaches it through a followed call: the name has more than one candidate, the declaration left the cone of the caller, or a follow mark, a marker over its whole body or the call changed.",
        paths.join(", ")
    )
}
/// The text of each address a marker change names, as context, where no other change
/// recalls it.
fn recalls(scan: &Scan, marked: &BTreeSet<String>, changes: &[Change]) -> Vec<Change> {
    let recalled: BTreeSet<&str> = changes
        .iter()
        .filter(|c| !c.is_marker())
        .map(|c| c.address.as_str())
        .collect();
    let mut out = Vec::new();
    for law in &scan.laws {
        // ยง n4fbh9vd4.c@k0dvt
        let mut recall = |address: String, path: &Path, text: &str| {
            if marked.contains(&address) && !recalled.contains(address.as_str()) {
                out.push(Change {
                    address,
                    kind: Kind::Recall,
                    old_path: Some(path_of(path)),
                    new_path: Some(path_of(path)),
                    old_text: Some(text.to_string()),
                    new_text: Some(text.to_string()),
                    callees: Vec::new(),
                    lines: [None, None],
                    why: None,
                });
            }
        };
        recall(law.id.clone(), &law.loc.path, &law.pin_text());
        for al in &law.clauses {
            if let Some(letter) = &al.letter {
                let text = match al.header.is_empty() {
                    true => al.text.clone(),
                    false => format!("{}\n{}", al.header, al.text),
                };
                recall(format!("{}.{letter}", law.id), &al.loc.path, &text);
            }
        }
    }
    out
}

/// A marker that kept its pin, or changed only its pinned digest.
fn weighed_pin(change: &Change) -> bool {
    change.kind == Kind::Marker
        && change
            .old_text
            .as_deref()
            .zip(change.new_text.as_deref())
            .is_some_and(|(old, new)| {
                is_pinned(old) && is_pinned(new) && strip_digests(old) == strip_digests(new)
            })
}

fn strip_digests(text: &str) -> String {
    static DIGEST_RE: std::sync::LazyLock<regex::Regex> = std::sync::LazyLock::new(|| {
        regex::Regex::new(&format!("@{}", crate::marker::DIGEST)).expect("digest token")
    });
    DIGEST_RE.replace_all(text, "@DIGEST").to_string()
}

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

    #[test]
    fn a_callee_hidden_by_a_parse_error_is_named_as_such_not_as_undeclared() {
        let helpers = "def other(x):\n    return [x,\n\n\ndef cap(charge):\n    return charge\n";
        let follow = FollowIndex::from_sources(
            &[(PathBuf::from("src/helpers.py"), helpers.to_string())],
            &crate::policy::TestPaths::conventions(),
        );
        assert_eq!(
            unfollowed("cap", &follow),
            "No longer followed: src/helpers.py does not parse with the tree-sitter grammar at line 2, where error recovery may have swallowed a declaration of `cap`."
        );
        assert_eq!(
            unfollowed("gone", &follow),
            "No longer followed: the compared side declares no `gone`."
        );
    }

    #[test]
    fn the_stretches_a_drift_reads_print_in_the_order_the_law_lists_their_kinds() {
        let read = |kind: span_lang::Read| CalleeDiff {
            name: read_label(kind).to_string(),
            path: "src/lib.rs".into(),
            old: Some("a".into()),
            new: Some("b".into()),
            why: None,
            read: Some(kind),
        };
        let mut drift = change(
            "abcdefgh1.a",
            Kind::Drift,
            Some("// ยง abcdefgh1.a@aaaaa"),
            Some("// ยง abcdefgh1.a@aaaaa"),
        );
        drift.callees = vec![
            read(span_lang::Read::Attribute),
            read(span_lang::Read::Prefix),
        ];
        let out = render_diff(&[drift]);
        let at = |kind| {
            out.find(&format!("@@ {}\n", read_label(kind)))
                .unwrap_or_else(|| panic!("{out}"))
        };
        assert!(
            at(span_lang::Read::Prefix) < at(span_lang::Read::Attribute),
            "{out}"
        );
    }

    /// Each law of the review of `changes` with its status, in print order.
    fn statuses(changes: &[Change]) -> Vec<(String, review::Status)> {
        review_of(changes, &FileMap::new(), &FollowIndex::default(), "")
            .rules
            .into_iter()
            .map(|rule| (rule.id, rule.status))
            .collect()
    }

    #[test]
    fn json_strings_escape_every_control_character() {
        let raw = "a\u{1}b\tc\"d\\e\nf\u{1f}";
        let parsed: String = serde_json::from_str(&json_escape(raw)).unwrap();
        assert_eq!(parsed, raw);
    }

    #[test]
    fn the_review_opens_with_the_block_as_each_side_writes_it() {
        let rows = vec![BlockRow {
            path: "AGENTS.md".to_string(),
            attr: "default-branch",
            old: Some("main".to_string()),
            new: Some("evil".to_string()),
        }];
        let review =
            review::Review::gather("HEAD".into(), Vec::new(), 0, rows, Vec::new(), Vec::new());
        let out = review::review_markdown(&review);
        assert!(out.contains("\n## Silcrow block changed\n"), "{out}");
        assert!(out.contains("--- a/AGENTS.md\n"), "{out}");
        assert!(out.contains("\n-default-branch=\"main\"\n"), "{out}");
        assert!(out.contains("\n+default-branch=\"evil\"\n"), "{out}");
        let json: serde_json::Value =
            serde_json::from_str(&review::review_json(&review, &BTreeMap::new())).unwrap();
        assert_eq!(json["block"][0]["new"], "evil", "{json}");
    }
    use std::path::Path;

    #[test]
    fn a_marker_or_an_end_inside_a_string_is_neither_to_diff() {
        let rs = "fn f() {\n    // ยง abcdefgh1.a@aaaaa\n    let s = r\"\n// ยง abcdefgh1.a@bbbbb\n// ยง end abcdefgh1.a\n\";\n    go();\n}\n";
        let pins = marker_pins(Path::new("src/a.rs"), rs, None);
        assert_eq!(
            pins["abcdefgh1.a"],
            vec![(2, "// ยง abcdefgh1.a@aaaaa".into())]
        );
        assert_eq!(pin_lines(Path::new("src/a.rs"), rs, "abcdefgh1.a"), vec![2]);
        assert_eq!(
            line_span(Path::new("src/a.rs"), rs, 2).map(|s| s.1),
            Some(8)
        );
        let kt =
            "// ยง abcdefgh1.a@aaaaa\nval x = \"\"\"\n// ยง end abcdefgh1.a\n\"\"\"\nval y = 1\n";
        assert_eq!(line_span(Path::new("src/a.kt"), kt, 1), Some((2, 5)));
    }

    #[test]
    fn declared_law_and_clause_are_changes() {
        let old = Scan::default();
        let new = parse::scan_text(
            Path::new("docs/decisions/n.md"),
            "## T\n\n**ยง abcdefgh1 Binding sentence.**\n- (a) First clause.\n",
        );
        let changes = collect_law_changes(&old, &new);
        assert!(changes
            .iter()
            .any(|c| c.address == "abcdefgh1" && c.kind == Kind::Declared));
        assert!(changes
            .iter()
            .any(|c| c.address == "abcdefgh1.a" && c.kind == Kind::Clause));
    }

    #[test]
    fn a_struck_law_active_again_reads_as_revived() {
        let path = Path::new("docs/decisions/n.md");
        let old = parse::scan_text(
            path,
            "## T\n\n**ยง abcdefgh1 ~~Binding sentence.~~**\n\n- (a) Retry twice.\n",
        );
        let new = parse::scan_text(
            path,
            "## T\n\n**ยง abcdefgh1 Binding sentence.**\n\n- (a) Retry twice.\n",
        );
        let changes = collect_law_changes(&old, &new);
        let revived = changes.iter().find(|c| c.address == "abcdefgh1").unwrap();
        assert_eq!(revived.kind, Kind::Reused, "{changes:?}");
        assert_eq!(revived.old_text.as_deref(), Some("~~Binding sentence.~~"));
        assert!(revived.new_text.as_deref().unwrap().contains("Revives"));
        assert_eq!(statuses(&changes)[0].1, review::Status::New);
    }

    #[test]
    fn a_draft_mark_added_or_dropped_reads_as_its_transition_and_no_text_change() {
        let path = Path::new("docs/decisions/n.md");
        let owed = "## T\n\n**ยง abcdefgh1 Binding sentence.**\n\n- (a) One.\n\n- (b) Two.\n";
        let draft = "## T\n\n**ยง abcdefgh1 Binding sentence.**\n\n- (a) One.\n\n- (b)? Two.\n";
        let (o, d) = (parse::scan_text(path, owed), parse::scan_text(path, draft));
        let made = collect_law_changes(&o, &d);
        assert_eq!(made.len(), 1, "{made:?}");
        assert_eq!(made[0].kind, Kind::Draft);
        assert_eq!(made[0].address, "abcdefgh1.b");
        assert_eq!(
            [made[0].old_text.as_deref(), made[0].new_text.as_deref()],
            [Some("Two."), Some("Two.")]
        );
        assert_eq!(statuses(&made)[0].1, review::Status::Drafted);
        let dropped = collect_law_changes(&d, &o);
        assert_eq!(dropped.len(), 1, "{dropped:?}");
        assert_eq!(statuses(&dropped)[0].1, review::Status::New);
        assert!(render_diff(&made).contains(DRAFT_MADE));
        let tty = review::review_tty(&review_of(
            &made,
            &BTreeMap::new(),
            &FollowIndex::default(),
            "",
        ));
        assert!(tty.contains("+(b)? Two."), "{tty}");
        assert!(tty.contains("-(b) Two."), "{tty}");
    }

    #[test]
    fn a_burned_letter_declared_again_reads_as_reused() {
        let path = Path::new("docs/decisions/n.md");
        let old = parse::scan_text(
            path,
            "## T\n\n**ยง abcdefgh1 Binding sentence.**\n\n- (a) ~~Retry twice.~~\n",
        );
        let new = parse::scan_text(
            path,
            "## T\n\n**ยง abcdefgh1 Binding sentence.**\n\n- (a) Never retry.\n",
        );
        let changes = collect_law_changes(&old, &new);
        let reused = changes.iter().find(|c| c.address == "abcdefgh1.a").unwrap();
        assert_eq!(reused.kind, Kind::Reused, "{changes:?}");
        assert_eq!(reused.old_text.as_deref(), Some("~~Retry twice.~~"));
        assert!(reused.new_text.as_deref().unwrap().contains("burned"));
        assert_eq!(statuses(&changes)[0].1, review::Status::New);
    }

    #[test]
    fn amended_clause_keeps_law_quiet() {
        let old = parse::scan_text(
            Path::new("docs/decisions/n.md"),
            "## T\n\n**ยง abcdefgh1 Binding sentence.**\n- (a) First clause.\n",
        );
        let new = parse::scan_text(
            Path::new("docs/decisions/n.md"),
            "## T\n\n**ยง abcdefgh1 Binding sentence.**\n- (a) First clause, narrowed.\n",
        );
        let changes = collect_law_changes(&old, &new);
        assert!(changes
            .iter()
            .all(|c| c.address != "abcdefgh1" || c.kind == Kind::Clause));
        assert_eq!(changes.len(), 1);
        assert!(changes.iter().any(|c| c.address == "abcdefgh1.a"));
    }

    fn note_changes(old: &str, new: &str) -> Vec<Change> {
        let path = Path::new("docs/decisions/n.md");
        collect_law_changes(&parse::scan_text(path, old), &parse::scan_text(path, new))
    }

    #[test]
    fn a_remint_reads_the_old_markers_under_the_new_id_and_leaves_a_qualified_one() {
        let remint = BTreeMap::from([("abcdefgh4".to_string(), "abcdefgh5".to_string())]);
        let text = "fn f() {\n    // ยง abcdefgh4.a@aaaaa\n    go();\n    // ยง end abcdefgh4.a\n    // ยง libs/x:abcdefgh4@bbbbb\n    let s = \"abcdefgh4\";\n}\n";
        assert_eq!(
            as_reminted(Path::new("src/f.rs"), text.to_string(), &remint),
            "fn f() {\n    // ยง abcdefgh5.a@aaaaa\n    go();\n    // ยง end abcdefgh5.a\n    // ยง libs/x:abcdefgh4@bbbbb\n    let s = \"abcdefgh4\";\n}\n"
        );
        // A head that keeps two active ids merged two laws: neither is a remint.
        let path = Path::new("docs/decisions/n.md");
        let old = parse::scan_text(path, "**ยง abcdefgh1 One.**\n\n**ยง abcdefgh2 Two.**\n");
        let new = parse::scan_text(
            path,
            "**ยง abcdefgh3<a id=\"abcdefgh1\"></a><a id=\"abcdefgh2\"></a> Both.**\n",
        );
        assert!(reminted(&old, &new).is_empty());
    }

    #[test]
    fn a_struck_law_retires_it_and_its_active_clauses() {
        let changes = note_changes(
            "**ยง abcdefgh1 Binding sentence.**\n- (a) First.\n- (b) ~~Gone.~~\n",
            "**ยง abcdefgh1 ~~Binding sentence.~~**\n- (a) First.\n- (b) ~~Gone.~~\n",
        );
        let retired: Vec<_> = changes
            .iter()
            .filter(|c| c.kind == Kind::Retired)
            .map(|c| (c.address.as_str(), c.old_text.as_deref()))
            .collect();
        assert_eq!(
            retired,
            [
                ("abcdefgh1", Some("Binding sentence.")),
                ("abcdefgh1.a", Some("First."))
            ],
            "{changes:?}"
        );
    }

    #[test]
    fn a_struck_clause_is_retired_a_deleted_one_deleted_and_a_revived_one_reuses_its_letter() {
        let changes = note_changes(
            "**ยง abcdefgh1 Law.**\n- (a) First.\n- (b) Second.\n- (c) ~~Third.~~\n",
            "**ยง abcdefgh1 Law.**\n- (a) ~~First.~~\n- (c) Third.\n",
        );
        let kinds: Vec<_> = changes
            .iter()
            .map(|c| (c.address.as_str(), c.kind, c.old_text.is_some()))
            .collect();
        assert_eq!(
            kinds,
            [
                ("abcdefgh1.a", Kind::Retired, true),
                ("abcdefgh1.b", Kind::Deleted, true),
                ("abcdefgh1.c", Kind::Reused, true),
            ]
        );
    }

    #[test]
    fn a_strike_a_reword_a_removal_and_a_deletion_each_read_apart() {
        let old = "**ยง abcdefgh1 Struck now.**\n- (a) One.\n\n**ยง abcdefgh2 ~~Struck before.~~**\n- (a) ~~Two.~~\n  | t |\n\n**ยง abcdefgh3 Deleted.**\n- (a) Three.\n- (b) **Retired.**\n\n**ยง abcdefgh4 Reworded.**\n";
        let new = "**ยง abcdefgh1 ~~Struck now.~~**\n- (a) One.\n\n**ยง abcdefgh5<a id=\"abcdefgh4\"></a> Reworded again.**\n";
        let path = Path::new("docs/decisions/n.md");
        let (old, new) = (parse::scan_text(path, old), parse::scan_text(path, new));
        let mut changes = collect_law_changes(&old, &new);
        changes.extend(collect_deleted(&old, &new));
        changes.sort();
        changes.dedup();
        let kinds: Vec<_> = changes
            .iter()
            .map(|c| {
                (
                    c.address.as_str(),
                    c.kind,
                    c.old_text.as_deref().unwrap_or(""),
                )
            })
            .collect();
        assert_eq!(
            kinds,
            [
                ("abcdefgh1", Kind::Retired, "Struck now."),
                ("abcdefgh1.a", Kind::Retired, "One."),
                ("abcdefgh2", Kind::Removed, "~~Struck before.~~"),
                ("abcdefgh2.a", Kind::Removed, "~~Two.~~\n  | t |"),
                ("abcdefgh3", Kind::Deleted, "Deleted."),
                ("abcdefgh3.a", Kind::Deleted, "Three."),
                ("abcdefgh3.b", Kind::Deleted, "**Retired.**"),
                ("abcdefgh5", Kind::Reminted, "Reworded."),
            ]
        );
        let order: Vec<(String, &str)> = statuses(&changes)
            .into_iter()
            .map(|(id, status)| (id, status.status_key()))
            .collect();
        let want = [
            ("abcdefgh3", "deleted"),
            ("abcdefgh1", "retired"),
            ("abcdefgh2", "removed"),
            ("abcdefgh5", "reminted"),
        ]
        .map(|(id, key)| (id.to_string(), key));
        assert_eq!(order, want);
        let tty = render_diff(&changes);
        let at = |heading: &str| {
            tty.find(heading)
                .unwrap_or_else(|| panic!("{heading}\n{tty}"))
        };
        assert!(at("## ยง abcdefgh3: deleted without a strike") < at("## ยง abcdefgh1: retired"));
        assert!(
            at("## ยง abcdefgh2: removed after a published strike")
                < at("## ยง abcdefgh5: reminted from abcdefgh4 to abcdefgh5")
        );
        assert!(tty.contains("-~~Struck before.~~"), "{tty}");
    }

    #[test]
    fn a_law_never_active_is_not_new() {
        let changes = note_changes("", "**ยง abcdefgh1 ~~Born dead.~~**\n- (a) First.\n");
        assert!(changes.is_empty(), "{changes:?}");
    }

    fn change(address: &str, kind: Kind, old: Option<&str>, new: Option<&str>) -> Change {
        let path = if matches!(kind, Kind::Marker | Kind::Drift | Kind::Accepted) {
            "src/x.rs"
        } else {
            "docs/decisions/n.md"
        };
        Change {
            address: address.into(),
            kind,
            old_path: old.map(|_| path.into()),
            new_path: new.map(|_| path.into()),
            old_text: old.map(Into::into),
            new_text: new.map(Into::into),
            callees: Vec::new(),
            lines: [None, None],
            why: None,
        }
    }

    fn grouped_sample() -> Vec<Change> {
        vec![
            change("abcdefgh1", Kind::Amended, Some("Old."), Some("New.")),
            change("abcdefgh2.a", Kind::Clause, None, Some("Fresh clause.")),
            change("abcdefgh3.a", Kind::Recall, Some("Kept."), Some("Kept.")),
            change(
                "abcdefgh3.a",
                Kind::Accepted,
                Some("save();\n"),
                Some("drop();\n"),
            ),
            change("abcdefgh4.a", Kind::Retired, Some("Struck clause."), None),
            change(
                "abcdefgh4.a",
                Kind::Marker,
                Some("// ยง abcdefgh4.a@aaaaa"),
                None,
            ),
        ]
    }

    #[test]
    fn the_tty_review_is_patches_alone_with_each_law_as_one_hunk_of_its_note() {
        let tty = review::review_tty(&review_of(
            &grouped_sample(),
            &BTreeMap::new(),
            &FollowIndex::default(),
            "",
        ));
        for prose in ["# Silcrow review", "Check:", "## ", "* `", "ยง", "```"] {
            assert!(!tty.contains(prose), "{prose}\n{tty}");
        }
        assert!(
            tty.lines().all(|l| l.is_empty()
                || l.starts_with(['@', ' ', '-', '+'])
                || l.starts_with("diff --git ")),
            "{tty}"
        );
        assert!(tty.contains(" (a) Kept.\n"), "{tty}");
    }

    #[test]
    fn the_review_is_one_entry_per_law_in_order_of_risk() {
        let diff = render_diff(&grouped_sample());
        let at = |needle: &str| {
            diff.find(needle)
                .unwrap_or_else(|| panic!("{needle}\n{diff}"))
        };
        let order = [
            at("## ยง abcdefgh4: retired\n"),
            at("### abcdefgh4.a: retired\n"),
            at("-Struck clause."),
            at("## ยง abcdefgh3: behaviour change accepted\n"),
            at("### abcdefgh3.a: behaviour change accepted\n"),
            at("\n> Kept.\n"),
            at("-save();"),
            at("+drop();"),
            at("## ยง abcdefgh2: new\n"),
            at("+Fresh clause."),
            at("## ยง abcdefgh1: text changed\n"),
            at("-Old."),
            at("+New."),
        ];
        assert!(order.windows(2).all(|w| w[0] < w[1]), "{diff}");
        assert_eq!(diff.matches("## ยง abcdefgh4").count(), 1, "{diff}");
        assert!(
            diff.contains("Check: does the code below still do what abcdefgh3.a says?"),
            "{diff}"
        );
    }

    #[test]
    fn the_json_review_holds_the_same_laws_in_the_same_order() {
        let json: serde_json::Value =
            serde_json::from_str(&diff_json(Path::new("."), &grouped_sample(), 0)).unwrap();
        let laws: Vec<(&str, &str)> = json["laws"]
            .as_array()
            .unwrap()
            .iter()
            .map(|law| (law["id"].as_str().unwrap(), law["status"].as_str().unwrap()))
            .collect();
        assert_eq!(
            laws,
            [
                ("abcdefgh4", "retired"),
                ("abcdefgh3", "accepted"),
                ("abcdefgh2", "new"),
                ("abcdefgh1", "text-changed"),
            ]
        );
        let clause = &json["laws"][1]["clauses"][0];
        assert_eq!(clause["address"], "abcdefgh3.a", "{json}");
        assert_eq!(clause["text"]["new"], "Kept.", "{json}");
        assert_eq!(
            clause["locations"][0]["pins"][0]["kind"], "accepted",
            "{json}"
        );
        assert_eq!(json["laws"][3]["sentence"]["text"]["new"], "New.", "{json}");
        assert_eq!(
            json["laws"][0]["sentence"]["status"],
            serde_json::Value::Null,
            "{json}"
        );
        assert_eq!(json["ungoverned"], serde_json::json!([]), "{json}");
    }

    #[test]
    fn diff_ends_parses_two_dot_range() {
        let ends = diff_ends(Path::new("."), "main..HEAD").unwrap();
        assert_eq!(ends.old_rev, "main");
        assert_eq!(ends.new_rev.as_deref(), Some("HEAD"));
    }

    #[test]
    fn diff_ends_single_ref_uses_worktree() {
        let ends = diff_ends(Path::new("."), "HEAD~3").unwrap();
        assert_eq!(ends.old_rev, "HEAD~3");
        assert!(ends.new_rev.is_none());
    }

    #[test]
    fn an_open_range_reads_head_at_its_missing_end() {
        let ends = diff_ends(Path::new("."), "main..").unwrap();
        assert_eq!(
            (ends.old_rev.as_str(), ends.new_rev.as_deref()),
            ("main", Some("HEAD"))
        );
        let ends = diff_ends(Path::new("."), "..main").unwrap();
        assert_eq!(
            (ends.old_rev.as_str(), ends.new_rev.as_deref()),
            ("HEAD", Some("main"))
        );
    }

    #[test]
    fn an_accept_its_span_does_not_show_prints_why() {
        let mut accepted = change(
            "abcdefgh1",
            Kind::Accepted,
            Some("// ยง abcdefgh1@aaaaa\nf();\n"),
            Some("// ยง abcdefgh1@bbbbb\nf();\n"),
        );
        accepted.why = Some(UNSHOWN_MOVE.to_string());
        let recall = change("abcdefgh1", Kind::Recall, Some("Law."), Some("Law."));
        let diff = render_diff(&[accepted, recall]);
        assert!(diff.contains(&format!(" {UNSHOWN_MOVE}")), "{diff}");
    }

    #[test]
    fn diff_all_qualifies_a_nested_project_and_prints_each_law_once() {
        let lib = Some("lib".to_string());
        assert_eq!(qualify(&lib, "abcdefgh1.a"), "lib:abcdefgh1.a");
        assert_eq!(qualify(&lib, ".:abcdefgh1"), "abcdefgh1");
        assert_eq!(qualify(&lib, "svc:abcdefgh1"), "svc:abcdefgh1");
        assert_eq!(qualify(&None, "abcdefgh1"), "abcdefgh1");
        let declared = [change("abcdefgh1", Kind::Declared, None, Some("Law."))];
        let none = None;
        let mut rules = Vec::new();
        for (prefix, key) in [("lib/", &lib), ("", &none)] {
            let docs = crate::walk::Patterns::default();
            let shown = Shown {
                prefix,
                key,
                docs: &docs,
            };
            rules.extend(review::law_entries(
                &declared,
                &FileMap::new(),
                &FollowIndex::default(),
                &Callers::new(),
                &shown,
            ));
        }
        let review =
            review::Review::gather("HEAD".into(), Vec::new(), 0, Vec::new(), rules, Vec::new());
        let diff = review::review_markdown(&review);
        assert_eq!(diff.matches("## ยง abcdefgh1: new").count(), 1, "{diff}");
        assert_eq!(diff.matches("## ยง lib:abcdefgh1: new").count(), 1, "{diff}");
        assert!(
            diff.contains("Decision note `lib/docs/decisions/n.md`."),
            "{diff}"
        );
        assert!(
            diff.contains("Decision note `docs/decisions/n.md`."),
            "{diff}"
        );
    }

    #[test]
    fn split_address_keeps_a_dotted_project_path() {
        assert_eq!(
            split_address("pkg.v2:abcdefgh1.a"),
            ("pkg.v2:abcdefgh1".to_string(), Some("a".to_string()))
        );
        assert_eq!(split_address("abcdefgh1"), ("abcdefgh1".to_string(), None));
    }

    #[test]
    fn move_same_text_is_moved() {
        let old = parse::scan_text(
            Path::new("docs/decisions/old.md"),
            "**ยง abcdefgh1 Binding sentence.**\n",
        );
        let new = parse::scan_text(
            Path::new("docs/decisions/new.md"),
            "**ยง abcdefgh1 Binding sentence.**\n",
        );
        let changes = collect_law_changes(&old, &new);
        assert_eq!(changes[0].kind, Kind::Moved);
        assert_eq!(changes[0].address, "abcdefgh1");
    }

    fn sample_diff_changes() -> Vec<Change> {
        vec![
            Change {
                address: "abcdefgh1".into(),
                kind: Kind::Declared,
                old_path: None,
                new_path: Some("docs/decisions/cli/cli.md".into()),
                old_text: None,
                new_text: Some("Binding sentence.".into()),
                callees: Vec::new(),
                lines: [None, None],
                why: None,
            },
            Change {
                address: "abcdefgh1.a".into(),
                kind: Kind::Clause,
                old_path: None,
                new_path: Some("docs/decisions/cli/cli.md".into()),
                old_text: None,
                new_text: Some("First clause.".into()),
                callees: Vec::new(),
                lines: [None, None],
                why: None,
            },
            Change {
                address: "abcdefgh1.a".into(),
                kind: Kind::Marker,
                old_path: None,
                new_path: Some("src/main.rs".into()),
                old_text: None,
                new_text: Some("// ยง abcdefgh1.a".into()),
                callees: Vec::new(),
                lines: [None, None],
                why: None,
            },
            Change {
                address: "abcdefgh1.a".into(),
                kind: Kind::Marker,
                old_path: Some("src/keep.rs".into()),
                new_path: Some("src/keep.rs".into()),
                old_text: Some("// ยง abcdefgh1.a".into()),
                new_text: Some("// ยง abcdefgh1.a".into()),
                callees: Vec::new(),
                lines: [None, None],
                why: None,
            },
        ]
    }

    #[test]
    fn each_place_is_named_by_its_own_file_under_its_law() {
        let diff = render_diff(&sample_diff_changes());
        assert!(
            diff.contains("diff --git a/src/main.rs b/src/main.rs\n"),
            "{diff}"
        );
        assert!(
            diff.contains("diff --git a/src/keep.rs b/src/keep.rs\n"),
            "{diff}"
        );
        assert!(!diff.contains("cli.md#"), "{diff}");
        assert!(
            diff.contains("Decision note `docs/decisions/cli/cli.md`."),
            "{diff}"
        );
    }

    #[test]
    fn diff_opens_with_recall_then_markers() {
        let diff = render_diff(&sample_diff_changes());
        let law_at = diff.find("+Binding sentence.").expect("law recall");
        let clause_at = diff.find("+First clause.").expect("clause recall");
        let keep_at = diff.find("`src/keep.rs`").expect("unchanged path");
        let added_at = diff.find("`src/main.rs`").expect("changed path");
        assert!(law_at < clause_at);
        assert!(clause_at < keep_at);
        assert!(clause_at < added_at);
        assert!(!diff.contains("// ยง abcdefgh1.a"), "{diff}");
    }

    #[test]
    fn unchanged_marker_is_context_not_a_minus_plus() {
        let diff = render_diff(&sample_diff_changes());
        assert!(
            diff.contains("`src/keep.rs`: span of abcdefgh1.a, unchanged."),
            "{diff}"
        );
        assert!(!diff.contains("// ยง abcdefgh1.a"), "{diff}");
        assert!(
            diff.contains("`src/main.rs`: span of abcdefgh1.a, added."),
            "{diff}"
        );
    }

    #[test]
    fn one_entry_per_law_with_its_clauses_under_it() {
        let diff = render_diff(&sample_diff_changes());
        assert_eq!(diff.matches("## ยง abcdefgh1: new\n").count(), 1, "{diff}");
        assert_eq!(diff.matches("### abcdefgh1.a: new\n").count(), 1, "{diff}");
        assert!(diff.find("## ยง abcdefgh1").unwrap() < diff.find("### abcdefgh1.a").unwrap());
    }

    fn rust_outer(inner: bool, outer_body: &str, inner_body: &str) -> String {
        let pin = format!("{} abcdefgh1@aaaaa", "// ยง");
        let nested = if inner {
            let inner_pin = format!("{} abcdefgh2@bbbbb", "// ยง");
            format!("    {{\n        {inner_pin}\n        {inner_body}\n    }}\n")
        } else {
            String::new()
        };
        format!("fn outer() {{\n    {pin}\n    {outer_body}\n{nested}}}\n")
    }

    #[test]
    fn a_removed_pin_carries_its_pin_comment_and_a_vanished_project_finds_its_pins() {
        let pin = format!("{} abcdefgh1@aaaaa", "# ยง");
        let text = format!("def total(xs):\n    {pin}\n    return sum(xs)\n");
        let path = "libs/money/src/sum.py";
        let files: FileMap = BTreeMap::from([(
            path.into(),
            (
                Some(text.clone()),
                Some("def total(xs):\n    return sum(xs)\n".into()),
            ),
        )]);
        let removed = Change {
            address: "libs/money:abcdefgh1".into(),
            kind: Kind::Marker,
            old_path: Some(path.into()),
            new_path: None,
            old_text: Some(pin.clone()),
            new_text: None,
            callees: Vec::new(),
            lines: [Some(2), None],
            why: None,
        };
        let review = review_of(&[removed], &files, &FollowIndex::default(), "");
        let shown = format!("    {pin}\n    return sum(xs)\n");
        let pin_of = &review.rules[0].head.locations[0].pins[0];
        assert_eq!(pin_of.old.as_deref(), Some(shown.as_str()));
        assert_eq!(pin_of.kind, "removed");
        assert_eq!(
            pin_lines(Path::new(path), &text, "libs/money:abcdefgh1"),
            [2]
        );
        assert!(pin_lines(Path::new("src/sum.py"), &text, "libs/money:abcdefgh1").is_empty());
    }

    fn span_files(old: &str, new: &str) -> FileMap {
        BTreeMap::from([(
            "src/x.rs".into(),
            (Some(old.to_string()), Some(new.to_string())),
        )])
    }

    fn span_changes() -> Vec<Change> {
        vec![
            Change {
                address: "abcdefgh1".into(),
                kind: Kind::Amended,
                old_path: Some("docs/decisions/n.md".into()),
                new_path: Some("docs/decisions/n.md".into()),
                old_text: Some("Outer law.".into()),
                new_text: Some("Outer law, amended.".into()),
                callees: Vec::new(),
                lines: [None, None],
                why: None,
            },
            Change {
                address: "abcdefgh1".into(),
                kind: Kind::Marker,
                old_path: Some("src/x.rs".into()),
                new_path: Some("src/x.rs".into()),
                old_text: Some("// ยง abcdefgh1@aaaaa".into()),
                new_text: Some("// ยง abcdefgh1@aaaaa".into()),
                callees: Vec::new(),
                lines: [None, None],
                why: None,
            },
        ]
    }

    #[test]
    fn span_diff_keeps_change_inside_pin() {
        let old = rust_outer(false, "silcrow();", "");
        let new = rust_outer(false, "silcrow(x);", "");
        let diff = render_diff_with(&span_changes(), &span_files(&old, &new));
        assert!(diff.contains("-    silcrow();") || diff.contains("-silcrow();"));
        assert!(diff.contains("+    silcrow(x);") || diff.contains("+silcrow(x);"));
        assert!(diff.contains(" silcrow") || diff.contains("fn outer"));
    }

    #[test]
    fn span_diff_drops_change_outside_pin() {
        let old = format!(
            "fn other() {{ a(); }}\n{}",
            rust_outer(false, "silcrow();", "")
        );
        let new = format!(
            "fn other() {{ b(); }}\n{}",
            rust_outer(false, "silcrow();", "")
        );
        let diff = render_diff_with(&span_changes(), &span_files(&old, &new));
        assert!(!diff.contains("b();"), "{diff}");
        assert!(
            !diff.contains("-fn other") && !diff.contains("+fn other"),
            "{diff}"
        );
    }

    #[test]
    fn span_diff_punches_nested_inner() {
        let old = rust_outer(true, "silcrow();", "lade();");
        let new = rust_outer(true, "silcrow();", "lade(x);");
        let diff = render_diff_with(&span_changes(), &span_files(&old, &new));
        assert!(!diff.contains("lade(x);"), "{diff}");
        assert!(diff.contains("silcrow();"), "{diff}");
    }

    #[test]
    fn parsed_spans_punch_as_extract_punched_does() {
        let text = rust_outer(true, "silcrow();", "lade();");
        let (old, _) = sides(&span_files(&text, &text));
        let markers = &old.markers[Path::new("src/x.rs")];
        for line in [2, 5] {
            let (span, _, _) = punched_in(&text, markers, line).expect("span");
            assert_eq!(
                Some(span),
                extract_punched(Path::new("src/x.rs"), &text, line)
            );
        }
    }

    #[test]
    fn boundary_drift_lists_caller_laws() {
        let pin = format!("{} abcdefgh1@aaaaa", "// ยง");
        let caller_pin = format!("{} abcdefgh2@aaaaa", "// ยง");
        let tax = |body: &str| format!("fn vat() {{\n    {pin}\n    {body}\n}}\n");
        let invoice = format!("fn total() {{\n    {caller_pin}\n    vat();\n}}\n");
        let (old, new) = (tax("save(1);"), tax("save(2);"));
        let follow = FollowIndex::from_sources(
            &[
                (PathBuf::from("src/tax.rs"), new.clone()),
                (PathBuf::from("src/invoice.rs"), invoice),
            ],
            &crate::policy::TestPaths::conventions(),
        );
        let mut changes = span_changes();
        for change in &mut changes {
            for path in [&mut change.old_path, &mut change.new_path] {
                if path.as_deref() == Some("src/x.rs") {
                    *path = Some("src/tax.rs".into());
                }
            }
        }
        let files = BTreeMap::from([("src/tax.rs".into(), (Some(old), Some(new)))]);
        let diff = render_diff_follow(&changes, &files, &follow, "");
        assert!(
            diff.contains(
                " src/tax.rs:2: ยง abcdefgh1 drifted; callers carry ยง abcdefgh2 (src/invoice.rs:2). Re-read them."
            ),
            "{diff}"
        );
    }

    #[test]
    fn boundary_drift_through_a_followed_callee_lists_caller_laws() {
        let pin = format!("{} abcdefgh1@aaaaa", "// ยง");
        let caller_pin = format!("{} abcdefgh2@aaaaa", "// ยง");
        let tax = format!("fn vat() {{\n    {pin}\n    rate();\n}}\n");
        let invoice = format!("fn total() {{\n    {caller_pin}\n    vat();\n}}\n");
        let follow = FollowIndex::from_sources(
            &[
                (PathBuf::from("src/tax.rs"), tax.clone()),
                (PathBuf::from("src/invoice.rs"), invoice),
                (
                    PathBuf::from("src/rate.rs"),
                    "fn rate() {\n    two();\n}\n".into(),
                ),
            ],
            &crate::policy::TestPaths::conventions(),
        );
        let mut changes = span_changes();
        for change in &mut changes {
            if change.kind == Kind::Marker {
                change.kind = Kind::Drift;
                change.old_path = Some("src/tax.rs".into());
                change.new_path = Some("src/tax.rs".into());
                change.lines = [Some(2), Some(2)];
                change.callees = vec![CalleeDiff {
                    name: "rate".into(),
                    path: "src/rate.rs".into(),
                    old: Some("fn rate() {\n    one();\n}".into()),
                    new: Some("fn rate() {\n    two();\n}".into()),
                    why: None,
                    read: None,
                }];
            }
        }
        let untouched = render_diff_follow(&changes, &FileMap::new(), &follow, "");
        let touched = render_diff_follow(
            &changes,
            &BTreeMap::from([("src/tax.rs".into(), (Some(tax.clone()), Some(tax)))]),
            &follow,
            "",
        );
        for diff in [untouched, touched] {
            assert!(
                diff.contains(
                    "src/tax.rs:2: ยง abcdefgh1 drifted; callers carry ยง abcdefgh2 (src/invoice.rs:2). Re-read them."
                ),
                "{diff}"
            );
        }
    }

    fn declared_with_marker(marker: &str) -> Vec<Change> {
        vec![
            Change {
                address: "abcdefgh1".into(),
                kind: Kind::Declared,
                old_path: None,
                new_path: Some("docs/decisions/n.md".into()),
                old_text: None,
                new_text: Some("New law.".into()),
                callees: Vec::new(),
                lines: [None, None],
                why: None,
            },
            Change {
                address: "abcdefgh1".into(),
                kind: Kind::Marker,
                old_path: Some("src/x.rs".into()),
                new_path: Some("src/x.rs".into()),
                old_text: Some(marker.to_string()),
                new_text: Some(marker.to_string()),
                callees: Vec::new(),
                lines: [None, None],
                why: None,
            },
        ]
    }

    #[test]
    fn new_recall_does_not_paint_unchanged_span() {
        let src = rust_outer(false, "silcrow();", "");
        let marker = format!("{} abcdefgh1@aaaaa", "// ยง");
        let diff = render_diff_with(&declared_with_marker(&marker), &span_files(&src, &src));
        assert!(diff.contains("+New law."), "{diff}");
        assert!(!diff.contains("// ยง abcdefgh1"), "{diff}");
        assert!(
            diff.contains("    silcrow();\n") || diff.contains(" silcrow();"),
            "{diff}"
        );
        assert!(!diff.contains("+    silcrow();"), "{diff}");
        assert!(!diff.contains("-    silcrow();"), "{diff}");
        assert!(!diff.contains("+fn outer"), "{diff}");
        assert!(!diff.contains("-fn outer"), "{diff}");
    }

    #[test]
    fn amended_recall_does_not_paint_unchanged_span() {
        let src = rust_outer(false, "silcrow();", "");
        let mut changes = span_changes();
        changes[0].old_text = Some("Old law.".into());
        changes[0].new_text = Some("New law.".into());
        let diff = render_diff_with(&changes, &span_files(&src, &src));
        assert!(diff.contains("-Old law."), "{diff}");
        assert!(diff.contains("+New law."), "{diff}");
        assert!(!diff.contains("+    silcrow();"), "{diff}");
        assert!(!diff.contains("-    silcrow();"), "{diff}");
        assert!(!diff.contains("// ยง abcdefgh1"), "{diff}");
    }

    #[test]
    fn bare_marker_is_comment_only() {
        let pin = format!("{} abcdefgh1", "// ยง");
        let src = format!("fn outer() {{\n    {pin}\n    silcrow();\n}}\n");
        let diff = render_diff_with(&declared_with_marker(&pin), &span_files(&src, &src));
        assert!(diff.contains("+New law."), "{diff}");
        assert!(!diff.contains("// ยง abcdefgh1"), "{diff}");
        assert!(!diff.contains("silcrow();"), "{diff}");
        assert!(!diff.contains("fn outer"), "{diff}");
    }

    #[test]
    fn retired_recall_is_all_minus() {
        let changes = vec![Change {
            address: "abcdefgh1".into(),
            kind: Kind::Retired,
            old_path: Some("docs/decisions/n.md".into()),
            new_path: None,
            old_text: Some("Gone law.".into()),
            new_text: None,
            callees: Vec::new(),
            lines: [None, None],
            why: None,
        }];
        let diff = render_diff(&changes);
        assert!(diff.contains("-Gone law."), "{diff}");
        assert!(!diff.contains("+Gone law."), "{diff}");
    }

    #[test]
    fn install_span_is_install_not_run() {
        let src = include_str!("plane.rs");
        // The pin moves whenever install or its clause does; read it rather than freeze it.
        let pin = src
            .split("hqv22s05t@")
            .nth(1)
            .map(|rest| &rest[..5])
            .expect("plane.rs pins hqv22s05t");
        let files = BTreeMap::from([("src/plane.rs".into(), (None, Some(src.to_string())))]);
        let changes = vec![
            Change {
                address: "hqv22s05t".into(),
                kind: Kind::Declared,
                old_path: None,
                new_path: Some("docs/decisions/harness.md".into()),
                old_text: None,
                new_text: Some("`silcrow install` writes the skill pointer, and without `--user` also the `AGENTS.md` block and the hooks.".into()),
                callees: Vec::new(),
                lines: [None, None],
                why: None,
            },
            Change {
                address: "hqv22s05t".into(),
                kind: Kind::Marker,
                old_path: None,
                new_path: Some("src/plane.rs".into()),
                old_text: None,
                new_text: Some(format!("{} hqv22s05t@{pin}", "// ยง")),
                callees: Vec::new(),
                lines: [None, None],
                why: None,
            },
        ];
        let diff = render_diff_with(&changes, &files);
        assert!(diff.contains("+pub fn install"), "{diff}");
        assert!(!diff.contains("// ยง hqv22s05t"), "{diff}");
        assert!(diff.contains("install_skill"), "{diff}");
        assert!(!diff.contains("pub fn run"), "{diff}");
    }

    #[test]
    fn two_pins_same_law_are_two_spans() {
        let pin = format!("{} a2d8n8r1q@dnfcm", "// ยง");
        let src = format!(
            "\
fn silcrow() {{
    {pin}
    let _ = r#\"name: \"silcrow\"\"#;
}}

fn skill_state() {{
    let leftover = true;
}}

fn lade() {{
    {pin}
    let _ = r#\"name: \"lade\"\"#;
}}
"
        );
        let files = BTreeMap::from([(
            "src/plane.rs".into(),
            (Some(src.to_string()), Some(src.to_string())),
        )]);
        let changes = vec![
            Change {
                address: "a2d8n8r1q".into(),
                kind: Kind::Amended,
                old_path: Some("docs/decisions/plane.md".into()),
                new_path: Some("docs/decisions/plane.md".into()),
                old_text: Some("Plane.".into()),
                new_text: Some("Plane, amended.".into()),
                callees: Vec::new(),
                lines: [None, None],
                why: None,
            },
            Change {
                address: "a2d8n8r1q".into(),
                kind: Kind::Marker,
                old_path: Some("src/plane.rs".into()),
                new_path: Some("src/plane.rs".into()),
                old_text: Some(format!("{} a2d8n8r1q@dnfcm", "// ยง")),
                new_text: Some(format!("{} a2d8n8r1q@dnfcm", "// ยง")),
                callees: Vec::new(),
                lines: [None, None],
                why: None,
            },
        ];
        let diff = render_diff_with(&changes, &files);
        assert!(diff.contains("name: \"silcrow\""), "{diff}");
        assert!(diff.contains("name: \"lade\""), "{diff}");
        assert!(!diff.contains("skill_state"), "{diff}");
    }

    #[test]
    fn declared_change_renders_note_path() {
        let old = Scan::default();
        let new = parse::scan_text(
            Path::new("docs/decisions/n.md"),
            "**ยง abcdefgh1 Binding sentence.**\n",
        );
        let changes = collect_law_changes(&old, &new);
        let diff = render_diff(&changes);
        assert!(
            diff.contains("diff --git a/docs/decisions/n.md b/docs/decisions/n.md\n"),
            "{diff}"
        );
        assert!(
            diff.contains(" @@ text of abcdefgh1\n+Binding sentence"),
            "{diff}"
        );
    }

    /// Both sides of a `FileMap`, as the code files they hold.
    fn sides(files: &FileMap) -> (Side, Side) {
        let side = |old: bool| {
            Side::of(
                files
                    .iter()
                    .filter_map(|(path, (before, after))| {
                        let text = if old { before } else { after };
                        Some((PathBuf::from(path), text.clone()?))
                    })
                    .collect(),
                &TestPaths::conventions(),
                None,
            )
        };
        (side(true), side(false))
    }

    fn repin_change(old: &str, new: &str) -> (Change, FileMap) {
        let mut files = FileMap::new();
        files.insert("src/x.rs".into(), (Some(old.into()), Some(new.into())));
        let changes = marker_diff(Path::new("src/x.rs"), [Some(old), Some(new)], [None, None]);
        assert_eq!(changes.len(), 1, "{changes:?}");
        (changes[0].clone(), files)
    }

    #[test]
    fn repin_over_the_same_span_folds() {
        let (change, files) = repin_change(
            "fn f() {\n    // ยง abcdefgh1@aaaaa\n    save();\n}\n",
            "fn f() {\n    // ยง abcdefgh1@bbbbb\n    save();\n}\n",
        );
        assert!(weighed_pin(&change));
        let (old, new) = sides(&files);
        assert!(drift_of(&change, &files, &old, &new, false)
            .unwrap()
            .is_none());
    }

    #[test]
    fn two_pins_written_alike_are_each_weighed_at_their_own_span() {
        let src = |second: &str| {
            format!("fn f() {{\n    // ยง abcdefgh1@aaaaa\n    save();\n}}\n\nfn g() {{\n    // ยง abcdefgh1@aaaaa\n    {second}\n}}\n")
        };
        let (old, new) = (src("load();"), src("drop();"));
        let mut files = FileMap::new();
        files.insert("src/x.rs".into(), (Some(old.clone()), Some(new.clone())));
        let changes = marker_diff(
            Path::new("src/x.rs"),
            [Some(&old), Some(&new)],
            [None, None],
        );
        assert_eq!(changes.len(), 2, "{changes:?}");
        let (old_side, new_side) = sides(&files);
        let drifts: Vec<Change> = changes
            .iter()
            .filter_map(|c| drift_of(c, &files, &old_side, &new_side, false).unwrap())
            .collect();
        assert_eq!(drifts.len(), 1, "{drifts:?}");
        assert!(drifts[0].new_text.as_deref().unwrap().contains("drop();"));
    }

    #[test]
    fn repin_over_a_changed_span_is_accepted() {
        let (change, files) = repin_change(
            "fn f() {\n    // ยง abcdefgh1@aaaaa\n    save();\n}\n",
            "fn f() {\n    // ยง abcdefgh1@bbbbb\n    drop();\n}\n",
        );
        let (old, new) = sides(&files);
        let drift = drift_of(&change, &files, &old, &new, false)
            .unwrap()
            .expect("drift");
        assert_eq!(drift.kind, Kind::Accepted);
        assert!(drift.old_text.unwrap().contains("save();"));
        assert!(drift.new_text.unwrap().contains("drop();"));
    }

    #[test]
    fn an_accept_shows_each_changed_stretch_it_reads_beside_the_span_and_names_it() {
        let src = |guard: &str, digest: &str, body: &str| {
            format!("fn f(a: u32) -> u32 {{\n    if a > {guard} {{\n        return 0;\n    }}\n    // ยง abcdefgh1@{digest}\n    let r = a + {body};\n    // ยง end abcdefgh1\n    r\n}}\n")
        };
        for (body, span_moved) in [("1", false), ("2", true)] {
            let (change, files) = repin_change(&src("10", "aaaaa", "1"), &src("99", "bbbbb", body));
            let (old, new) = sides(&files);
            let drift = drift_of(&change, &files, &old, &new, false)
                .unwrap()
                .expect("drift");
            assert_eq!(drift.kind, Kind::Accepted);
            assert_eq!(
                strip_digests(drift.old_text.as_deref().unwrap())
                    != strip_digests(drift.new_text.as_deref().unwrap()),
                span_moved
            );
            assert_eq!(drift.callees.len(), 1, "{:?}", drift.callees);
            let read = &drift.callees[0];
            assert_eq!(read.read, Some(span_lang::Read::Prefix));
            assert!(
                read.old.as_deref().unwrap().contains("if a > 10 {"),
                "{read:?}"
            );
            assert!(
                read.new.as_deref().unwrap().contains("if a > 99 {"),
                "{read:?}"
            );
            assert!(
                drift
                    .why
                    .as_deref()
                    .unwrap()
                    .contains("code before the span in its function"),
                "{:?}",
                drift.why
            );
            let json: serde_json::Value =
                serde_json::from_str(&diff_json(Path::new("."), std::slice::from_ref(&drift), 0))
                    .unwrap();
            let location = &json["laws"][0]["sentence"]["locations"][0];
            assert_eq!(location["reads"][0]["read"], "prefix", "{json}");
            let tty = render_diff_with(std::slice::from_ref(&drift), &FileMap::new());
            assert!(
                tty.contains(" @@ code before the span in its function\n"),
                "{tty}"
            );
            assert!(tty.contains("+    if a > 99 {"), "{tty}");
        }
    }

    #[test]
    fn a_drift_shows_the_signature_and_the_call_that_receives_its_closure_as_one_prefix() {
        let src = |ty: &str, adapter: &str| {
            format!("fn f(xs: &[{ty}]) -> usize {{\n    xs.iter().{adapter}(|x| {{\n        // ยง abcdefgh1@aaaaa\n        **x > 1\n    }}).count()\n}}\n")
        };
        let (change, files) = (
            Change {
                address: "abcdefgh1".into(),
                kind: Kind::Marker,
                old_path: Some("src/x.rs".into()),
                new_path: Some("src/x.rs".into()),
                old_text: Some("// ยง abcdefgh1@aaaaa".into()),
                new_text: Some("// ยง abcdefgh1@aaaaa".into()),
                callees: Vec::new(),
                lines: [None, None],
                why: None,
            },
            span_files(&src("u32", "filter"), &src("u64", "take_while")),
        );
        let (old, new) = sides(&files);
        let drift = drift_of(&change, &files, &old, &new, false)
            .unwrap()
            .expect("drift");
        assert_eq!(drift.kind, Kind::Drift);
        let reads: Vec<_> = drift.callees.iter().map(|c| c.read).collect();
        assert_eq!(
            reads,
            [Some(span_lang::Read::Prefix)],
            "{:?}",
            drift.callees
        );
        let prefix = drift.callees[0].new.as_deref().unwrap();
        assert!(
            prefix.contains("u64") && prefix.contains("take_while"),
            "{prefix}"
        );
        let why = drift.why.unwrap();
        assert!(
            why.contains("the code before the span in its function, which changed"),
            "{why}"
        );
    }

    #[test]
    fn a_kept_pin_over_a_moved_callee_is_a_drift_naming_it() {
        let src = |body: &str| {
            format!("fn f() {{\n    // ยง abcdefgh1@aaaaa\n    save();\n}}\n\nfn save() {{\n    {body}\n}}\n")
        };
        let (change, files) = (
            Change {
                address: "abcdefgh1".into(),
                kind: Kind::Marker,
                old_path: Some("src/x.rs".into()),
                new_path: Some("src/x.rs".into()),
                old_text: Some("// ยง abcdefgh1@aaaaa".into()),
                new_text: Some("// ยง abcdefgh1@aaaaa".into()),
                callees: Vec::new(),
                lines: [None, None],
                why: None,
            },
            span_files(&src("write();"), &src("write_twice();")),
        );
        let (old, new) = sides(&files);
        let drift = drift_of(&change, &files, &old, &new, false)
            .unwrap()
            .expect("drift");
        assert_eq!(drift.kind, Kind::Drift);
        assert_eq!(drift.old_text, drift.new_text);
        assert_eq!(drift.callees.len(), 1, "{:?}", drift.callees);
        let callee = &drift.callees[0];
        assert_eq!(
            (callee.name.as_str(), callee.path.as_str()),
            ("save", "src/x.rs")
        );
        assert!(callee.old.as_deref().unwrap().contains("write();"));
        assert!(callee.new.as_deref().unwrap().contains("write_twice();"));
        let diff = render_diff_with(std::slice::from_ref(&drift), &files);
        assert!(diff.contains(" @@ followed callee save\n"), "{diff}");
        assert!(diff.contains("-    write();"), "{diff}");
        assert!(diff.contains("+    write_twice();"), "{diff}");
        let json: serde_json::Value =
            serde_json::from_str(&diff_json(Path::new("."), std::slice::from_ref(&drift), 0))
                .unwrap();
        let location = &json["laws"][0]["sentence"]["locations"][0];
        assert_eq!(location["callees"][0]["name"], "save", "{json}");
        assert_eq!(location["pins"][0]["kind"], "drift", "{json}");
    }

    /// The drift of the pin `abcdefgh1` of src/x.rs between two trees, each file mapped to
    /// its text before and after.
    fn drift_between(files: &[(&str, &str, &str)]) -> Option<Change> {
        let files: FileMap = files
            .iter()
            .map(|(path, old, new)| {
                (
                    path.to_string(),
                    (Some(old.to_string()), Some(new.to_string())),
                )
            })
            .collect();
        let change = Change {
            address: "abcdefgh1".into(),
            kind: Kind::Marker,
            old_path: Some("src/x.rs".into()),
            new_path: Some("src/x.rs".into()),
            old_text: Some("// ยง abcdefgh1@aaaaa".into()),
            new_text: Some("// ยง abcdefgh1@aaaaa".into()),
            callees: Vec::new(),
            lines: [None, None],
            why: None,
        };
        let (old, new) = sides(&files);
        drift_of(&change, &files, &old, &new, false).unwrap()
    }

    #[test]
    fn a_call_rebound_by_an_import_is_a_drift() {
        let main = |a: &str, b: &str| {
            format!("mod a;\nmod b;\nuse {a}::step as first;\nuse {b}::step as second;\nfn f(x: u32) -> u32 {{\n    // ยง abcdefgh1@aaaaa\n    first(x) - second(x)\n}}\n")
        };
        let (old, new) = (main("a", "b"), main("b", "a"));
        let rebound = drift_between(&[
            ("src/x.rs", &old, &new),
            (
                "src/a.rs",
                "pub fn step(x: u32) -> u32 { x * 2 }\n",
                "pub fn step(x: u32) -> u32 { x * 2 }\n",
            ),
            (
                "src/b.rs",
                "pub fn step(x: u32) -> u32 { x + 9 }\n",
                "pub fn step(x: u32) -> u32 { x + 9 }\n",
            ),
        ])
        .expect("two swapped imports are a drift");
        assert_ne!(rebound.why.as_deref(), Some(CALLEE_EDIT), "{rebound:?}");
        // A callee moved behind a re-export reads alike: no drift.
        let same = "mod m1;\nuse m1::helper;\nfn f(x: u32) -> u32 {\n    // ยง abcdefgh1@aaaaa\n    helper(x)\n}\n";
        assert!(drift_between(&[
            ("src/x.rs", same, same),
            (
                "src/m1.rs",
                "pub fn helper(x: u32) -> u32 { x }\n",
                "pub fn helper(x: u32) -> u32 { x }\n"
            ),
        ])
        .is_none());
    }

    #[test]
    fn an_edited_callee_says_a_callee_changed_and_names_no_rebinding() {
        let main = "mod m;\nuse m::helper;\nfn f(x: u32) -> u32 {\n    // ยง abcdefgh1@aaaaa\n    helper(x)\n}\n";
        let drift = drift_between(&[
            ("src/x.rs", main, main),
            (
                "src/m.rs",
                "pub fn helper(x: u32) -> u32 { x * 7 }\n",
                "pub fn helper(x: u32) -> u32 { x * 8 }\n",
            ),
        ])
        .expect("an edited callee is a drift");
        assert_eq!(drift.callees.len(), 1, "{drift:?}");
        assert_eq!(drift.why.as_deref(), Some(CALLEE_EDIT), "{drift:?}");
    }

    #[test]
    fn an_unreadable_span_fails_instead_of_folding() {
        let (mut change, files) = repin_change(
            "fn f() {\n    // ยง abcdefgh1@aaaaa\n    save();\n}\n",
            "fn f() {\n    // ยง abcdefgh1@bbbbb\n    save();\n}\n",
        );
        change.new_text = Some("// ยง abcdefgh1@ccccc".into());
        let (old, new) = sides(&files);
        let err = drift_of(&change, &files, &old, &new, false).unwrap_err();
        assert!(err.to_string().contains("is not in the file"), "{err}");
        change.new_path = Some("src/gone.rs".into());
        assert!(drift_of(&change, &files, &old, &new, false).is_err());
    }

    #[test]
    fn a_subject_word_is_not_a_remint_mark() {
        let change = Change {
            address: "abcdefgh1".into(),
            kind: Kind::Marker,
            old_path: Some("src/x.rs".into()),
            new_path: Some("src/x.rs".into()),
            old_text: Some("ยง abcdefgh1 The graph fails open.".into()),
            new_text: Some("ยง abcdefgh1 The graph fails closed.".into()),
            callees: Vec::new(),
            lines: [None, None],
            why: None,
        };
        assert!(!weighed_pin(&change));
    }

    #[test]
    fn path_hash_in_source_is_not_a_marker() {
        let changes = marker_diff(
            Path::new("src/diff.rs"),
            [
                Some("fn x() {}\n"),
                Some("assert!(diff.contains(\"docs/decisions/cli/cli.md#abcdefgh1.a\"));\n"),
            ],
            [None, None],
        );
        assert!(changes.is_empty(), "{changes:?}");
    }

    #[test]
    fn a_marker_in_a_markdown_fence_is_no_marker_change() {
        let fenced = "Text.\n\n```ts\nfunction f() {\n  // ยง abcdefgh1@aaaaa\n  go();\n}\n```\n";
        let changes = marker_diff(
            Path::new("README.md"),
            [Some(fenced), Some(&fenced.replace("go();", "stop();"))],
            [None, None],
        );
        assert!(changes.is_empty(), "{changes:?}");
    }

    #[test]
    fn pin_only_digest_is_one_marker_change() {
        let changes = marker_diff(
            Path::new("src/x.rs"),
            [
                Some("// ยง abcdefgh1@aaaaa\n"),
                Some("// ยง abcdefgh1@bbbbb\n"),
            ],
            [None, None],
        );
        assert_eq!(changes.len(), 1);
        assert!(weighed_pin(&changes[0]));
    }

    #[test]
    fn a_remint_keeps_every_group_in_json() {
        let json: serde_json::Value =
            serde_json::from_str(&diff_json(Path::new("."), &[], 3)).unwrap();
        assert_eq!(
            (json["remint"].clone(), json["pinned"].clone()),
            (true.into(), 3.into())
        );
        for key in ["block", "laws", "ungoverned"] {
            assert!(json[key].is_array(), "{key}: {json}");
        }
        let empty = review::Review::gather(
            "HEAD".into(),
            Vec::new(),
            3,
            Vec::new(),
            Vec::new(),
            Vec::new(),
        );
        assert!(review::review_markdown(&empty)
            .contains("scheme   span digest remint (3 pinned markers)"));
    }

    #[test]
    fn diff_json_nests_law_clause_marker() {
        let changes = vec![
            Change {
                address: "abcdefgh1".into(),
                kind: Kind::Declared,
                old_path: None,
                new_path: Some("docs/decisions/n.md".into()),
                old_text: None,
                new_text: Some("Binding sentence".into()),
                callees: Vec::new(),
                lines: [None, None],
                why: None,
            },
            Change {
                address: "abcdefgh1.a".into(),
                kind: Kind::Clause,
                old_path: None,
                new_path: Some("docs/decisions/n.md".into()),
                old_text: None,
                new_text: Some("First".into()),
                callees: Vec::new(),
                lines: [None, None],
                why: None,
            },
            Change {
                address: "abcdefgh1.a".into(),
                kind: Kind::Marker,
                old_path: None,
                new_path: Some("src/x.rs".into()),
                old_text: None,
                new_text: Some("ยง abcdefgh1.a".into()),
                callees: Vec::new(),
                lines: [None, None],
                why: None,
            },
        ];
        let json: serde_json::Value = serde_json::from_str(&diff_json(
            Path::new(env!("CARGO_MANIFEST_DIR")),
            &changes,
            0,
        ))
        .unwrap();
        let law = &json["laws"][0];
        assert_eq!(
            (&law["id"], &law["status"]),
            (&"abcdefgh1".into(), &"new".into())
        );
        assert_eq!(law["sentence"]["text"]["new"], "Binding sentence", "{json}");
        let clause = &law["clauses"][0];
        assert_eq!(clause["letter"], "a", "{json}");
        let location = &clause["locations"][0];
        assert_eq!(location["path"], "src/x.rs", "{json}");
        assert_eq!(location["doc"], false, "{json}");
        assert_eq!(location["pins"][0]["kind"], "added", "{json}");
    }

    #[test]
    fn empty_diff_stream_is_silent() {
        emit_diff_stream("").unwrap();
    }

    #[test]
    fn the_arguments_are_revisions_alone_and_two_are_a_range() {
        let revs =
            |args: &[&str]| revision(&args.iter().map(|a| a.to_string()).collect::<Vec<_>>());
        assert_eq!(revs(&[]).unwrap(), None);
        // A nine-character SHA reads as a revision, never as a law id.
        assert_eq!(revs(&["9a823256a"]).unwrap().as_deref(), Some("9a823256a"));
        assert_eq!(
            revs(&["main", "HEAD"]).unwrap().as_deref(),
            Some("main..HEAD")
        );
        assert_eq!(
            revs(&["main...HEAD"]).unwrap().as_deref(),
            Some("main...HEAD")
        );
        assert!(revs(&["main..HEAD", "x"]).is_err());
        assert_eq!(range_end(Some("main...")).as_deref(), Some("HEAD"));
        assert_eq!(range_end(Some("main..topic")).as_deref(), Some("topic"));
        assert_eq!(range_end(Some("main")), None);
    }

    #[test]
    fn law_id_keeps_its_clauses() {
        assert!(keep_address("k7m2x9p4a.v", "k7m2x9p4a"));
        assert!(!keep_address("k7m2x9p4a.v", "k7m2x9p4a.u"));
    }
}