silcrow 0.2.0

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
use anyhow::{bail, Context, Result};
use regex::Regex;
use std::collections::{BTreeMap, BTreeSet};
use std::path::{Component, Path, PathBuf};
use std::sync::LazyLock;

use crate::hash;
use crate::marker::{DIGEST, ID, PROJECTPATH};
use crate::parse;
use crate::walk;
use crate::workspace::{self, LawScans, ProjectRef, Workspace};
use crate::write::{self, WritePlan};

/// A qualified reference as any form writes it: a marker or an end, an adoption, or the text of
/// a cite link.
static QREF_RE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(&format!(
        r"(ยง\s*(?:end\s+)?|\[(?:ยง\s*)?)({PROJECTPATH}):({ID})\b"
    ))
    .expect("qualified reference")
});

/// An unqualified reference in the same forms. Group 3 holds the colon of a qualified one, which
/// `QREF_RE` reads instead.
static UREF_RE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(&format!(r"(ยง\s*(?:end\s+)?|\[(?:ยง\s*)?)({ID})\b(:?)"))
        .expect("unqualified reference")
});

static QREF_ONE_RE: LazyLock<Regex> = LazyLock::new(|| on_one_line(&QREF_RE));

static UREF_ONE_RE: LazyLock<Regex> = LazyLock::new(|| on_one_line(&UREF_RE));

/// `re` as it reads a `ยง one` line, where an entry also opens after `ยง one` or a comma.
fn on_one_line(re: &Regex) -> Regex {
    let lead = r"ยง\s*(?:end\s+)?|";
    assert!(
        re.as_str().contains(lead),
        "a pointer regex opens with a marker lead"
    );
    Regex::new(
        &re.as_str()
            .replacen(lead, r"ยง\s*(?:end\s+|one\s+)?|,\s*|", 1),
    )
    .expect("one-line pointer regex")
}

static QCITE_RE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(&format!(r"^(?:ยง\s*)?({PROJECTPATH}):({ID})")).expect("qualified cite text")
});

static ADOPT_LINE_RE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(&format!(
        r"^\s*\*\*ยง\s*{PROJECTPATH}:{ID}(?:\.[a-z]+)?\*\*\s*$"
    ))
    .expect("adoption line")
});

/// What `fix` knows of the workspace around the project it rewrites.
pub struct Around<'a> {
    pub own: &'a str,
    /// Ids and alias anchors of the laws of the current project.
    pub own_ids: BTreeSet<String>,
    /// Laws of every other project: project path, then id, then the note relative to that project.
    pub others: BTreeMap<String, BTreeMap<String, PathBuf>>,
}

impl<'a> Around<'a> {
    fn new(own: &'a str, scan: &parse::Scan, scans: &LawScans) -> Self {
        Self {
            own,
            own_ids: scan
                .laws
                .iter()
                .flat_map(|law| std::iter::once(&law.id).chain(&law.aliases))
                .cloned()
                .collect(),
            others: scans
                .scans
                .iter()
                .map(|(key, scan)| {
                    let ids = scan
                        .laws
                        .iter()
                        .map(|law| (law.id.clone(), law.loc.path.clone()))
                        .collect();
                    (key.clone(), ids)
                })
                .collect(),
        }
    }

    fn declaring(&self, id: &str) -> Vec<&str> {
        let mut projects: Vec<&str> = self
            .others
            .iter()
            .filter(|(_, ids)| ids.contains_key(id))
            .map(|(key, _)| key.as_str())
            .collect();
        if self.own_ids.contains(id) {
            projects.push(self.own);
        }
        projects.sort();
        projects
    }
}

static CITE_LINK_RE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(&format!(
        r"\[([^\]]*)\]\(([^)#]*)(#({ID})(?:\.([a-z]+))?(?:@{DIGEST})?)\)"
    ))
    .expect("cite link regex")
});

static BARE_ID_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(&format!(r"\b({ID})((?:\.[a-z]+)?)\b")).expect("bare id"));

/// Spans where an id is already a reference form: code, links, anchors, `ยง id`.
/// Each is matched on its own, so overlapping spans all mask.
static NOT_BARE_RES: LazyLock<Vec<Regex>> = LazyLock::new(|| {
    [
        r"`[^`]*`",
        r"\[[^\]]*\]\([^)]*\)",
        r"<a\s[^>]*>[^<]*</a>",
        r"<[^>]+>",
        r"ยง\s*\S+",
    ]
    .iter()
    .map(|re| Regex::new(re).expect("not bare"))
    .collect()
});

/// The head of a law up to its carrying sentence: the sign, the id or its anchor wrap, and
/// the alias anchors after it.
static HEAD_PREFIX_RE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(&format!(
        r#"^\s*\*\*ยง!?\??\s*(?:<a\s+id="{ID}">{ID}</a>|{ID}\b)(?:<a\s+id="{ID}"></a>)*"#
    ))
    .expect("head prefix regex")
});

static HEAD_RE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(&format!(
        r#"^\s*\*\*ยง!?\??\s*(?:<a\s+id="({ID})">|(\+[a-z0-9-]+)|({ID})\b)"#
    ))
    .expect("law head")
});

static PROVISIONAL_CLAUSE_RE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"^(\s*(?:[-*+]\s+|\d+\.\s+)?)\(\+\)(\??)(\s+)").expect("provisional clause")
});

/// A row of a lettered table whose first cell opens with `(+)`.
static PROVISIONAL_ROW_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^(\s*\|\s*)\(\+\)(\s+)").expect("provisional row"));

static LETTERED_ROW_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^\s*\|\s*\((?:[a-z]+|\+)\)(?:\s|$)").expect("lettered row"));

static LETTERED_ITEM_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^\s*- \([a-z]+\)\??(?:\s|$)").expect("lettered item"));

static SECTION_BREAK_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^##\s+").expect("section break"));

pub struct ResolvePlan {
    pub writes: WritePlan,
    pub actions: Vec<String>,
    pub warnings: Vec<String>,
}

pub fn plan(ws: &Workspace, project: &ProjectRef, scheme_remint: bool) -> Result<ResolvePlan> {
    if scheme_remint {
        return plan_scheme_remint(&project.dir, ws.base_ref("HEAD")?.as_deref());
    }
    plan_scoped(ws, project, None)
}

/// When `staged_only` is set, provisional declarations are discovered only in those
/// decision paths, the staged files of `pre-commit`. Pointer rewrites still scan the tree.
pub fn plan_scoped(
    ws: &Workspace,
    project: &ProjectRef,
    staged_only: Option<&[PathBuf]>,
) -> Result<ResolvePlan> {
    // ยง fxas3vhge.c@f9jnf
    let mut actions = Vec::new();
    let mut warnings = Vec::new();
    let mut name_to_id: BTreeMap<String, String> = BTreeMap::new();

    let root = project.dir.as_path();
    let scan = parse::scan_root(root)?;
    let scans = ws.law_scans(&project.key)?;
    let around = Around::new(&project.key, &scan, &scans);
    let mut id_owners: BTreeMap<String, String> = BTreeMap::new();
    for law in &scan.laws {
        if hash::is_provisional_id(&law.id) {
            continue;
        }
        if let Some(first) = id_owners.get(&law.id) {
            bail!(
                "duplicate id {}: first at {}, also at {}:{}",
                law.id,
                first,
                law.loc.path.display(),
                law.loc.line
            );
        }
        id_owners.insert(
            law.id.clone(),
            format!("{}:{}", law.loc.path.display(), law.loc.line),
        );
        if !hash::verify_id(&law.name, &law.id) {
            warnings.push(format!(
                "HASH {} at {}:{} does not match its carrying sentence (use accept)",
                law.id,
                law.loc.path.display(),
                law.loc.line
            ));
        }
    }

    let aliases = alias_pointer_re(&scan)?;
    let one_line = aliases.as_ref().map(|(re, _)| on_one_line(re));
    let scope: Vec<PathBuf> = decision_paths_for_scope(root, staged_only)?
        .into_iter()
        .map(|p| p.strip_prefix(root).unwrap_or(&p).to_path_buf())
        .collect();
    let declared_paths = build_id_to_path(&scan, &BTreeMap::new());
    let mut name_heads: BTreeMap<&str, String> = BTreeMap::new();
    for law in &scan.laws {
        // The head mints the id. A cite of `ยง +name` elsewhere carries no sentence.
        let Some(name) = law.id.strip_prefix('+') else {
            continue;
        };
        if !scope.contains(&law.loc.path) {
            continue;
        }
        // ยง fxas3vhge.a@h1hn4
        let here = format!("{}:{}", law.loc.path.display(), law.loc.line);
        if let Some(first) = name_heads.get(name) {
            bail!(
                "{here}: ยง +{name} is also the provisional name of the head at {first}: a name is unique within the change. Rename one of the two."
            );
        }
        name_heads.insert(name, here.clone());
        // ยง end fxas3vhge.a
        // The cite is rewritten to the current id below, so the id hashes the sentence as written.
        // ยง nth5nbchz.d@w499q
        let carrying = link_bare_ids(
            &current_ids(&law.name.replace(&format!("ยง +{name}"), ""), &aliases),
            &law.loc.path,
            &declared_paths,
            &BTreeSet::new(),
        );
        // ยง end nth5nbchz.d
        if hash::canonicalise(&carrying).is_empty() {
            bail!(
                "{}:{}: provisional ยง +{name} has no carrying sentence",
                law.loc.path.display(),
                law.loc.line
            );
        }
        let id = hash::mint_id(&carrying);
        // ยง cmx8g7zp2.a@1ttjz
        if let Some(first) = id_owners.get(&id) {
            bail!(
                "{here}: ยง +{name} mints {id}, which the law at {first} already carries: a duplicate id is refused. Reword one of the two carrying sentences."
            );
        }
        // ยง end cmx8g7zp2.a
        id_owners.insert(id.clone(), here);
        actions.push(format!("MINT +{name} -> {id}"));
        name_to_id.insert(name.to_string(), id);
    }

    refuse_taken_ids(ws, root, &scan, &name_to_id)?;
    let id_to_path = build_id_to_path(&scan, &name_to_id);
    let mut letters = letters_per_law(&scan, &name_to_id);
    if has_provisional_clause(root)? {
        burn_published_letters(ws, root, &scan, &mut letters)?;
    }
    let paths = collect_rewrite_paths(root)?;
    let paths_of = walk::Project::at(root)?;
    let implemented = named_drafts(&scan, &project.key);
    let mut writes = Vec::new();
    let bodies = crate::par::map_many(paths.iter().collect(), |rel| {
        let body = std::fs::read_to_string(root.join(rel)).ok()?;
        crate::cache::preload(rel, &body);
        Some(body)
    });
    for (rel, body) in paths.iter().zip(bodies) {
        let Some(body) = body else {
            continue;
        };
        let note = paths_of.is_note(rel);
        let drafted = match implemented.get(rel).filter(|_| note && scope.contains(rel)) {
            Some(lines) => implement_drafts(&body, lines, &mut actions),
            None => body.clone(),
        };
        let (mut next, file_actions) = rewrite_file(
            rel,
            note,
            &drafted,
            &name_to_id,
            &id_to_path,
            &mut letters,
            &around,
        )?;
        if let (Some((re, current)), Some(one)) = (&aliases, &one_line) {
            // ยง b73qzqyt9.b@dpevj
            let minted: BTreeSet<&String> = name_to_id.values().collect();
            let mut lines = Vec::new();
            for (idx, line) in next.split('\n').enumerate() {
                let re = match crate::marker::opens_one(line) {
                    true => one,
                    false => re,
                };
                let head = HEAD_RE
                    .captures(line)
                    .and_then(|c| c.get(1).or(c.get(3)))
                    .map(|m| m.as_str().to_string())
                    .filter(|id| !minted.contains(id));
                if let (Some(id), Some(caps)) = (&head, re.captures(line)) {
                    warnings.push(format!(
                        "ALIAS {}:{}: the carrying sentence of ยง {id} cites {}, an alias of ยง {}. Rewriting it would remint ยง {id}: edit the cite, then run `silcrow accept {id}`.",
                        rel.display(),
                        idx + 1,
                        &caps[2],
                        current[&caps[2]]
                    ));
                    lines.push(line.to_string());
                    continue;
                }
                let rewritten = re.replace_all(line, |caps: &regex::Captures| {
                    let id = &current[&caps[2]];
                    actions.push(format!("CURRENT {} -> {id} in {}", &caps[2], rel.display()));
                    format!("{}{id}", &caps[1])
                });
                lines.push(rewritten.into_owned());
            }
            next = lines.join("\n");
        }
        actions.extend(file_actions);
        if next != body {
            writes.push((rel.clone(), next));
            warnings.push(format!("REWRITE {}", rel.display()));
        }
    }
    let lettered = |err: &parse::FormError| {
        parse::names_provisional_letter(&err.message)
            && writes
                .iter()
                .find(|(rel, _)| *rel == err.loc.path)
                .is_some_and(|(_, next)| {
                    next.split('\n').nth(err.loc.line - 1).is_some_and(|line| {
                        !PROVISIONAL_CLAUSE_RE.is_match(line) && !PROVISIONAL_ROW_RE.is_match(line)
                    })
                })
    };
    let form: Vec<String> = scan
        .form_errors
        .iter()
        .filter(|err| !lettered(err))
        .map(|err| {
            format!(
                "FORM {}:{}: {}",
                err.loc.path.display(),
                err.loc.line,
                err.message
            )
        })
        .collect();
    warnings.splice(0..0, form);

    Ok(ResolvePlan {
        writes: WritePlan { writes },
        actions,
        warnings,
    })
}

/// The draft state each law head or clause line of a note takes once a marker of the project
/// names its draft, by note and 1-based line, with its address: a named address drops its `?`,
/// and a draft law that drops its own keeps each clause no marker names a draft.
type DraftLines = BTreeMap<PathBuf, BTreeMap<usize, (bool, String)>>;

fn named_drafts(scan: &parse::Scan, own: &str) -> DraftLines {
    // ยง t4mm4dk9z@v4d9z
    let aliases: BTreeMap<&str, &str> = scan
        .laws
        .iter()
        .flat_map(|law| law.aliases.iter().map(|a| (a.as_str(), law.id.as_str())))
        .collect();
    let named: BTreeSet<(&str, Option<&str>)> = scan
        .pointers
        .iter()
        .filter(|p| p.kind == parse::PointerKind::Implements)
        .filter(|p| p.project.as_deref().is_none_or(|key| key == own))
        .filter_map(|p| match &p.target {
            parse::Target::Stable { id, letter } => Some((
                aliases.get(id.as_str()).copied().unwrap_or(id.as_str()),
                letter.as_deref(),
            )),
            parse::Target::Display { .. } => None,
        })
        .collect();
    let mut out = DraftLines::new();
    for law in scan.laws.iter().filter(|law| !law.struck) {
        let clauses: Vec<(&parse::Clause, &str, bool)> = law
            .clauses
            .iter()
            .filter(|c| !c.struck)
            .filter_map(|c| {
                let letter = c.letter.as_deref()?;
                Some((c, letter, named.contains(&(law.id.as_str(), Some(letter)))))
            })
            .collect();
        let lines = out.entry(law.loc.path.clone()).or_default();
        if law.draft {
            if !named.contains(&(law.id.as_str(), None)) && !clauses.iter().any(|c| c.2) {
                continue;
            }
            lines.insert(law.loc.line, (false, law.id.clone()));
        }
        // ยง t4mm4dk9z.a@6r2q5
        for (clause, letter, named) in clauses {
            if clause.draft && (named || law.draft) {
                lines.insert(clause.loc.line, (!named, format!("{}.{letter}", law.id)));
            }
        }
        // ยง end t4mm4dk9z.a
    }
    out
}

/// `body` with each line of `lines` written with or without its draft `?`, as it wants.
fn implement_drafts(
    body: &str,
    lines: &BTreeMap<usize, (bool, String)>,
    actions: &mut Vec<String>,
) -> String {
    // ยง t4mm4dk9z@7s3kr
    let mut out: Vec<String> = Vec::new();
    for (idx, line) in body.split('\n').enumerate() {
        let next = match (lines.get(&(idx + 1)), parse::undraft(line)) {
            (Some((false, address)), Some(plain)) => {
                actions.push(format!("IMPLEMENT {address}"));
                plain
            }
            (Some((true, address)), None) => {
                actions.push(format!("DRAFT {address}"));
                parse::redraft(line)
            }
            _ => line.to_string(),
        };
        out.push(next);
    }
    out.join("\n")
}

/// A minted id that an alias anchor keeps names the law that keeps it, and an id a removed law
/// carried, minted or written by hand, would bring that law back with another meaning.
fn refuse_taken_ids(
    ws: &Workspace,
    root: &Path,
    scan: &parse::Scan,
    name_to_id: &BTreeMap<String, String>,
) -> Result<()> {
    // ยง cmx8g7zp2.d@rjqe8
    let keepers: BTreeMap<&String, &parse::Law> = scan
        .laws
        .iter()
        .flat_map(|law| law.aliases.iter().map(move |alias| (alias, law)))
        .collect();
    let taken: Vec<String> = name_to_id
        .iter()
        .filter_map(|(name, id)| {
            let keeper = keepers.get(id)?;
            Some(format!(
                "ยง +{name} mints {id}, an alias anchor of ยง {} at {}:{}",
                keeper.id,
                keeper.loc.path.display(),
                keeper.loc.line
            ))
        })
        .collect();
    if !taken.is_empty() {
        bail!(
            "{}: an alias anchor is a taken id, and a marker or a cite of it resolves to the law that keeps it. Reword the carrying sentence.",
            taken.join(", ")
        );
    }
    // ยง end cmx8g7zp2.d
    let minted: BTreeSet<String> = name_to_id.values().cloned().collect();
    // ยง cmx8g7zp2.b@ccg05
    let declared: BTreeSet<String> = scan
        .laws
        .iter()
        .map(|law| law.id.clone())
        .filter(|id| !hash::is_provisional_id(id))
        .collect();
    let frozen = ws.frozen(root, &minted.union(&declared).cloned().collect())?;
    if !frozen.is_empty() {
        let mut named: Vec<String> = name_to_id
            .iter()
            .filter(|(_, id)| frozen.contains(*id))
            .map(|(name, id)| format!("ยง +{name} mints {id}"))
            .collect();
        named.extend(
            scan.laws
                .iter()
                .filter(|law| frozen.contains(&law.id))
                .map(|law| {
                    format!(
                        "{}:{}: ยง {} is declared",
                        law.loc.path.display(),
                        law.loc.line,
                        law.id
                    )
                }),
        );
        bail!(
            "{}: a removed law carried that id in the published history, and an id never comes back with another meaning. Reword the carrying sentence.",
            named.join(", ")
        );
    }
    Ok(())
}

fn rewrite_file(
    rel: &Path,
    anchor: bool,
    body: &str,
    name_to_id: &BTreeMap<String, String>,
    id_to_path: &BTreeMap<String, PathBuf>,
    letters: &mut BTreeMap<String, BTreeSet<String>>,
    around: &Around<'_>,
) -> Result<(String, Vec<String>)> {
    let mut actions = Vec::new();
    let body = if anchor {
        body.to_string()
    } else {
        crate::cache::memo(rel, body, &"canonical pointers", || {
            parse::canonical_pointers(crate::marker::is_markdown(rel), body)
        })
    };
    let (mut next, qualifier_actions) = repair_qualifiers(rel, &body, around)?;
    actions.extend(qualifier_actions);
    let mut cites = Vec::new();
    for (name, id) in name_to_id {
        // ยง fxas3vhge.b@gfntd
        // A cite's link text takes the bare id, never the anchored head that `ยง +name` takes
        // in a note, and its anchor names the id whether it was written `#+name` or `#name`.
        let cite = Regex::new(&format!(
            r"\[(ยง\s*)?\+{name}((?:\.[a-z]+)?)\]\(([^)#]*)#\+?{name}\)",
            name = regex::escape(name)
        ))?;
        cites.push((cite, format!("[${{1}}{id}${{2}}](${{3}}#{id})")));
    }
    let named = name_to_id
        .keys()
        .any(|name| next.contains(&format!("+{name}")));
    if named {
        next = outside_literals(rel, &next, |mut code: String| {
            for (cite, to) in &cites {
                code = cite.replace_all(&code, to.as_str()).into_owned();
            }
            for (name, id) in name_to_id {
                for (from, to) in replacement_pairs(name, id, anchor) {
                    if code.contains(&from) {
                        code = replace_name(&code, &from, &to);
                    }
                }
            }
            // ยง fxas3vhge.c@et68x
            code.split_inclusive('\n')
                .map(|line| match crate::marker::opens_one(line.trim_end()) {
                    true => name_to_id
                        .iter()
                        .fold(line.to_string(), |line, (name, id)| {
                            replace_name(&line, &format!("+{name}"), id)
                        }),
                    false => line.to_string(),
                })
                .collect()
            // ยง end fxas3vhge.c
        });
    }
    if anchor {
        let (assigned, letter_actions) =
            assign_provisional_letters(rel, &next, name_to_id, letters)?;
        next = assigned;
        actions.extend(letter_actions);
    }
    let rewritten = rewrite_cite_paths(&next, rel, id_to_path);
    if rewritten != next {
        next = rewritten;
    }
    next = rewrite_qualified_cite_paths(&next, rel, around);
    if anchor {
        let minted: BTreeSet<&String> = name_to_id.values().collect();
        next = link_bare_ids(&next, rel, id_to_path, &minted);
    }
    if anchor {
        // ยง dvd9ggj68@zr32s
        let formed = parse::rewrite_parse_form(&next);
        if formed != next {
            next = formed;
        }
    }
    Ok((next, actions))
}

/// A qualifier that names the current project is stripped. One that names no project is
/// rewritten to the one project that declares the id, which is the repair after a project moved.
/// An adoption keeps its qualifier: stripped, it would read as a declaration. An unqualified id
/// the current project does not declare is qualified with the one other project that does.
fn repair_qualifiers(rel: &Path, body: &str, around: &Around<'_>) -> Result<(String, Vec<String>)> {
    // ยง x2btw6k6f.b@5gq02
    let mut actions = Vec::new();
    let mut out = Vec::new();
    let markdown = crate::marker::is_markdown(rel);
    let fenced = crate::cache::memo(rel, body, &"fenced lines", || {
        crate::marker::fenced_lines(markdown, body)
    });
    for (idx, line) in body.split('\n').enumerate() {
        // A fence and an inline code span quote a reference, they do not make one.
        if fenced.get(idx).copied().unwrap_or(false) {
            out.push(line.to_string());
            continue;
        }
        let adoption = ADOPT_LINE_RE.is_match(line);
        let mut failure = None;
        let (qref, uref): (&Regex, &Regex) = match crate::marker::opens_one(line) {
            true => (&QREF_ONE_RE, &UREF_ONE_RE),
            false => (&QREF_RE, &UREF_RE),
        };
        let next = replace_outside_code(markdown, line, qref, |caps: &regex::Captures| {
            let (lead, project, id) = (&caps[1], &caps[2], &caps[3]);
            // ยง x2btw6k6f.a@q4vty
            if project == around.own {
                if !adoption && around.own_ids.contains(id) {
                    actions.push(format!("STRIP {project}:{id} in {}", rel.display()));
                    return format!("{lead}{id}");
                }
                return caps[0].to_string();
            }
            // ยง end x2btw6k6f.a
            if around.others.contains_key(project) {
                return caps[0].to_string();
            }
            match around.declaring(id)[..] {
                [] => caps[0].to_string(),
                [found] if found == around.own && adoption => caps[0].to_string(),
                [found] if found == around.own => {
                    actions.push(format!("STRIP {project}:{id} in {}", rel.display()));
                    format!("{lead}{id}")
                }
                [found] => {
                    actions.push(format!(
                        "RELOCATE {project}:{id} -> {found}:{id} in {}",
                        rel.display()
                    ));
                    format!("{lead}{found}:{id}")
                }
                ref several => {
                    failure = Some(format!(
                        "{}:{}: `{project}:{id}` names no project, and the id is declared in several: {}. Write the project path by hand.",
                        rel.display(),
                        idx + 1,
                        several
                            .iter()
                            .map(|k| format!("`{k}`"))
                            .collect::<Vec<_>>()
                            .join(", ")
                    ));
                    caps[0].to_string()
                }
            }
        });
        if let Some(message) = failure {
            bail!(message);
        }
        let next = replace_outside_code(markdown, &next, uref, |caps: &regex::Captures| {
            let (lead, id) = (&caps[1], &caps[2]);
            if !caps[3].is_empty() || around.own_ids.contains(id) {
                return caps[0].to_string();
            }
            match around.declaring(id)[..] {
                [found] => {
                    actions.push(format!("QUALIFY {id} -> {found}:{id} in {}", rel.display()));
                    format!("{lead}{found}:{id}")
                }
                _ => caps[0].to_string(),
            }
        });
        out.push(next);
    }
    Ok((out.join("\n"), actions))
}

/// `line` with each match of `re` written by `with`, except a match inside an inline code
/// span of a markdown line.
fn replace_outside_code(
    markdown: bool,
    line: &str,
    re: &Regex,
    mut with: impl FnMut(&regex::Captures) -> String,
) -> String {
    let masked = if markdown {
        parse::mask_inline_code(line)
    } else {
        line.to_string()
    };
    let mut out = String::with_capacity(line.len());
    let mut last = 0;
    for caps in re.captures_iter(&masked) {
        let m = caps.get(0).expect("whole match");
        out.push_str(&line[last..m.start()]);
        out.push_str(&with(&caps));
        last = m.end();
    }
    out.push_str(&line[last..]);
    out
}

/// The path of a qualified cite follows the note of its project, as an unqualified one does.
fn rewrite_qualified_cite_paths(body: &str, source_rel: &Path, around: &Around<'_>) -> String {
    // ยง eh0rt4jyr@zm9r7
    let source = workspace::in_workspace(around.own, source_rel);
    CITE_LINK_RE
        .replace_all(body, |caps: &regex::Captures| {
            let Some(q) = QCITE_RE.captures(caps[1].trim()) else {
                return caps[0].to_string();
            };
            let (project, id) = (&q[1], &q[2]);
            if id != &caps[4] {
                return caps[0].to_string();
            }
            let Some(target) = around.others.get(project).and_then(|ids| ids.get(id)) else {
                return caps[0].to_string();
            };
            let current = relative_link_path(&source, &workspace::in_workspace(project, target));
            if caps[2].trim() == current {
                return caps[0].to_string();
            }
            let anchor = caps.get(3).map(|m| m.as_str()).unwrap_or("");
            format!("[{}]({current}{anchor})", &caps[1])
        })
        .into_owned()
}

fn decision_paths_for_scope(root: &Path, staged_only: Option<&[PathBuf]>) -> Result<Vec<PathBuf>> {
    match staged_only {
        None => walk::decision_files(root),
        Some(staged) => {
            let project = walk::Project::at(root)?;
            Ok(staged
                .iter()
                .filter(|rel| project.is_note(rel) && root.join(rel).is_file())
                .map(|rel| root.join(rel))
                .collect())
        }
    }
}

fn print_fallback_logs(root: &Path) -> Result<()> {
    // ยง k6rfj5k37.e@5qd2h
    for notice in crate::span::fallback_notices(root)? {
        crate::say!("  WRN {notice}");
    }
    Ok(())
}

pub fn resolve_staged(
    ws: &Workspace,
    project: &ProjectRef,
    staged: &[PathBuf],
    dry_run: bool,
) -> Result<Option<Vec<PathBuf>>> {
    let root = project.dir.as_path();
    print_fallback_logs(root)?;
    let plan = plan_scoped(ws, project, Some(staged))?;
    apply_planned(ws, project, staged, dry_run, plan)
}

/// What `plan_scoped` plans for the staged change of each of `projects`, when no plan writes a
/// decision note: then no project rewrites what another reads, and each may run beside the
/// others. None when one does, or when one cannot be planned.
pub fn independent_plans(
    ws: &Workspace,
    projects: &[(&ProjectRef, Option<Vec<PathBuf>>)],
) -> Option<Vec<ResolvePlan>> {
    let plans = crate::par::map(
        projects.iter().collect(),
        |_| 1,
        |(project, staged)| {
            let plan = plan_scoped(ws, project, staged.as_deref()).ok()?;
            let notes = walk::Project::at(&project.dir).ok()?;
            let own = plan
                .writes
                .writes
                .iter()
                .all(|(rel, _)| !notes.is_note(rel));
            own.then_some(plan)
        },
    );
    plans.into_iter().collect()
}

/// `resolve_staged` with its plan already made.
pub fn resolve_planned(
    ws: &Workspace,
    project: &ProjectRef,
    staged: &[PathBuf],
    dry_run: bool,
    plan: ResolvePlan,
) -> Result<Option<Vec<PathBuf>>> {
    print_fallback_logs(&project.dir)?;
    apply_planned(ws, project, staged, dry_run, plan)
}

fn apply_planned(
    ws: &Workspace,
    project: &ProjectRef,
    staged: &[PathBuf],
    dry_run: bool,
    plan: ResolvePlan,
) -> Result<Option<Vec<PathBuf>>> {
    let root = project.dir.as_path();
    for action in &plan.actions {
        crate::say!("  {action}");
    }
    for warn in &plan.warnings {
        crate::say!("  {warn}");
    }
    write::apply(&plan.writes, root, dry_run)?;
    let texts = project_pin_texts(ws, project)?;
    let pins = crate::span::pin_bare(root, &texts, Some(staged))?;
    let (pins, drifted) = leave_drifted_bare(root, pins)?;
    write::apply(&pins, root, dry_run)?;
    fail_on_drifted_bare(drifted)?;
    let rewritten: Vec<PathBuf> = plan
        .writes
        .writes
        .iter()
        .chain(&pins.writes)
        .map(|(rel, _)| rel.clone())
        .collect();
    if dry_run || rewritten.is_empty() {
        Ok(None)
    } else {
        Ok(Some(rewritten))
    }
}

/// `pins` with each bare marker that drifted since `HEAD` left bare, named for `accept`, since
/// a deleted digest is no approval, and how many there are.
fn leave_drifted_bare(root: &Path, pins: write::WritePlan) -> Result<(write::WritePlan, usize)> {
    // ยง jed5hb8sa.b@2eeth
    let drifted = crate::span::drifted_bare(root, &pins)?;
    if drifted.is_empty() {
        return Ok((pins, 0));
    }
    for d in &drifted {
        crate::say!(
            "  ERR {}:{}: ยง {} carried {} at HEAD, and its span hashes to @{} now: it drifted, and `fix` pins no drift. Read it against its law or clause, then run `silcrow accept {}`.",
            d.rel.display(),
            d.line,
            d.addr.display(),
            d.held_digests(),
            d.now,
            d.addr.display()
        );
    }
    Ok((
        crate::span::leave_bare(root, pins, &drifted)?,
        drifted.len(),
    ))
}

fn fail_on_drifted_bare(drifted: usize) -> Result<()> {
    if drifted > 0 {
        bail!("{drifted} bare marker(s) drifted since HEAD and stay bare: run `silcrow accept` on each address above");
    }
    Ok(())
}

/// The texts a project's pins hash, its own and those of every other project.
pub fn project_pin_texts(ws: &Workspace, project: &ProjectRef) -> Result<crate::span::PinTexts> {
    let scan = parse::scan_root(&project.dir)?;
    Ok(crate::span::PinTexts::for_project(
        &scan,
        &ws.law_scans(&project.key)?,
    ))
}

pub fn run(ws: &Workspace, project: &ProjectRef, dry_run: bool, scheme_remint: bool) -> Result<()> {
    // ยง jed5hb8sa@ax57e
    let root = project.dir.as_path();
    print_fallback_logs(root)?;
    // ยง jed5hb8sa.a@tx0a6
    // The pins in the tree were written under the scheme HEAD's history last recorded, which
    // a branch commit records before the published base ever does.
    if scheme_remint {
        // With no `Silcrow-Scheme` in the history the scheme of the pins is unknown, and a pin
        // whose inputs held since the commit that wrote its digest proves another scheme wrote it.
        let recorded = crate::hook::recorded_scheme_at(&ws.root, "HEAD")?;
        let has_history = crate::check::has_history(&ws.root);
        if let Some(recorded) = recorded.filter(|&n| n != crate::scheme::BINARY_VERSION) {
            return run_remint_digests(ws, project, dry_run, Some(recorded));
        }
        if recorded.is_none() && has_history && plan(ws, project, true)?.writes.writes.is_empty() {
            return run_remint_digests(ws, project, dry_run, None);
        }
    }
    // ยง end jed5hb8sa.a
    let plan = plan(ws, project, scheme_remint)?;
    run_plan(ws, project, dry_run, scheme_remint, plan)
}

/// `run` with no scheme remint and its plan already made.
pub fn run_planned(
    ws: &Workspace,
    project: &ProjectRef,
    dry_run: bool,
    plan: ResolvePlan,
) -> Result<()> {
    print_fallback_logs(&project.dir)?;
    run_plan(ws, project, dry_run, false, plan)
}

fn run_plan(
    ws: &Workspace,
    project: &ProjectRef,
    dry_run: bool,
    scheme_remint: bool,
    plan: ResolvePlan,
) -> Result<()> {
    let root = project.dir.as_path();
    for action in &plan.actions {
        crate::say!("  {action}");
    }
    for warn in &plan.warnings {
        crate::say!("  {warn}");
    }
    // A pin hashes the id it names: the pins of a reminted law that held before the remint
    // re-pin with it, since nothing they bind but the id moved.
    // ยง xnsbksxv6.e@cws0r
    let reminted: BTreeSet<String> = if scheme_remint && !plan.writes.writes.is_empty() {
        parse::scan_root(root)?
            .laws
            .iter()
            .filter(|law| !hash::is_provisional_id(&law.id) && hash::mint_id(&law.name) != law.id)
            .map(|law| law.id.clone())
            .collect()
    } else {
        BTreeSet::new()
    };
    let held = if reminted.is_empty() {
        BTreeSet::new()
    } else {
        let scan = parse::scan_root(root)?;
        let old = crate::accept::head_sentences(
            root,
            scan.laws.iter().filter(|law| reminted.contains(&law.id)),
        )?;
        crate::accept::sentence_held(ws, project, project, &old, &|p| {
            p.project.is_none() && reminted.contains(&p.id)
        })?
    };
    write::apply(&plan.writes, root, dry_run)?;
    if !dry_run && !held.is_empty() {
        let repins = crate::span::repin_at(root, project_pin_texts(ws, project)?, &held, &|p| {
            p.project.is_none()
        })?;
        for (rel, _) in &repins.writes {
            crate::say!("  REPIN {}: the id it names was reminted", rel.display());
        }
        write::apply(&repins, root, dry_run)?;
    }
    // ยง end xnsbksxv6.e
    let texts = project_pin_texts(ws, project)?;
    let pins = crate::span::pin_bare(root, &texts, None)?;
    let (pins, drifted) = leave_drifted_bare(root, pins)?;
    for (rel, _) in &pins.writes {
        crate::say!("  PIN {}", rel.display());
    }
    write::apply(&pins, root, dry_run)?;
    fail_on_drifted_bare(drifted)?;
    // ยง d1bc2zca5.c@mynem
    let unhashable = crate::span::unhashable(root, &|_| true)?;
    if !unhashable.is_empty() {
        for err in &unhashable {
            crate::say!("  {err}");
        }
        bail!(
            "{} pin(s) cannot be hashed: write the code each line above names so the grammar parses it, then run `silcrow fix` again",
            unhashable.len()
        );
    }
    // ยง end d1bc2zca5.c
    // ยง rr512n5e2.e@bpj5e
    let spanless = crate::span::spanless(root)?;
    if !spanless.is_empty() {
        for err in &spanless {
            crate::say!("  {err}");
        }
        bail!(
            "{} marker(s) pin nothing: move each above the construct it carries, then run `silcrow fix` again",
            spanless.len()
        );
    }
    // ยง end rr512n5e2.e
    let wrote = !(plan.writes.writes.is_empty() && pins.writes.is_empty());
    if !wrote {
        crate::say!("\nโœ“ Nothing to fix.");
    } else if dry_run {
        crate::say!("\nRun with --write to apply. Pins are planned on the tree as it is now.");
    } else {
        crate::say!("\nโœ“ Fixed. Run `silcrow check`.");
    }
    Ok(())
}

fn run_remint_digests(
    ws: &Workspace,
    project: &ProjectRef,
    dry_run: bool,
    recorded: Option<u32>,
) -> Result<()> {
    // ยง jed5hb8sa.a@5xk0x
    let root = project.dir.as_path();
    let scan = parse::scan_root(root)?;
    let scans = ws.law_scans(&project.key)?;
    let now =
        crate::span::TreeTokens::new(root, crate::span::PinTexts::for_project(&scan, &scans))?;
    // No reader of the recorded scheme is kept, and `HEAD` may not have passed `check` under
    // it: a commit with `--no-verify`, a cherry-pick or `git am` runs no hook. A pin's digest
    // held at `HEAD` when no file it reads changed after the commit that wrote that digest, and
    // a pin whose inputs are unchanged since `HEAD` then changed scheme and nothing else.
    crate::published::require_history(&ws.root)?;
    let head = tempfile::tempdir()?;
    crate::published::write_tree(&ws.root, "HEAD", head.path())?;
    let head_ws = Workspace::at(head.path().to_path_buf())?;
    let head_root = head.path().join(root.strip_prefix(&ws.root)?);
    let mut head_scans = scans;
    for (key, scan) in head_ws.law_scans(&project.key)?.scans {
        head_scans.scans.insert(key, scan);
    }
    let head_scan = parse::scan_root(&head_root)?;
    let at_head = crate::span::TreeTokens::new(
        &head_root,
        crate::span::PinTexts::for_project(&head_scan, &head_scans),
    )?;
    let note_of = |addr: &str| -> Option<PathBuf> {
        let (key, local) = match addr.split_once(':') {
            Some((key, local)) => (key, local),
            None => (project.key.as_str(), addr),
        };
        let id = local.split('.').next()?;
        let scan = match key == project.key {
            true => &head_scan,
            false => head_scans.scans.get(key)?,
        };
        let law = scan
            .laws
            .iter()
            .find(|law| law.id == id || law.aliases.iter().any(|a| a == id))?;
        Some(crate::workspace::in_workspace(key, &law.loc.path))
    };
    let held_since = |rel: &Path, addr: &str, written: &str, followed: &BTreeSet<PathBuf>| {
        let Some(note) = note_of(addr) else {
            return Ok(false);
        };
        let mut reads: Vec<PathBuf> = std::iter::once(rel)
            .chain(followed.iter().map(PathBuf::as_path))
            .map(|path| crate::workspace::in_workspace(&project.key, path))
            .collect();
        reads.push(note);
        crate::published::written_last(&ws.root, &reads, &format!("{addr}@{written}"))
    };
    let (plan, drifted) =
        crate::span::remint_digests(root, &head_root, &at_head, &now, &held_since)?;
    let scheme = match recorded {
        Some(recorded) => format!("scheme {recorded}"),
        None => "another scheme".to_string(),
    };
    for pin in &drifted {
        crate::say!(
            "  DRIFT {pin}: its span, a callee or its clause changed since HEAD, or a file it reads changed after the commit that wrote its digest, so nothing shows that {scheme} pinned it as it stands. It keeps its digest: read it, then run `silcrow accept <address>`."
        );
    }
    if plan.writes.is_empty() {
        crate::say!("\nโœ“ No pinned span digests to remint.");
        return Ok(());
    }
    for (rel, _) in &plan.writes {
        crate::say!("  REMINT-DIGEST {}", rel.display());
    }
    write::apply(&plan, root, dry_run)?;
    if dry_run {
        crate::say!("\nRun with --write to apply.");
    } else {
        crate::say!("\nโœ“ Span digest remint complete.");
    }
    Ok(())
}

/// `text` with every pointer to an alias anchor naming the id its law carries now.
fn current_ids(text: &str, aliases: &Option<(Regex, BTreeMap<String, String>)>) -> String {
    let Some((re, current)) = aliases else {
        return text.to_string();
    };
    re.replace_all(text, |caps: &regex::Captures| {
        format!("{}{}", &caps[1], current[&caps[2]])
    })
    .into_owned()
}

/// Every pointer form that names an alias anchor, the id cut out as group 2, and each alias
/// to the id its law carries now. `None` when no head keeps an alias.
fn alias_pointer_re(scan: &parse::Scan) -> Result<Option<(Regex, BTreeMap<String, String>)>> {
    let current: BTreeMap<String, String> = scan
        .laws
        .iter()
        .filter(|law| !hash::is_provisional_id(&law.id))
        .flat_map(|law| law.aliases.iter().map(|a| (a.clone(), law.id.clone())))
        .collect();
    if current.is_empty() {
        return Ok(None);
    }
    let ids: Vec<String> = current.keys().map(|a| regex::escape(a)).collect();
    let re = Regex::new(&format!(
        r"(\[ยง\s*|\[|ยง\s*(?:end\s+)?|\]\([^)#\s]*#)({})\b",
        ids.join("|")
    ))?;
    Ok(Some((re, current)))
}

fn anchored_marker(id: &str) -> String {
    format!("ยง <a id=\"{id}\">{id}</a>")
}

fn replacement_pairs(name: &str, id: &str, anchor: bool) -> Vec<(String, String)> {
    // ยง fxas3vhge.b@kgxtc
    let (declare, declare_tight) = if anchor {
        (anchored_marker(id), format!("ยง<a id=\"{id}\">{id}</a>"))
    } else {
        (format!("ยง {id}"), format!("ยง{id}"))
    };
    vec![
        (format!("ยง? +{name}"), declare.replacen('ยง', "ยง?", 1)),
        (format!("ยง!? +{name}"), declare.replacen('ยง', "ยง!?", 1)),
        (format!("ยง?! +{name}"), declare.replacen('ยง', "ยง!?", 1)),
        (format!("ยง! +{name}"), declare.replacen('ยง', "ยง!", 1)),
        (format!("ยง +{name}"), declare),
        (format!("ยง+{name}"), declare_tight),
        (format!("// ยง +{name}"), format!("// ยง {id}")),
        (format!("<!-- ยง +{name}"), format!("<!-- ยง {id}")),
        (format!("ยง end +{name}"), format!("ยง end {id}")),
        (format!("#+{name}"), format!("#{id}")),
        (format!("[+{name}"), format!("[{id}")),
    ]
}

/// `text` with `rewrite` applied to each stretch outside a string, a heredoc or a template, so
/// a `ยง +name` the program holds as a value is no pointer and stays as written.
fn outside_literals(rel: &Path, text: &str, rewrite: impl Fn(String) -> String) -> String {
    // ยง fxas3vhge.d@e9e97
    let mut out = String::with_capacity(text.len());
    let mut at = 0;
    for (start, end) in crate::span::literal_ranges(rel, text) {
        if start < at {
            continue;
        }
        out.push_str(&rewrite(text[at..start].to_string()));
        out.push_str(&text[start..end]);
        at = end;
    }
    out.push_str(&rewrite(text[at..].to_string()));
    out
}

/// Replaces `from` only where the provisional name it ends with stops, so `+p1` is never
/// rewritten inside `+p10` or `+cache` inside `+cache-ttl`.
fn replace_name(text: &str, from: &str, to: &str) -> String {
    let is_name = |c: char| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-';
    let bounded = from.ends_with(is_name);
    let mut out = String::with_capacity(text.len());
    let mut at = 0;
    for (start, _) in text.match_indices(from) {
        let end = start + from.len();
        if bounded && text[end..].starts_with(is_name) {
            continue;
        }
        out.push_str(&text[at..start]);
        out.push_str(to);
        at = end;
    }
    out.push_str(&text[at..]);
    out
}

fn build_id_to_path(
    scan: &parse::Scan,
    name_to_id: &BTreeMap<String, String>,
) -> BTreeMap<String, PathBuf> {
    let mut map = BTreeMap::new();
    for law in &scan.laws {
        let id = resolve_law_id(&law.id, name_to_id);
        if hash::is_provisional_id(&id) {
            continue;
        }
        map.insert(id, law.loc.path.clone());
    }
    map
}

fn letters_per_law(
    scan: &parse::Scan,
    name_to_id: &BTreeMap<String, String>,
) -> BTreeMap<String, BTreeSet<String>> {
    // ยง s6aqqwvmc.b@zmqgn
    let mut map = BTreeMap::new();
    for law in &scan.laws {
        let id = resolve_law_id(&law.id, name_to_id);
        let entry = map.entry(id).or_insert_with(BTreeSet::new);
        for al in &law.clauses {
            if let Some(letter) = &al.letter {
                entry.insert(letter.clone());
            }
        }
    }
    map
}

fn has_provisional_clause(root: &Path) -> Result<bool> {
    for path in walk::decision_files(root)? {
        let text = std::fs::read_to_string(&path)?;
        let lines: Vec<&str> = text.lines().collect();
        let fence = parse::fence_mask(&lines);
        if lines.iter().zip(fence).any(|(line, fenced)| {
            !fenced && (PROVISIONAL_CLAUSE_RE.is_match(line) || PROVISIONAL_ROW_RE.is_match(line))
        }) {
            return Ok(true);
        }
    }
    Ok(false)
}

/// Every letter the first-parent history of the default branch held for a law is burned
/// there, struck or since deleted, tombstone included, so a stale marker of it on another branch
/// would name a new obligation. The fork point counts too. With no commit yet nothing is
/// published.
fn burn_published_letters(
    ws: &Workspace,
    root: &Path,
    scan: &parse::Scan,
    letters: &mut BTreeMap<String, BTreeSet<String>>,
) -> Result<()> {
    // ยง s6aqqwvmc.b@dxab1
    let held = ws.base_ref("HEAD").and_then(|base| match base {
        Some(base) => Ok(Some((
            crate::published::at(root, &base)?,
            ws.held_letters(root)?,
        ))),
        None => Ok(None),
    });
    let held = held.context(
        "`fix` gives a `(+)` clause a letter the published history never held for its law, so it reads that history",
    )?;
    let Some((published, history)) = held else {
        return Ok(());
    };
    for law in &scan.laws {
        let used = letters.entry(law.id.clone()).or_default();
        if let Some(burned) = published.letters_of(law) {
            used.extend(burned);
        }
        for id in std::iter::once(&law.id).chain(&law.aliases) {
            used.extend(history.get(id).into_iter().flatten().cloned());
        }
    }
    Ok(())
}

fn resolve_law_id(token: &str, name_to_id: &BTreeMap<String, String>) -> String {
    if let Some(name) = token.strip_prefix('+') {
        name_to_id
            .get(name)
            .cloned()
            .unwrap_or_else(|| format!("+{name}"))
    } else {
        token.to_string()
    }
}

/// The single letter after the last one the law writes or burned, so a `(+)` written last
/// lands in letter order and a letter left free by a deleted clause is never given again. A
/// compound letter is a child of its prefix, so `(aa)` after `(z)` would read as nested under
/// `(a)`: past `(z)` there is none.
pub fn next_free_letter(used: &BTreeSet<String>) -> Option<String> {
    let last = used.iter().filter_map(|l| l.bytes().next()).max();
    let first = last.map_or(b'a', |b| b + 1);
    (first..=b'z').next().map(|b| (b as char).to_string())
}

fn assign_provisional_letters(
    rel: &Path,
    body: &str,
    name_to_id: &BTreeMap<String, String>,
    letters: &mut BTreeMap<String, BTreeSet<String>>,
) -> Result<(String, Vec<String>)> {
    let mut actions = Vec::new();
    let mut current_law: Option<String> = None;
    let ended_nl = body.ends_with('\n');
    let mut out: Vec<String> = Vec::new();
    let lines: Vec<&str> = body.lines().collect();
    let fence = parse::fence_mask(&lines);
    // Whether the lines read so far still attach to the head of the law, as the parser reads
    // them, so a table opening here letters its rows, and whether the table being read does.
    let mut head_owned = false;
    let mut rows_letter: Option<bool> = None;
    let mut prev_blank = false;
    for (idx, line) in lines.into_iter().enumerate() {
        if fence[idx] {
            out.push(line.to_string());
            continue;
        }
        if SECTION_BREAK_RE.is_match(line) {
            current_law = None;
            out.push(line.to_string());
            continue;
        }
        if let Some(caps) = HEAD_RE.captures(line) {
            let token = caps
                .get(1)
                .or(caps.get(2))
                .or(caps.get(3))
                .unwrap()
                .as_str();
            current_law = Some(resolve_law_id(token, name_to_id));
            (head_owned, rows_letter, prev_blank) = (true, None, false);
            out.push(line.to_string());
            continue;
        }
        let row = line.trim_start().starts_with('|');
        if !row {
            rows_letter = None;
        }
        let item = PROVISIONAL_CLAUSE_RE.is_match(line) || LETTERED_ITEM_RE.is_match(line);
        let letters_rows = row && *rows_letter.get_or_insert(head_owned);
        if line.trim().is_empty() {
            prev_blank = true;
        } else {
            let indent = line.len() - line.trim_start().len();
            let lettering = item || (letters_rows && LETTERED_ROW_RE.is_match(line));
            if lettering || line.starts_with('#') || (prev_blank && !row && indent < 2) {
                head_owned = false;
            }
            prev_blank = false;
        }
        let provisional = if letters_rows {
            PROVISIONAL_ROW_RE.captures(line)
        } else if row {
            None
        } else {
            PROVISIONAL_CLAUSE_RE.captures(line)
        };
        if let Some(target) = &current_law {
            if let Some(caps) = provisional {
                // ยง s6aqqwvmc.b@0exgh
                let used = letters.entry(target.clone()).or_default();
                let Some(letter) = next_free_letter(used) else {
                    bail!(
                        "{}:{}: ยง {target} has no single letter left for a `(+)` clause: it writes or burned (z), and a `(+)` takes the letter after the last. Declare a successor law, or write the clause as a compound under the letter it narrows.",
                        rel.display(),
                        idx + 1
                    );
                };
                used.insert(letter.clone());
                actions.push(format!("LETTER {target}.{letter}"));
                let prefix = caps.get(1).map(|m| m.as_str()).unwrap_or("");
                // A row carries no draft mark, so its groups stop at the space.
                let (draft, space) = match caps.len() {
                    4 => (&caps[2], caps.get(3).map(|m| m.as_str()).unwrap_or(" ")),
                    _ => ("", caps.get(2).map(|m| m.as_str()).unwrap_or(" ")),
                };
                let rest = line[caps.get(0).unwrap().end()..].trim_start();
                out.push(format!("{prefix}({letter}){draft}{space}{rest}"));
                continue;
            }
        }
        out.push(line.to_string());
    }
    let mut text = out.join("\n");
    if ended_nl {
        text.push('\n');
    }
    Ok((text, actions))
}

fn rewrite_cite_paths(
    body: &str,
    source_rel: &Path,
    id_to_path: &BTreeMap<String, PathBuf>,
) -> String {
    CITE_LINK_RE
        .replace_all(body, |caps: &regex::Captures| {
            let text = &caps[1];
            let link_path = caps[2].trim();
            let anchor = caps.get(3).map(|m| m.as_str()).unwrap_or("");
            let id = &caps[4];
            if QCITE_RE.is_match(text.trim()) {
                return caps[0].to_string();
            }
            let Some(target) = id_to_path.get(id) else {
                return caps[0].to_string();
            };
            let current = relative_link_path(source_rel, target);
            if link_path.is_empty() {
                if normalize_path(source_rel) == normalize_path(target) {
                    return caps[0].to_string();
                }
                return format!("[{text}]({current}{anchor})");
            }
            let resolved = resolve_link_path(source_rel, link_path);
            if normalize_path(&resolved) == normalize_path(target) && link_path == current {
                return caps[0].to_string();
            }
            format!("[{text}]({current}{anchor})")
        })
        .into_owned()
}

/// A bare id a reader cannot follow becomes a link to its law. Only ids the tree
/// declares are touched, so an ordinary nine-letter word is never rewritten. The carrying
/// sentence of a law minted before this run, not in `minted`, is left as written: the link
/// would remint it.
fn link_bare_ids(
    body: &str,
    source_rel: &Path,
    id_to_path: &BTreeMap<String, PathBuf>,
    minted: &BTreeSet<&String>,
) -> String {
    // ยง nth5nbchz.d@p4ndn
    let ended_nl = body.ends_with('\n');
    let mut in_fence = false;
    let mut out = Vec::new();
    for line in body.lines() {
        if line.trim_start().starts_with("```") {
            in_fence = !in_fence;
        }
        let settled = HEAD_RE
            .captures(line)
            .and_then(|c| c.get(1).or(c.get(3)))
            .is_some_and(|id| !minted.contains(&id.as_str().to_string()));
        if in_fence || settled || line.trim_start().starts_with("```") {
            out.push(line.to_string());
            continue;
        }
        let masked: Vec<(usize, usize)> = NOT_BARE_RES
            .iter()
            .flat_map(|re| re.find_iter(line).map(|m| (m.start(), m.end())))
            .collect();
        let mut next = String::with_capacity(line.len());
        let mut last = 0;
        for caps in BARE_ID_RE.captures_iter(line) {
            let m = caps.get(0).unwrap();
            if masked.iter().any(|(a, b)| m.start() < *b && m.end() > *a) {
                continue;
            }
            let id = &caps[1];
            let Some(target) = id_to_path.get(id) else {
                continue;
            };
            let path = if normalize_path(source_rel) == normalize_path(target) {
                String::new()
            } else {
                relative_link_path(source_rel, target)
            };
            next.push_str(&line[last..m.start()]);
            next.push_str(&format!("[{id}{}]({path}#{id})", &caps[2]));
            last = m.end();
        }
        next.push_str(&line[last..]);
        out.push(next);
    }
    let mut text = out.join("\n");
    if ended_nl {
        text.push('\n');
    }
    text
}

fn resolve_link_path(source_rel: &Path, link_path: &str) -> PathBuf {
    let base = source_rel.parent().unwrap_or_else(|| Path::new(""));
    normalize_path(&base.join(link_path))
}

fn normalize_path(path: &Path) -> PathBuf {
    let mut out = PathBuf::new();
    for comp in path.components() {
        match comp {
            Component::CurDir => {}
            Component::ParentDir => {
                out.pop();
            }
            Component::Normal(part) => out.push(part),
            Component::RootDir | Component::Prefix(_) => out.push(comp.as_os_str()),
        }
    }
    out
}

fn relative_link_path(from_file: &Path, to_file: &Path) -> String {
    let from_dir = from_file.parent().unwrap_or_else(|| Path::new(""));
    let from = from_dir.components().collect::<Vec<_>>();
    let to = to_file.components().collect::<Vec<_>>();
    let mut common = 0usize;
    while common < from.len() && common < to.len() && from[common] == to[common] {
        common += 1;
    }
    let mut rel = PathBuf::new();
    for _ in common..from.len() {
        rel.push("..");
    }
    for comp in to.iter().skip(common) {
        rel.push(comp.as_os_str());
    }
    rel.to_string_lossy().replace('\\', "/")
}

fn plan_scheme_remint(root: &Path, base: Option<&str>) -> Result<ResolvePlan> {
    // ยง d1bc2zca5.f@mpes3
    let scan = parse::scan_root(root)?;
    let published = match base {
        Some(base) => crate::published::at(root, base)?.keys(),
        None => BTreeSet::new(),
    };
    let mut actions = Vec::new();
    let warnings = Vec::new();
    let mut remap: BTreeMap<String, String> = BTreeMap::new();
    let mut owners: BTreeMap<String, String> = BTreeMap::new();

    for law in &scan.laws {
        if hash::is_provisional_id(&law.id) {
            continue;
        }
        let new_id = hash::mint_id(&law.name);
        if new_id == law.id {
            continue;
        }
        if let Some(loc) = owners.get(&new_id) {
            bail!(
                "scheme remint collision: {loc} and {}:{} both mint to {new_id}",
                law.loc.path.display(),
                law.loc.line
            );
        }
        owners.insert(
            new_id.clone(),
            format!("{}:{}", law.loc.path.display(), law.loc.line),
        );
        actions.push(format!("REMINT {} -> {new_id} ({})", law.id, law.name));
        remap.insert(law.id.clone(), new_id);
    }

    if remap.is_empty() {
        return Ok(ResolvePlan {
            writes: WritePlan { writes: Vec::new() },
            actions,
            warnings,
        });
    }

    let Remap { mut plan, kept } = plan_remap(root, remap.clone())?;
    let mut warnings = warnings;
    warnings.extend(
        plan.warnings
            .iter()
            .filter(|w| w.starts_with("CITE "))
            .cloned(),
    );
    for law in &scan.laws {
        let Some(new_id) = remap.get(&law.id) else {
            continue;
        };
        if !published.contains(&law.id) && !kept.contains(&law.id) {
            continue;
        }
        // ยง b73qzqyt9@f98wb
        let Some((_, text)) = plan
            .writes
            .writes
            .iter_mut()
            .find(|(rel, _)| *rel == law.loc.path)
        else {
            bail!(
                "{}: the remint of ยง {} rewrote no head",
                law.loc.path.display(),
                law.id
            );
        };
        *text = crate::accept::add_alias(text, law.loc.line, new_id, &law.id)?;
        actions.push(format!(
            "ALIAS {} keeps #{}",
            law.loc.path.display(),
            law.id
        ));
    }
    plan.actions = actions;
    plan.warnings = warnings;
    Ok(plan)
}

pub fn plan_remap(root: &Path, remap: BTreeMap<String, String>) -> Result<Remap> {
    // ยง xnsbksxv6.a@vyemz
    let mut actions: Vec<String> = remap
        .iter()
        .map(|(old, new)| format!("REMAP {old} -> {new}"))
        .collect();
    actions.sort();
    // An id qualified by a project path names that project's law, not this one.
    let mut remap = rewrite_project(root, &remap, &|text: &str, old: &str, new: &str| {
        replace_token(text, old, new, |c| c != ':')
    })?;
    remap.plan.actions = actions;
    Ok(remap)
}

/// A remap and the old ids it left in a carrying sentence of another law.
pub struct Remap {
    pub plan: ResolvePlan,
    /// Each reminted id a carrying sentence still cites: its law keeps it as an alias anchor
    /// so the cite resolves.
    pub kept: BTreeSet<String>,
}

type Rewrite<'a> = &'a dyn Fn(&str, &str, &str) -> String;

/// Every file of the project with each old id of `remap` written new by `rewrite`, except in
/// the carrying sentence of a law, whose words its id hashes: there only the head before the
/// sentence is rewritten, and each old id the sentence cites is named and kept.
fn rewrite_project(
    root: &Path,
    remap: &BTreeMap<String, String>,
    rewrite: Rewrite<'_>,
) -> Result<Remap> {
    // ยง b73qzqyt9.c@rg03r
    let mut writes = Vec::new();
    let mut warnings = Vec::new();
    let mut kept = BTreeSet::new();
    let all = |text: &str| {
        remap
            .iter()
            .fold(text.to_string(), |acc, (old, new)| rewrite(&acc, old, new))
    };
    let project = walk::Project::at(root)?;
    for rel in collect_rewrite_paths(root)? {
        let Ok(body) = std::fs::read_to_string(root.join(&rel)) else {
            continue;
        };
        let markdown = crate::marker::is_markdown(&rel);
        let fenced = crate::marker::fenced_lines(markdown, &body);
        let literal = if markdown {
            Vec::new()
        } else {
            crate::span::unmarked_lines(&rel, &body, None)
        };
        let heads: BTreeMap<usize, String> = if project.is_note(&rel) {
            parse::scan_text(&rel, &body)
                .laws
                .into_iter()
                .map(|law| (law.loc.line - 1, law.id))
                .collect()
        } else {
            BTreeMap::new()
        };
        let mut lines = Vec::new();
        for (idx, line) in body.split('\n').enumerate() {
            let Some(law) = heads.get(&idx) else {
                // ยง xnsbksxv6.a@jntbv
                let pointer = if markdown {
                    !fenced.get(idx).copied().unwrap_or(false)
                } else {
                    // ยง xs2e8kj86.a@ag1gz
                    !literal.get(idx).copied().unwrap_or(false)
                        && crate::marker::is_pointer_line(line)
                };
                lines.push(if pointer {
                    outside_inline_code(line, &all)
                } else {
                    line.to_string()
                });
                continue;
            };
            let split = HEAD_PREFIX_RE.find(line).map_or(0, |m| m.end());
            let (head, sentence) = line.split_at(split);
            for (old, new) in remap {
                if rewrite(sentence, old, new) != sentence {
                    kept.insert(old.clone());
                    warnings.push(format!(
                        "CITE {}:{}: the carrying sentence of ยง {law} cites {old}, left as written: rewriting it would remint ยง {law}. The law now ยง {new} keeps #{old} as an alias anchor: edit the cite, then run `silcrow accept {law}`.",
                        rel.display(),
                        idx + 1,
                    ));
                }
            }
            lines.push(format!("{}{sentence}", all(head)));
        }
        let next = lines.join("\n");
        if next != body {
            warnings.push(format!("REWRITE {}", rel.display()));
            writes.push((rel, next));
        }
    }
    Ok(Remap {
        plan: ResolvePlan {
            writes: WritePlan { writes },
            actions: Vec::new(),
            warnings,
        },
        kept,
    })
}

/// `line` with `rewrite` applied to each stretch outside inline code: backticks escape an id
/// that must not move.
fn outside_inline_code(line: &str, rewrite: &dyn Fn(&str) -> String) -> String {
    let mut out = String::with_capacity(line.len());
    let mut start = 0;
    let mut in_code = false;
    for (at, c) in line.char_indices() {
        if c != '`' {
            continue;
        }
        let part = &line[start..at];
        out.push_str(&if in_code {
            part.to_string()
        } else {
            rewrite(part)
        });
        out.push('`');
        start = at + 1;
        in_code = !in_code;
    }
    let rest = &line[start..];
    out.push_str(&if in_code {
        rest.to_string()
    } else {
        rewrite(rest)
    });
    out
}

/// `text` with each `from` that stands as a whole token, after a character `before` admits,
/// written `to`.
fn replace_token(text: &str, from: &str, to: &str, before: impl Fn(char) -> bool) -> String {
    let mut out = String::with_capacity(text.len());
    let mut last = 0;
    for (at, _) in text.match_indices(from) {
        let prev = text[..at].chars().next_back();
        let next = text[at + from.len()..].chars().next();
        let whole = prev.is_none_or(|c| !c.is_ascii_alphanumeric() && before(c))
            && next.is_none_or(|c| !c.is_ascii_alphanumeric());
        if whole && at >= last {
            out.push_str(&text[last..at]);
            out.push_str(to);
            last = at + from.len();
        }
    }
    out.push_str(&text[last..]);
    out
}

/// In a project other than the one that declares them, only the pointers qualified with the
/// declaring project's path name its ids, the cite anchor included.
pub fn plan_remap_qualified(
    root: &Path,
    origin: &str,
    remap: &BTreeMap<String, String>,
) -> Result<Remap> {
    // ยง z75jh6fxe@mgw4f
    let project = regex::escape(origin);
    let rewrite = |text: &str, old: &str, new: &str| {
        let cite = Regex::new(&format!(
            r"\[((?:ยง\s*)?){project}:{old}((?:\.[a-z]+)?)\]\(([^)#]*)#{old}\b"
        ))
        .expect("qualified cite regex");
        let text = cite.replace_all(text, format!("[${{1}}{origin}:{new}${{2}}](${{3}}#{new}"));
        // A longer project path that ends in `origin`, `corelib:` for `lib:`, is another project.
        replace_token(
            &text,
            &format!("{origin}:{old}"),
            &format!("{origin}:{new}"),
            |c| !(c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '/' | '-')),
        )
    };
    rewrite_project(root, remap, &rewrite)
}

pub fn collect_rewrite_paths(root: &Path) -> Result<Vec<PathBuf>> {
    let mut paths = Vec::new();
    for path in walk::decision_files(root)? {
        paths.push(path.strip_prefix(root).unwrap_or(&path).to_path_buf());
    }
    for path in walk::code_files(root)? {
        paths.push(path.strip_prefix(root).unwrap_or(&path).to_path_buf());
    }
    for path in walk::doc_files(root)? {
        paths.push(path.strip_prefix(root).unwrap_or(&path).to_path_buf());
    }
    if root.join("AGENTS.md").is_file() {
        paths.push(PathBuf::from("AGENTS.md"));
    }
    paths.sort();
    paths.dedup();
    Ok(paths)
}

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

    #[test]
    fn a_remap_rewrites_pointer_positions_only() {
        let x = hash::mint_id("Rule x holds.");
        let new = hash::mint_id("Rule x holds now.");
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join("AGENTS.md"),
            "<silcrow notes=\"docs/decisions/**/*.md\">\n</silcrow>\n",
        )
        .unwrap();
        std::fs::create_dir_all(dir.path().join("docs/decisions")).unwrap();
        let note = format!(
            "# N\n\n**ยง <a id=\"{x}\">{x}</a> Rule x holds now.**\n\n- (a) See [{x}](#{x}), not `{x}`.\n\n```\n// ยง {x}.a\n```\n"
        );
        std::fs::write(dir.path().join("docs/decisions/n.md"), &note).unwrap();
        std::fs::write(
            dir.path().join("lib.rs"),
            format!(
                "fn f() {{\n    // ยง {x}.a\n    log(\"REJECT {x} now\");\n    // ยง end {x}.a\n}}\n"
            ),
        )
        .unwrap();
        std::fs::write(
            dir.path().join("guide.md"),
            format!("Read ยง {x}, written `ยง {x}`.\n\n<!-- ยง {x} -->\n"),
        )
        .unwrap();
        let remap = BTreeMap::from([(x.clone(), new.clone())]);
        let Remap { plan, .. } = plan_remap(dir.path(), remap).unwrap();
        let written: BTreeMap<_, _> = plan.writes.writes.into_iter().collect();
        assert_eq!(
            written[Path::new("docs/decisions/n.md")],
            format!(
                "# N\n\n**ยง <a id=\"{new}\">{new}</a> Rule x holds now.**\n\n- (a) See [{new}](#{new}), not `{x}`.\n\n```\n// ยง {x}.a\n```\n"
            )
        );
        assert_eq!(
            written[Path::new("lib.rs")],
            format!("fn f() {{\n    // ยง {new}.a\n    log(\"REJECT {x} now\");\n    // ยง end {new}.a\n}}\n")
        );
        assert_eq!(
            written[Path::new("guide.md")],
            format!("Read ยง {new}, written `ยง {x}`.\n\n<!-- ยง {new} -->\n")
        );
    }

    #[test]
    fn a_remap_leaves_other_carrying_sentences_valid() {
        let x = hash::mint_id("Rule x holds.");
        let new = hash::mint_id("Rule x holds now.");
        let y_sentence = format!("Rule y builds on {x}.");
        let y = hash::mint_id(&y_sentence);
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join("AGENTS.md"),
            "<silcrow notes=\"docs/decisions/**/*.md\">\n</silcrow>\n",
        )
        .unwrap();
        std::fs::create_dir_all(dir.path().join("docs/decisions")).unwrap();
        let note = format!(
            "# N\n\n**ยง <a id=\"{x}\">{x}</a> Rule x holds now.**\n\n**ยง <a id=\"{y}\">{y}</a> {y_sentence}**\n\n- (a) See [{x}](#{x}).\n"
        );
        std::fs::write(dir.path().join("docs/decisions/n.md"), &note).unwrap();
        std::fs::write(
            dir.path().join("lib.rs"),
            format!("// ยง {x}\n// ยง lib:{x}\n"),
        )
        .unwrap();
        let remap = BTreeMap::from([(x.clone(), new.clone())]);
        let Remap { plan, kept } = plan_remap(dir.path(), remap).unwrap();
        assert_eq!(kept, BTreeSet::from([x.clone()]));
        let written: BTreeMap<_, _> = plan.writes.writes.into_iter().collect();
        let note = &written[Path::new("docs/decisions/n.md")];
        let scan = parse::scan_text(Path::new("docs/decisions/n.md"), note);
        for law in &scan.laws {
            assert_eq!(hash::mint_id(&law.name), law.id, "{note}");
        }
        assert!(note.contains(&format!("See [{new}](#{new})")), "{note}");
        assert!(
            plan.warnings.iter().any(|w| w.starts_with("CITE ")),
            "{:?}",
            plan.warnings
        );
        assert_eq!(
            written[Path::new("lib.rs")],
            format!("// ยง {new}\n// ยง lib:{x}\n"),
            "a qualified pointer names another project"
        );
    }

    #[test]
    fn qualifier_repair_skips_inline_code_and_fences() {
        let around = Around {
            own: ".",
            own_ids: BTreeSet::from(["abcdefgh1".to_string()]),
            others: BTreeMap::from([(
                "lib".to_string(),
                BTreeMap::from([(
                    "zzzzzzzz1".to_string(),
                    PathBuf::from("docs/decisions/n.md"),
                )]),
            )]),
        };
        let body = "See ยง zzzzzzzz1 and ยง .:abcdefgh1, not `ยง zzzzzzzz1` or `ยง .:abcdefgh1`.\n\n```\nยง zzzzzzzz1 ยง .:abcdefgh1\n```\n";
        let (out, actions) = repair_qualifiers(Path::new("docs/guide.md"), body, &around).unwrap();
        assert_eq!(
            out,
            "See ยง lib:zzzzzzzz1 and ยง abcdefgh1, not `ยง zzzzzzzz1` or `ยง .:abcdefgh1`.\n\n```\nยง zzzzzzzz1 ยง .:abcdefgh1\n```\n"
        );
        assert_eq!(actions.len(), 2, "{actions:?}");
    }

    #[test]
    fn a_qualified_remap_rewrites_only_that_project_path() {
        let out = replace_token(
            "ยง lib:abcdefgh1 ยง corelib:abcdefgh1 ยง a/lib:abcdefgh1 (ยง lib:abcdefgh1)",
            "lib:abcdefgh1",
            "lib:zzzzzzzz1",
            |c| !(c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '/' | '-')),
        );
        assert_eq!(
            out,
            "ยง lib:zzzzzzzz1 ยง corelib:abcdefgh1 ยง a/lib:abcdefgh1 (ยง lib:zzzzzzzz1)"
        );
    }

    #[test]
    fn replacement_pairs_cover_markers() {
        let pairs = replacement_pairs("runtime", "abcdefgh1", false);
        let marker = pairs
            .iter()
            .find(|(from, _)| from.starts_with("// "))
            .map(|(f, _)| f.as_str())
            .unwrap();
        assert!(marker.contains("+runtime"));
        assert!(!marker.contains("abcdefgh1"));
    }

    #[test]
    fn replacement_pairs_cover_explicit_ends() {
        let pairs = replacement_pairs("runtime", "abcdefgh1", false);
        assert!(pairs.contains(&("ยง end +runtime".into(), "ยง end abcdefgh1".into())));
    }

    #[test]
    fn replacement_pairs_use_anchor_in_decisions() {
        let pairs = replacement_pairs("runtime", "abcdefgh1", true);
        let declare = pairs
            .iter()
            .find(|(from, _)| from == "ยง +runtime")
            .map(|(_, to)| to.clone())
            .unwrap();
        assert!(declare.contains("<a id=\"abcdefgh1\">"));
    }

    #[test]
    fn rewrite_stops_at_the_end_of_a_name() {
        let names = BTreeMap::from([
            ("p1".to_string(), "aaaaaaaa1".to_string()),
            ("p10".to_string(), "bbbbbbbb1".to_string()),
            ("cache".to_string(), "cccccccc1".to_string()),
            ("cache-ttl".to_string(), "dddddddd1".to_string()),
        ]);
        let body = "fn f() {\n    // ยง +p1.a\n    // ยง +p10.a\n    // ยง +cache\n    // ยง +cache-ttl\n    // ยง end +p1.a\n    // ยง end +p10.a\n}\n";
        let mut next = body.to_string();
        for (name, id) in &names {
            for (from, to) in replacement_pairs(name, id, false) {
                next = replace_name(&next, &from, &to);
            }
        }
        assert_eq!(
            next,
            "fn f() {\n    // ยง aaaaaaaa1.a\n    // ยง bbbbbbbb1.a\n    // ยง cccccccc1\n    // ยง dddddddd1\n    // ยง end aaaaaaaa1.a\n    // ยง end bbbbbbbb1.a\n}\n"
        );
        let note = "**ยง +p1 One.**\n\n**ยง +p10 Ten, see [+p1.a](#+p1) and [+p10](#+p10).**\n\n**ยง +cache Cache.**\n\n**ยง +cache-ttl Ttl.**\n";
        let mut next = note.to_string();
        for (name, id) in &names {
            for (from, to) in replacement_pairs(name, id, true) {
                next = replace_name(&next, &from, &to);
            }
        }
        assert_eq!(
            next,
            "**ยง <a id=\"aaaaaaaa1\">aaaaaaaa1</a> One.**\n\n**ยง <a id=\"bbbbbbbb1\">bbbbbbbb1</a> Ten, see [aaaaaaaa1.a](#aaaaaaaa1) and [bbbbbbbb1](#bbbbbbbb1).**\n\n**ยง <a id=\"cccccccc1\">cccccccc1</a> Cache.**\n\n**ยง <a id=\"dddddddd1\">dddddddd1</a> Ttl.**\n"
        );
    }

    #[test]
    fn next_free_letter_skips_used() {
        let used = BTreeSet::from(["a".into(), "aa".into(), "b".into(), "c".into()]);
        assert_eq!(next_free_letter(&used).as_deref(), Some("d"));
    }

    #[test]
    fn next_free_letter_never_fills_a_gap() {
        let used = BTreeSet::from(["a".into(), "c".into(), "f".into()]);
        assert_eq!(next_free_letter(&used).as_deref(), Some("g"));
        assert_eq!(next_free_letter(&BTreeSet::new()).as_deref(), Some("a"));
    }

    #[test]
    fn no_letter_is_free_after_z() {
        let used: BTreeSet<String> = (b'a'..=b'z').map(|b| (b as char).to_string()).collect();
        assert_eq!(next_free_letter(&used), None);
        let mut letters = BTreeMap::from([("abcdefgh1".to_string(), used)]);
        let body = "**ยง abcdefgh1 A law.**\n\n- (+) New obligation.\n";
        let err =
            assign_provisional_letters(Path::new("n.md"), body, &BTreeMap::new(), &mut letters)
                .unwrap_err();
        assert!(err.to_string().contains("no single letter left"), "{err}");
    }

    #[test]
    fn a_provisional_clause_in_a_fence_is_not_lettered() {
        let mut letters = BTreeMap::new();
        let body = "**ยง abcdefgh1 A law.**\n\n```\n- (+) Example.\n```\n\n- (+) Real.\n";
        let (out, actions) =
            assign_provisional_letters(Path::new("n.md"), body, &BTreeMap::new(), &mut letters)
                .unwrap();
        assert!(out.contains("```\n- (+) Example.\n```"), "{out}");
        assert!(out.contains("- (a) Real."), "{out}");
        assert_eq!(actions.len(), 1, "{actions:?}");
    }

    #[test]
    fn bare_id_becomes_a_link() {
        let id_to_path = BTreeMap::from([(
            "abcdefgh1".to_string(),
            PathBuf::from("docs/decisions/cli/list.md"),
        )]);
        let source = PathBuf::from("docs/decisions/verbs.md");
        let body = "See abcdefgh1.a and `abcdefgh1`, [abcdefgh1](cli/list.md#abcdefgh1), ยง abcdefgh1, standards.\n";
        assert_eq!(
            link_bare_ids(body, &source, &id_to_path, &BTreeSet::new()),
            "See [abcdefgh1.a](cli/list.md#abcdefgh1) and `abcdefgh1`, [abcdefgh1](cli/list.md#abcdefgh1), ยง abcdefgh1, standards.\n"
        );
        let head = "**ยง <a id=\"abcdefgh2\">abcdefgh2</a> It logs abcdefgh1.**\n";
        assert_eq!(
            link_bare_ids(head, &source, &id_to_path, &BTreeSet::new()),
            head
        );
    }

    #[test]
    fn rewrite_cite_paths_updates_stale_location() {
        let id = "abcdefgh1";
        let id_to_path = BTreeMap::from([(
            id.to_string(),
            PathBuf::from("docs/decisions/cli/resolve.md"),
        )]);
        let source = PathBuf::from("docs/decisions/silcrow-design.md");
        let body = format!("[resolve](old/resolve.md#{id})");
        let out = rewrite_cite_paths(&body, &source, &id_to_path);
        assert!(out.contains("cli/resolve.md#abcdefgh1"));
        assert!(!out.contains("old/resolve.md"));
    }

    #[test]
    fn rewrite_cite_paths_leaves_correct_path() {
        let id = "abcdefgh1";
        let id_to_path = BTreeMap::from([(
            id.to_string(),
            PathBuf::from("docs/decisions/cli/resolve.md"),
        )]);
        let source = PathBuf::from("docs/decisions/silcrow-design.md");
        let body = format!("[resolve](cli/resolve.md#{id})");
        let out = rewrite_cite_paths(&body, &source, &id_to_path);
        assert_eq!(out, body);
    }

    #[test]
    fn a_provisional_row_of_a_lettered_table_is_lettered_and_a_label_row_is_not() {
        let mut letters = BTreeMap::from([("abcdefgh1".to_string(), BTreeSet::from(["a".into()]))]);
        let body = "**ยง abcdefgh1 A law.**\n\n| Clause | Rule |\n| --- | --- |\n| (a) | One. |\n| (+) | Refunds below 10 are free. |\n\n- (+) An item.\n\n  | Row | Text |\n  | --- | --- |\n  | (+) | A label. |\n";
        let (out, actions) =
            assign_provisional_letters(Path::new("n.md"), body, &BTreeMap::new(), &mut letters)
                .unwrap();
        assert!(
            out.contains("| (b) | Refunds below 10 are free. |"),
            "{out}"
        );
        assert!(out.contains("- (c) An item."), "{out}");
        assert!(out.contains("| (+) | A label. |"), "{out}");
        assert_eq!(actions.len(), 2, "{actions:?}");
        let scan = parse::scan_text(Path::new("n.md"), &out);
        assert!(
            scan.laws[0]
                .clauses
                .iter()
                .any(|c| c.letter.as_deref() == Some("b") && c.text.contains("Refunds below 10")),
            "{:?}",
            scan.laws[0].clauses
        );
        assert!(scan.form_errors.is_empty(), "{:?}", scan.form_errors);
        let left = parse::scan_text(Path::new("n.md"), body);
        let lines: Vec<usize> = left.form_errors.iter().map(|e| e.loc.line).collect();
        assert_eq!(lines, [6, 8], "{:?}", left.form_errors);
    }

    #[test]
    fn assign_provisional_letters_under_the_law() {
        let mut letters = BTreeMap::from([(
            "abcdefgh1".to_string(),
            BTreeSet::from(["a".into(), "b".into()]),
        )]);
        let body = "**ยง abcdefgh1 A law.**\n\n- (a) One.\n\n- (+) New obligation.\n";
        let (out, actions) =
            assign_provisional_letters(Path::new("n.md"), body, &BTreeMap::new(), &mut letters)
                .unwrap();
        assert!(out.contains("(c) New obligation."));
        assert!(actions.iter().any(|a| a.contains("abcdefgh1.c")));
    }

    mod props {
        use super::super::*;
        use crate::note_gen;
        use proptest::prelude::*;

        const NOTE: &str = "docs/decisions/note.md";

        fn prop_project(text: &str) -> tempfile::TempDir {
            let dir = tempfile::tempdir().unwrap();
            std::fs::create_dir_all(dir.path().join("docs/decisions")).unwrap();
            std::fs::write(
                dir.path().join("AGENTS.md"),
                "<silcrow notes=\"docs/decisions/**/*.md\">\nGraph: silcrow check.\n</silcrow>\n",
            )
            .unwrap();
            std::fs::write(dir.path().join(NOTE), text).unwrap();
            dir
        }

        /// One `fix` pass on the notes, applied, and the writes it planned.
        fn prop_fix(dir: &Path) -> Vec<(PathBuf, String)> {
            let ws = Workspace::discover(dir).unwrap();
            let project = ws.get(".").unwrap();
            let plan = plan_scoped(&ws, project, None).unwrap();
            for (rel, text) in &plan.writes.writes {
                std::fs::write(dir.join(rel), text).unwrap();
            }
            plan.writes.writes
        }

        fn prop_sentence(law: &parse::Law) -> String {
            let name = if hash::is_provisional_id(&law.id) {
                law.name.replace(&format!("ยง {}", law.id), "")
            } else {
                law.name.clone()
            };
            hash::canonicalise(&name)
        }

        type PinTexts = Vec<(String, String, bool, Vec<(String, String, bool)>)>;

        fn prop_texts(text: &str) -> PinTexts {
            parse::scan_text(Path::new(NOTE), text)
                .laws
                .iter()
                .map(|law| {
                    let clauses = law
                        .clauses
                        .iter()
                        .map(|al| {
                            (
                                al.letter.clone().unwrap(),
                                hash::pin_canon(&al.pin_body()),
                                al.struck,
                            )
                        })
                        .collect();
                    (
                        prop_sentence(law),
                        hash::pin_canon(&law.body),
                        law.struck,
                        clauses,
                    )
                })
                .collect()
        }

        proptest! {
            #![proptest_config(ProptestConfig {
                cases: 64,
                failure_persistence: None,
                ..ProptestConfig::default()
            })]

            #[test]
            fn fix_is_idempotent(note in note_gen::gen_note(true, false)) {
                let dir = prop_project(&note.render().text);
                prop_fix(dir.path());
                let again = prop_fix(dir.path());
                prop_assert!(again.is_empty(), "second pass rewrote {:?}", again);
            }

            #[test]
            fn fix_keeps_canonical_clause_text(note in note_gen::gen_note(true, false)) {
                let text = note.render().text;
                let dir = prop_project(&text);
                prop_fix(dir.path());
                let fixed = std::fs::read_to_string(dir.path().join(NOTE)).unwrap();
                prop_assert_eq!(prop_texts(&fixed), prop_texts(&text), "\n{}\n---\n{}", text, fixed);
            }
        }
    }
}