silcrow 0.1.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
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
use anyhow::{Context, Result};
use regex::Regex;
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::sync::LazyLock;

use crate::hash;
use crate::marker;
use crate::walk;

pub use crate::model::{
    Adoption, Clause, FormError, Law, Location, Pointer, PointerKind, Scan, Target,
};

use crate::marker::{DIGEST, ID, PROJECTPATH};

/// `§ <projectpath>:<id>[.<letter>]`: a reference into a project, never a declaration.
static QUALIFIED_RE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(&format!(r"§\s*({PROJECTPATH}):({ID})(?:\.([a-z]+))?\b")).expect("qualified regex")
});

static QUALIFIED_OPEN_RE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(&format!(r"^\s*(?:\*\*)?\s*§\s*{PROJECTPATH}:{ID}")).expect("qualified open regex")
});

static ADOPT_RE: LazyLock<Regex> = LazyLock::new(|| {
    // § v8b14v6pn.a@tgg5e
    Regex::new(&format!(
        r"^\s*\*\*§\s*({PROJECTPATH}):({ID})(?:\.([a-z]+))?\*\*\s*$"
    ))
    .expect("adopt regex")
});

static CITE_TEXT_RE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(&format!(r"^(?:§\s*)?({PROJECTPATH}):(.+)$")).expect("cite text regex")
});

static SIGN_RE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(&format!(
        r#"\(\s*§\s*<a\s+id="({ID})">{ID}</a>\s*\)|§\s*<a\s+id="({ID})">{ID}</a>|\(\s*§\s*({ID})\s*\)|§\s+({ID})\b"#
    ))
    .expect("marker regex")
});

static HEADING_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^(#{1,6})\s+(.+?)\s*$").expect("heading regex"));

static MD_LINK_RE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"\[([^\]]*)\]\(((?:[^)\s]*\.md)?#[^)\s]*)\)").expect("md link regex")
});

static ANCHOR_RE: LazyLock<Regex> = LazyLock::new(|| {
    // § h36xkjqaa.b@cyx1t
    Regex::new(&format!(r"#({ID})(?:\.([a-z]+))?(?:@{DIGEST})?\b")).expect("anchor regex")
});

static LETTER_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^\(([a-z]+)\)(?:\s+|$)").expect("letter token regex"));

static STRAY_LETTER_RE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"^\s*(?:(?:[-*+]|\d+[.)])\s*)?\(([a-z]+)\)(?:\s|$)").expect("stray letter regex")
});

static PROVISIONAL_DECLARE_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"§\s*\+([a-z0-9-]+)").expect("provisional declare regex"));

static MENTION_RE: LazyLock<Regex> = LazyLock::new(|| {
    // § n71fgy5xw.b@eaz5h
    Regex::new(&format!(r"§\s*({})(?:\.([a-z]+))?\b", marker::ID_READ)).expect("mention regex")
});

pub fn scan_root(root: &Path) -> Result<Scan> {
    // § q3ckz9sm8@93tww
    // § p9e62dtvr.a@98kp7
    let mut notes = Vec::new();
    for path in walk::decision_files(root)? {
        let text =
            std::fs::read_to_string(&path).with_context(|| format!("read {}", path.display()))?;
        let rel = PathBuf::from(display_path(&path, root));
        notes.push((rel, text));
    }
    let mut scan = scan_notes(&notes);
    // § end p9e62dtvr.a
    // The code walk also holds the documentation, which the doc walk below reads with its
    // mentions: a Markdown file outside `docs` is read for its markers alone.
    let project = walk::Project::at(root)?;
    let code: Vec<PathBuf> = walk::code_files(root)?
        .into_iter()
        .filter(|path| !project.is_doc(path.strip_prefix(root).unwrap_or(path)))
        .collect();
    for found in crate::par::map(code, |_| 1, |path| file_markers(root, &path, false)) {
        scan.pointers.extend(found?.pointers);
    }
    // § xs2e8kj86.f@h242v
    let docs = walk::doc_files(root)?;
    scan.doc_files = docs
        .iter()
        .map(|path| PathBuf::from(display_path(path, root)))
        .collect();
    for found in crate::par::map(docs, |_| 1, |path| file_markers(root, &path, true)) {
        let found = found?;
        scan.pointers.extend(found.pointers);
        scan.mentions.extend(found.mentions);
    }
    // § end xs2e8kj86.f
    Ok(scan)
}

/// The markers of one file, and its mentions when `mentions`, read on any thread.
fn file_markers(root: &Path, path: &Path, mentions: bool) -> Result<Scan> {
    let text = std::fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?;
    let rel = PathBuf::from(display_path(path, root));
    let mut scan = Scan::default();
    extract_markers(&rel, &text, &mut scan);
    // § mwneg21bd.d@nvek8
    if mentions {
        extract_mentions(&rel, &text, &mut scan);
        extract_doc_cites(&rel, &text, &mut scan);
    }
    // § end mwneg21bd.d
    Ok(scan)
}

/// The cite links of a documentation file: a link whose text is the id it targets, so a heading
/// anchor that happens to read like an id is not a cite.
fn extract_doc_cites(path: &Path, text: &str, scan: &mut Scan) {
    // § nth5nbchz.a@6dsg1
    let lines: Vec<&str> = text.lines().collect();
    let mut fence = fence_mask(&lines);
    mask_agents_block(path, text, &mut fence);
    for (idx, line) in lines.iter().enumerate() {
        if fence[idx] || !line.contains('#') {
            continue;
        }
        for caps in MD_LINK_RE.captures_iter(&mask_inline_code(line)) {
            let Some((project, id, letter)) = cite_target(&caps[1], &caps[2]) else {
                continue;
            };
            let label = caps[1].trim().trim_start_matches('§').trim_start();
            let label = match CITE_TEXT_RE.captures(label) {
                Some(named) if project.is_some() => named.get(2).map_or("", |m| m.as_str()),
                _ => label,
            };
            if !label.to_ascii_lowercase().starts_with(&id) {
                continue;
            }
            scan.pointers.push(Pointer {
                kind: PointerKind::Cite,
                project,
                name: id.clone(),
                target: pointer_target(id, letter),
                loc: Location {
                    path: path.to_path_buf(),
                    line: idx + 1,
                },
            });
        }
    }
}

pub fn scan_notes(notes: &[(PathBuf, String)]) -> Scan {
    // § v9apefaqs@msz6p
    let mut scan = Scan::default();
    for (rel, text) in notes {
        parse_note_text(rel, text, &mut scan);
    }
    lint_duplicate_ids(&mut scan);
    scan
}

pub fn scan_text(path: &Path, text: &str) -> Scan {
    let mut scan = Scan::default();
    parse_note_text(path, text, &mut scan);
    scan
}

pub fn parse_note_text(path: &Path, text: &str, scan: &mut Scan) {
    // § pxmeee9ra.c@var0h
    let raw: Vec<&str> = text.lines().collect();
    let fence = fence_mask(&raw);
    // The note is read with each draft `?` and each public `!` taken out, so a law reads, hashes
    // and mints as the same law written without them.
    let mut marked: HashMap<usize, Marks> = HashMap::new();
    let plain: Vec<std::borrow::Cow<'_, str>> = raw
        .iter()
        .enumerate()
        .map(|(i, line)| match unmark(line).filter(|_| !fence[i]) {
            Some((plain, marks)) => {
                marked.insert(i + 1, marks);
                std::borrow::Cow::Owned(plain)
            }
            None => std::borrow::Cow::Borrowed(*line),
        })
        .collect();
    let lines: Vec<&str> = plain.iter().map(|line| line.as_ref()).collect();
    // § end pxmeee9ra.c
    extract_pointers(path, &lines, &fence, scan);
    let first = scan.laws.len();
    extract_laws(path, &lines, &fence, scan);
    // § pxmeee9ra.b@5vtd0
    let draft = |line: usize| marked.get(&line).is_some_and(|m| m.draft);
    for law in &mut scan.laws[first..] {
        law.draft = draft(law.loc.line);
        for clause in &mut law.clauses {
            clause.draft = law.draft || draft(clause.loc.line);
        }
    }
    // § end pxmeee9ra.b
    // § q3ckz9sm8.e@ds4xf
    for law in &mut scan.laws[first..] {
        let marks = marked.get(&law.loc.line).copied().unwrap_or_default();
        law.public = marks.public;
        // § q3ckz9sm8.f@8th8x
        if marks.misordered {
            scan.form_errors.push(FormError {
                loc: law.loc.clone(),
                message: format!(
                    "the head of § {} opens `§?!`: a draft public promise opens `§!?`, its `?` last as a clause writes `(a)?`. Run `silcrow fix`",
                    law.id
                ),
            });
        }
        // § end q3ckz9sm8.f
    }
    // § end q3ckz9sm8.e
    reject_leftovers(path, &lines, &fence, first, scan);
    reject_html_comments(path, &lines, &fence, scan);
}

/// A law head that opens `§` with its marks: `!` for a public promise, `?` for a draft, and
/// both for a draft public promise.
static HEAD_MARKS_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^(\s*(?:\*\*)?\s*)§(!\?|\?!|!|\?)").expect("head marks regex"));

/// A clause item whose letter token reads `(x)?` or `(+)?`.
static DRAFT_CLAUSE_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^(\s*- \((?:[a-z]+|\+)\))\?(\s|$)").expect("draft clause regex"));

/// The marks of a law head or a clause item: a draft `?`, a public `!`, and whether a head
/// writes them in the order `§?!`.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Marks {
    pub draft: bool,
    pub public: bool,
    pub misordered: bool,
}

/// `line` without the marks of its law head or of its clause item, and those marks, or `None`
/// when it writes none: a `?` or a `!` anywhere else is text.
pub(crate) fn unmark(line: &str) -> Option<(String, Marks)> {
    // § pxmeee9ra.a@d3m19
    if let Some(caps) = HEAD_MARKS_RE.captures(line) {
        let plain = format!("{}§{}", &caps[1], &line[caps.get(0)?.end()..]);
        let marks = Marks {
            draft: caps[2].contains('?'),
            public: caps[2].contains('!'),
            misordered: &caps[2] == "?!",
        };
        return (!declare_ids(&plain).is_empty()).then_some((plain, marks));
    }
    DRAFT_CLAUSE_RE.is_match(line).then(|| {
        let marks = Marks {
            draft: true,
            ..Marks::default()
        };
        (
            DRAFT_CLAUSE_RE.replace(line, "${1}${2}").into_owned(),
            marks,
        )
    })
}

/// `line`, a law head or a clause item written without marks, with `marks`, a head's in the
/// order `§!?`.
pub(crate) fn remark(line: &str, marks: Marks) -> String {
    if letter_token(line).is_some() {
        return match marks.draft {
            true => line.replacen(')', ")?", 1),
            false => line.to_string(),
        };
    }
    let sign = match (marks.public, marks.draft) {
        (true, true) => "§!?",
        (true, false) => "§!",
        (false, true) => "§?",
        (false, false) => return line.to_string(),
    };
    line.replacen('§', sign, 1)
}

/// `line` without the `?` that makes its law head or its clause item a draft, its `!` kept, or
/// `None` when it writes no draft.
pub(crate) fn undraft(line: &str) -> Option<String> {
    let (plain, marks) = unmark(line)?;
    marks.draft.then(|| {
        remark(
            &plain,
            Marks {
                draft: false,
                ..marks
            },
        )
    })
}

/// `line`, a law head or a clause item written without a draft `?`, with it.
pub(crate) fn redraft(line: &str) -> String {
    let (plain, marks) = unmark(line).unwrap_or_else(|| (line.to_string(), Marks::default()));
    remark(
        &plain,
        Marks {
            draft: true,
            ..marks
        },
    )
}

/// `patch` with each head written as a plain `**§ `: adding or dropping a mark is no step of a
/// law's lineage.
pub(crate) fn plain_heads(patch: &str) -> String {
    static MARKED: LazyLock<Regex> =
        LazyLock::new(|| Regex::new(r"\*\*§[!?]{1,2} ").expect("marked head regex"));
    MARKED.replace_all(patch, "**§ ").into_owned()
}

/// A decision note reads the same without the CLI, so it hides nothing in an HTML comment.
fn reject_html_comments(path: &Path, lines: &[&str], fence: &[bool], scan: &mut Scan) {
    // § jhee7aqvb.a@w0md1
    for (idx, line) in lines.iter().enumerate() {
        if fence[idx] || !mask_inline_code(line).contains("<!--") {
            continue;
        }
        scan.form_errors.push(FormError {
            loc: Location {
                path: path.to_path_buf(),
                line: idx + 1,
            },
            message: "an HTML comment in a decision note: a note carries none, so write it as prose or delete it".to_string(),
        });
    }
}

/// A struck clause, a tombstone or an alias anchor that no law of the note holds can only be
/// what a deletion left behind.
fn reject_leftovers(path: &Path, lines: &[&str], fence: &[bool], first: usize, scan: &mut Scan) {
    // § vw7bmw3s3.f@zdw0n
    let mut held = HashSet::new();
    for law in &scan.laws[first..] {
        held.extend(law.loc.line..=law.end);
        for al in &law.clauses {
            held.extend(al.loc.line..=al.end);
        }
    }
    let reported: HashSet<usize> = scan
        .form_errors
        .iter()
        .filter(|e| e.loc.path == path)
        .map(|e| e.loc.line)
        .collect();
    for (idx, line) in lines.iter().enumerate() {
        if fence[idx]
            || held.contains(&(idx + 1))
            || reported.contains(&(idx + 1))
            || !declare_ids(line).is_empty()
        {
            continue;
        }
        let item = letter_token(line);
        let retired = item
            .as_ref()
            .is_some_and(|(_, rest)| is_struck(line) || is_tombstone(rest));
        let message = if retired {
            "a struck clause or a tombstone that no law holds: delete the leftover of the removed law"
        } else if !hash::aliases_in(line).is_empty() {
            "an alias anchor outside a law head: delete the leftover of the removed law"
        } else if item.is_some() {
            // § wqhsnrn8a.d@er1vs
            "a clause item that attaches to no law: no head opens its section above it. Move it under the head of its law, or drop its letter"
        } else {
            continue;
        };
        scan.form_errors.push(FormError {
            loc: Location {
                path: path.to_path_buf(),
                line: idx + 1,
            },
            message: message.to_string(),
        });
    }
}

/// The lines inside a code fence, fence lines included, as CommonMark reads a fence: a run of
/// at least three backticks or tildes opens it, a backtick fence with no backtick after its
/// run, and a run of the same character at least as long with only whitespace after closes it.
/// A fence that never closes runs to the end.
pub fn fence_mask(lines: &[&str]) -> Vec<bool> {
    // § xs2e8kj86.a@b10dw
    let mut out = vec![false; lines.len()];
    let mut open: Option<(char, usize)> = None;
    for (i, line) in lines.iter().enumerate() {
        let trimmed = line.trim_start();
        let run = |c: char| trimmed.chars().take_while(|&x| x == c).count();
        match open {
            Some((c, n)) => {
                out[i] = true;
                let len = run(c);
                if len >= n && trimmed[len..].trim().is_empty() {
                    open = None;
                }
            }
            None => {
                let fence = ['`', '~'].into_iter().find_map(|c| {
                    let len = run(c);
                    let info = &trimmed[len.min(trimmed.len())..];
                    (len >= 3 && !(c == '`' && info.contains('`'))).then_some((c, len))
                });
                if fence.is_some() {
                    out[i] = true;
                    open = fence;
                }
            }
        }
    }
    out
}

fn extract_laws(path: &Path, lines: &[&str], fence: &[bool], scan: &mut Scan) {
    // § q3ckz9sm8.b@edg1q
    let bounds = section_bounds(lines.len(), &section_headings(lines, fence));
    for (start, end) in bounds {
        let mut marks = Vec::new();
        for i in start..end {
            if fence[i] {
                continue;
            }
            if adopt(path, lines[i], i, scan) {
                continue;
            }
            reject_stray_sign(path, lines[i], i, scan);
            let ids = declare_ids(lines[i]);
            // § n71fgy5xw@f2804
            if ids.is_empty() && line_opens_with_sign(lines[i]) {
                scan.form_errors.push(FormError {
                    loc: Location {
                        path: path.to_path_buf(),
                        line: i + 1,
                    },
                    message: "§ opens this paragraph without a valid Crockford id".to_string(),
                });
            }
            // § end n71fgy5xw
            for id in ids {
                if !hash::is_provisional_id(&id) && !hash::is_crockford_id(&id) {
                    // § n71fgy5xw@2660h
                    scan.form_errors.push(FormError {
                        loc: Location {
                            path: path.to_path_buf(),
                            line: i + 1,
                        },
                        message: format!("§ {id} is not a valid Crockford id"),
                    });
                    continue;
                }
                marks.push((i, id));
            }
        }
        for (carry_idx, id) in marks {
            match infer_law(
                path,
                lines,
                fence,
                carry_idx,
                &id,
                end,
                &mut scan.form_errors,
            ) {
                Ok(law) => {
                    lint_letter_order(&law, &mut scan.lints);
                    lint_letter_gap(&law, &mut scan.lints);
                    scan.laws.push(law);
                }
                Err(err) => scan.form_errors.push(err),
            }
        }
    }
}

/// A single letter written after a later one reads as an insertion that took a single letter,
/// where an insertion between two letters takes a compound. Moving the line changes no letter.
fn lint_letter_order(law: &Law, lints: &mut Vec<crate::model::Lint>) {
    // § wqhsnrn8a.b@8bx0p
    let mut last: Option<&str> = None;
    for clause in &law.clauses {
        let Some(letter) = clause.letter.as_deref().filter(|l| l.len() == 1) else {
            continue;
        };
        match last {
            Some(prev) if letter < prev => lints.push(crate::model::Lint {
                loc: clause.loc.clone(),
                message: format!(
                    "clause ({letter}) of § {} is written after ({prev}): an insertion between two letters takes a compound letter. Move it above ({prev}), or write it as a compound under the letter it narrows",
                    law.id
                ),
            }),
            _ => last = Some(letter),
        }
    }
}

/// A clause line carries no id, so git cannot find a deleted letter the way it finds an id: the
/// tombstone is the only reservation `check` can read in the tree alone.
fn lint_letter_gap(law: &Law, lints: &mut Vec<crate::model::Lint>) {
    // § s6aqqwvmc.a@nyx19
    let singles: Vec<(char, &Clause)> = law
        .clauses
        .iter()
        .filter_map(|c| {
            let letter = c.letter.as_deref()?;
            let mut chars = letter.chars();
            let first = chars.next()?;
            chars.next().is_none().then_some((first, c))
        })
        .collect();
    let Some(&(last, clause)) = singles.iter().max_by_key(|(l, _)| *l) else {
        return;
    };
    for gap in ('a'..last).filter(|g| singles.iter().all(|(l, _)| l != g)) {
        lints.push(crate::model::Lint {
            loc: clause.loc.clone(),
            message: format!(
                "§ {} writes ({last}) and not ({gap}): a retired letter stays in the tree while its law does. Write ({gap}) back struck or as the tombstone `- ({gap}) **Retired.**`, so no clause takes it again",
                law.id
            ),
        });
    }
}

fn section_headings(lines: &[&str], fence: &[bool]) -> Vec<usize> {
    let mut out = Vec::new();
    for (i, line) in lines.iter().enumerate() {
        if fence[i] {
            continue;
        }
        if let Some((level, _)) = parse_heading(line) {
            if level == 2 {
                out.push(i);
            }
        }
    }
    out
}

fn section_bounds(n: usize, headings: &[usize]) -> Vec<(usize, usize)> {
    let mut out = Vec::new();
    if headings.is_empty() {
        if n > 0 {
            out.push((0, n));
        }
        return out;
    }
    if headings[0] > 0 {
        out.push((0, headings[0]));
    }
    for (k, &idx) in headings.iter().enumerate() {
        let end = headings.get(k + 1).copied().unwrap_or(n);
        out.push((idx, end));
    }
    out
}

fn infer_law(
    path: &Path,
    lines: &[&str],
    fence: &[bool],
    carry_idx: usize,
    id: &str,
    section_end: usize,
    errors: &mut Vec<FormError>,
) -> Result<Law, FormError> {
    // § p9e62dtvr@5jg2w
    let raw = lines[carry_idx];
    let loc_err = || Location {
        path: path.to_path_buf(),
        line: carry_idx + 1,
    };
    let (carry_text, _parent_indent, _) = carrying_block(raw).ok_or_else(|| FormError {
        loc: loc_err(),
        message: "§ has no determinable carrying block".to_string(),
    })?;
    // § wqhsnrn8a.g@ba67a
    if letter_token(raw).is_some() {
        errors.push(FormError {
            loc: loc_err(),
            message: format!("carrying line of § {id} must not carry a letter"),
        });
    }
    // § end wqhsnrn8a.g
    let mut clauses: Vec<Clause> = Vec::new();
    let mut acc = Attached::new(carry_idx);
    let mut seen = HashSet::new();
    let mut owner = Owner::Head;
    let mut prev_blank = false;
    let mut table_rows_letter: Option<bool> = None;
    // The rows of the table being read that come before its first lettered row.
    let mut table_header: Option<Vec<&str>> = None;
    let err_at = |j: usize, message: String| FormError {
        loc: Location {
            path: path.to_path_buf(),
            line: j + 1,
        },
        message,
    };
    for j in carry_idx + 1..section_end {
        let raw = lines[j];
        if fence[j] {
            // § wqhsnrn8a.e@dpqjz
            acc.attach(&owner, j, raw);
            prev_blank = false;
            continue;
        }
        if let Some((level, _)) = parse_heading(raw) {
            if level == 2 {
                break;
            }
            owner = Owner::Free;
            acc.attach(&owner, j, raw);
            prev_blank = false;
            continue;
        }
        if !declare_ids(raw).is_empty() {
            break;
        }
        if raw.trim().is_empty() {
            prev_blank = true;
            table_rows_letter = None;
            table_header = None;
            continue;
        }
        if raw.trim_start().starts_with('|') {
            let rows_letter = *table_rows_letter.get_or_insert(matches!(owner, Owner::Head));
            let lettered = if rows_letter { table_letter(raw) } else { None };
            prev_blank = false;
            if rows_letter && provisional_letter(raw.trim_start().trim_start_matches('|')) {
                // § fxas3vhge.e@pppez
                errors.push(err_at(j, unlettered(id)));
            }
            let Some((letter, rest)) = lettered else {
                // § wqhsnrn8a.f@wphs7
                if rows_letter
                    && matches!(owner, Owner::Head)
                    && !provisional_letter(raw.trim_start().trim_start_matches('|'))
                {
                    table_header.get_or_insert_with(Vec::new).push(raw);
                }
                acc.attach(&owner, j, raw);
                continue;
            };
            if let Some(parent) = parent_letter(&letter).filter(|p| !seen.contains(*p)) {
                // § wqhsnrn8a.b@x82th
                errors.push(err_at(
                    j,
                    format!(
                        "compound clause ({letter}) for § {id} has no parent ({parent}) before it"
                    ),
                ));
                owner = Owner::Free;
                continue;
            }
            if !seen.insert(letter.clone()) {
                // § wqhsnrn8a.c@15hh8
                errors.push(err_at(
                    j,
                    format!("duplicate clause letter ({letter}) for § {id}"),
                ));
                continue;
            }
            owner = Owner::Clause(clauses.len());
            acc.open(j, rest);
            clauses.push(Clause {
                header: table_header.get_or_insert_with(Vec::new).join("\n"),
                // The text keeps the letter cell, so the row has as many cells as its header.
                text: clean_body(raw.trim()),
                ..new_clause(path, j, letter, rest, raw)
            });
            continue;
        }
        table_rows_letter = None;
        table_header = None;
        if let Some((letter, rest)) = letter_token(raw) {
            prev_blank = false;
            if let Some(parent) = parent_letter(&letter) {
                // § wqhsnrn8a.b@g84dn
                if !seen.contains(parent) {
                    errors.push(err_at(
                        j,
                        format!("compound clause ({letter}) for § {id} has no parent ({parent}) before it"),
                    ));
                    owner = Owner::Free;
                    continue;
                }
            }
            if !seen.insert(letter.clone()) {
                // § wqhsnrn8a.c@zkz85
                errors.push(err_at(
                    j,
                    format!("duplicate clause letter ({letter}) for § {id}"),
                ));
                owner = Owner::Free;
                continue;
            }
            owner = Owner::Clause(clauses.len());
            acc.open(j, rest);
            clauses.push(new_clause(path, j, letter, rest, raw));
            continue;
        }
        if split_indent(raw)
            .1
            .strip_prefix("- ")
            .is_some_and(provisional_letter)
        {
            // § fxas3vhge.e@34dkd
            errors.push(err_at(j, unlettered(id)));
        }
        // § wqhsnrn8a.d@7ztse
        if let Some(letter) = stray_letter(raw) {
            errors.push(err_at(
                j,
                format!("({letter}) opens a line but is not a clause: write `- ({letter})`, or reword the line"),
            ));
        }
        // § end wqhsnrn8a.d
        // § wqhsnrn8a.a@r1btz
        let continues = !prev_blank || split_indent(raw).0 >= 2;
        prev_blank = false;
        if !continues {
            owner = Owner::Free;
        }
        acc.attach(&owner, j, raw);
        // § end wqhsnrn8a.a
    }
    let last_clause = clauses.last().map_or(0, |c| c.loc.line - 1);
    let mut context = String::new();
    let mut prev = None;
    for (j, raw) in acc.free.into_iter().filter(|(j, _)| *j < last_clause) {
        match prev {
            None => {}
            Some(p) if p + 1 == j => context.push('\n'),
            Some(_) => context.push_str("\n\n"),
        }
        context.push_str(&raw);
        prev = Some(j);
    }
    for (al, (body, end)) in clauses.iter_mut().zip(acc.bodies) {
        al.body = body.join("\n");
        al.end = end + 1;
    }
    let mut law_name = strip_letter_token(&carry_text);
    // § one fxas3vhge@a7wwb
    if let Some(name) = id.strip_prefix('+') {
        let head =
            Regex::new(&format!(r"^§\s*\+{}\s*", regex::escape(name))).expect("head name regex");
        law_name = head.replace(&law_name, "").into_owned();
    }
    Ok(Law {
        id: id.to_string(),
        name: law_name,
        body: acc.head.join("\n"),
        end: acc.head_end + 1,
        context,
        aliases: hash::aliases_in(raw),
        loc: Location {
            path: path.to_path_buf(),
            line: carry_idx + 1,
        },
        clauses,
        struck: is_struck(lines[carry_idx]),
        draft: false,
        public: false,
    })
}

enum Owner {
    Head,
    Clause(usize),
    Free,
}

/// The lines each owner holds, with the index of the last one it reached.
struct Attached {
    head: Vec<String>,
    head_end: usize,
    bodies: Vec<(Vec<String>, usize)>,
    /// The lines no owner holds, with their index.
    free: Vec<(usize, String)>,
}

impl Attached {
    fn new(carry_idx: usize) -> Self {
        Self {
            head: Vec::new(),
            head_end: carry_idx,
            bodies: Vec::new(),
            free: Vec::new(),
        }
    }

    fn open(&mut self, j: usize, rest: &str) {
        self.bodies.push((vec![rest.to_string()], j));
    }

    fn attach(&mut self, owner: &Owner, j: usize, raw: &str) {
        match owner {
            Owner::Head => {
                self.head.push(raw.to_string());
                self.head_end = j;
            }
            Owner::Clause(k) => {
                let (body, end) = &mut self.bodies[*k];
                body.push(raw.to_string());
                *end = j;
            }
            Owner::Free => self.free.push((j, raw.to_string())),
        }
    }
}

fn new_clause(path: &Path, j: usize, letter: String, rest: &str, raw: &str) -> Clause {
    // § p9e62dtvr.b@25631
    Clause {
        stable_id: None,
        letter: Some(letter),
        text: clean_body(rest),
        body: String::new(),
        header: String::new(),
        end: j + 1,
        struck: is_struck(raw) || is_tombstone(rest),
        draft: false,
        loc: Location {
            path: path.to_path_buf(),
            line: j + 1,
        },
    }
}

/// Whether `text` opens with the provisional letter `(+)`, which `fix` replaces.
fn provisional_letter(text: &str) -> bool {
    text.trim_start()
        .strip_prefix("(+)")
        .is_some_and(|rest| rest.is_empty() || rest.starts_with(char::is_whitespace))
}

const UNLETTERED: &str = "still carries the provisional letter (+)";

fn unlettered(id: &str) -> String {
    format!("a clause of § {id} {UNLETTERED}, which must be lettered before integration. Run `silcrow fix` to letter it.")
}

/// Whether a form error is the one a clause written `(+)` raises until `fix` letters it.
pub fn names_provisional_letter(message: &str) -> bool {
    message.contains(UNLETTERED)
}

/// A table row whose first cell opens with a letter token: `| (a) text | ... |`.
fn table_letter(raw: &str) -> Option<(String, &str)> {
    // § wqhsnrn8a.f@f61b1
    let cell = raw.trim_start().strip_prefix('|')?.trim_start();
    let caps = LETTER_RE.captures(cell)?;
    let letter = caps.get(1)?.as_str().to_string();
    Some((letter, cell[caps.get(0)?.end()..].trim_start()))
}

/// A letter token opening a line that is not a `- (x)` item, after any bullet, `-`, `*`, `+`,
/// `1.` or `1)`, and any run of whitespace.
fn stray_letter(raw: &str) -> Option<String> {
    STRAY_LETTER_RE.captures(raw).map(|c| c[1].to_string())
}

fn parent_letter(letter: &str) -> Option<&str> {
    (letter.len() > 1).then(|| &letter[..letter.len() - 1])
}

fn strip_letter_token(s: &str) -> String {
    LETTER_RE.replace(s, "").trim_start().to_string()
}

fn carrying_block(raw: &str) -> Option<(String, usize, bool)> {
    // § q3ckz9sm8.d@296st
    // § q3ckz9sm8.c@250v0
    if parse_heading(raw).is_some() || parse_bullet(raw).is_some() {
        return None;
    }
    // § end q3ckz9sm8.c
    // § q3ckz9sm8.b@kzj5r
    if !line_opens_with_sign(raw) {
        return None;
    }
    // § end q3ckz9sm8.b
    let (indent, body) = split_indent(raw);
    let text = clean_body(body);
    has_carrying_text(&text).then_some((text, indent, false))
}

fn line_opens_with_sign(line: &str) -> bool {
    let t = line.trim_start().trim_start_matches("**").trim_start();
    t.starts_with('§') || t.starts_with("(§")
}

fn extract_pointers(path: &Path, lines: &[&str], fence: &[bool], scan: &mut Scan) {
    // § nth5nbchz.a@wqxyv
    for (idx, line) in lines.iter().enumerate() {
        if fence[idx] {
            continue;
        }
        let loc = Location {
            path: path.to_path_buf(),
            line: idx + 1,
        };
        for caps in MD_LINK_RE.captures_iter(&mask_inline_code(line)) {
            if let Some((project, id, letter)) = cite_target(&caps[1], &caps[2]) {
                scan.pointers.push(Pointer {
                    kind: PointerKind::Cite,
                    project,
                    name: id.clone(),
                    target: pointer_target(id, letter),
                    loc: loc.clone(),
                });
            }
        }
    }
}

fn extract_markers(path: &Path, text: &str, scan: &mut Scan) {
    // § p9e62dtvr.c@txcv3
    let fenced = crate::span::unmarked_lines(path, text, None);
    for (idx, line) in text.lines().enumerate() {
        if fenced[idx] {
            continue;
        }
        let loc = Location {
            path: path.to_path_buf(),
            line: idx + 1,
        };
        for marker in marker::markers_in_line(line) {
            scan.pointers.push(Pointer {
                kind: PointerKind::Implements,
                project: marker.project.clone(),
                name: marker.id.clone(),
                target: pointer_target(marker.id, marker.letter),
                loc: loc.clone(),
            });
        }
    }
}

/// Sets in `mask` the lines of the `<silcrow>` block when `path` is an `AGENTS.md`.
fn mask_agents_block(path: &Path, text: &str, mask: &mut [bool]) {
    // § yymjgaqr0.e@2d183
    if path.file_name().and_then(|n| n.to_str()) != Some("AGENTS.md") {
        return;
    }
    let Some((start, end)) = crate::harness::block_range(text) else {
        return;
    };
    let first = text[..start].matches('\n').count();
    let last = text[..end].matches('\n').count();
    mask[first..=last].fill(true);
}

pub(crate) fn extract_mentions(path: &Path, text: &str, scan: &mut Scan) {
    // § mwneg21bd.c@dhqp5
    let lines: Vec<&str> = text.lines().collect();
    let mut fence = marker::fenced_lines(true, text);
    mask_agents_block(path, text, &mut fence);
    let mdx = marker::Dialect::of(path) == marker::Dialect::Mdx;
    for (idx, line) in lines.iter().enumerate() {
        let pointer = marker::is_pointer_line(line);
        let opened = line.trim_start();
        let comment = opened.starts_with("<!--") || (mdx && opened.starts_with("{/*"));
        if fence[idx] || !line.contains('§') || (pointer && comment) {
            continue;
        }
        let unquoted = mask_inline_code(line);
        // § szrkbrw70.b@hr68z
        for caps in QUALIFIED_RE.captures_iter(&unquoted) {
            let id = hash::normalise_id(&caps[2]);
            scan.mentions.push(Pointer {
                kind: PointerKind::Cite,
                project: Some(caps[1].to_string()),
                name: id.clone(),
                target: pointer_target(id, caps.get(3).map(|m| m.as_str().to_string())),
                loc: Location {
                    path: path.to_path_buf(),
                    line: idx + 1,
                },
            });
        }
        let prose = mask_re(&unquoted, &QUALIFIED_RE);
        for caps in MENTION_RE.captures_iter(&prose) {
            let id = hash::normalise_id(&caps[1]);
            scan.mentions.push(Pointer {
                kind: PointerKind::Cite,
                project: None,
                name: id.clone(),
                target: pointer_target(id, caps.get(2).map(|m| m.as_str().to_string())),
                loc: Location {
                    path: path.to_path_buf(),
                    line: idx + 1,
                },
            });
        }
    }
}

/// `text` with every marker, end and mention id, and every digest, in canonical form: what
/// `fix` writes for a pointer read through case or a Crockford homoglyph.
pub fn canonical_pointers(markdown: bool, text: &str) -> String {
    // § n71fgy5xw.b@vt3ep
    let fenced = marker::fenced_lines(markdown, text);
    let mut out = String::with_capacity(text.len());
    for (idx, line) in text.split_inclusive('\n').enumerate() {
        let bare = line.trim_end_matches(['\n', '\r']);
        let eol = &line[bare.len()..];
        if fenced[idx] {
            out.push_str(line);
            continue;
        }
        let canonical = marker::canonical_line(bare);
        if canonical != bare || !markdown || marker::is_pointer_line(bare) {
            out.push_str(&canonical);
            out.push_str(eol);
            continue;
        }
        let prose = mask_re(&mask_inline_code(bare), &QUALIFIED_RE);
        let mut fixed = bare.to_string();
        for caps in MENTION_RE.captures_iter(&prose) {
            let m = caps.get(1).expect("mention id");
            fixed.replace_range(m.range(), &hash::normalise_id(m.as_str()));
        }
        out.push_str(&fixed);
        out.push_str(eol);
    }
    out
}

fn pointer_target(id: String, letter: Option<String>) -> Target {
    Target::Stable { id, letter }
}

fn anchor_target(url: &str) -> Option<(String, Option<String>)> {
    // § h36xkjqaa.b@595c1
    let c = ANCHOR_RE.captures(url)?;
    Some((c[1].to_string(), c.get(2).map(|m| m.as_str().to_string())))
}

/// The fragment names the law. The letter of a clause is in the link text, `[id.c](note#id)`,
/// since a note has no anchor per letter. A link text `<projectpath>:<id>` names the project.
fn cite_target(text: &str, url: &str) -> Option<(Option<String>, String, Option<String>)> {
    // § nth5nbchz.a@t0a36
    let (id, letter) = anchor_target(url)?;
    let (project, text) = match CITE_TEXT_RE.captures(text.trim()) {
        Some(caps) if caps[2].starts_with(id.as_str()) => (
            Some(caps[1].to_string()),
            caps.get(2).map_or("", |m| m.as_str()),
        ),
        _ => (None, text.trim()),
    };
    if letter.is_some() {
        return Some((project, id, letter));
    }
    let named = text
        .strip_prefix(id.as_str())
        .and_then(|rest| rest.strip_prefix('.'))
        .filter(|l| !l.is_empty() && l.bytes().all(|b| b.is_ascii_lowercase()))
        .map(str::to_string);
    Some((project, id, named))
}

fn declare_ids(line: &str) -> Vec<String> {
    // § q3ckz9sm8.b@d815v
    if !line_opens_with_sign(line) {
        return Vec::new();
    }
    let searchable = mask_re(&mask_non_declare(line), &QUALIFIED_RE);
    let mut ids: Vec<String> = SIGN_RE
        .captures_iter(&searchable)
        .filter_map(|c| capture_id(&c))
        .collect();
    // § fxas3vhge.a@efh5h
    for caps in PROVISIONAL_DECLARE_RE.captures_iter(&searchable) {
        ids.push(format!("+{}", &caps[1]));
    }
    // § end fxas3vhge.a
    ids
}

fn mask_non_declare(line: &str) -> String {
    let mut s = mask_inline_code(line);
    s = mask_re(&s, &MD_LINK_RE);
    s
}

/// A paragraph that opens with a qualified marker adopts and declares nothing.
fn adopt(path: &Path, line: &str, idx: usize, scan: &mut Scan) -> bool {
    // § v8b14v6pn.a@74g8e
    if !QUALIFIED_OPEN_RE.is_match(line) {
        return false;
    }
    let loc = Location {
        path: path.to_path_buf(),
        line: idx + 1,
    };
    match ADOPT_RE.captures(line) {
        Some(caps) => scan.adoptions.push(Adoption {
            project: caps[1].to_string(),
            id: caps[2].to_string(),
            letter: caps.get(3).map(|m| m.as_str().to_string()),
            loc,
        }),
        None => scan.form_errors.push(FormError {
            loc,
            message: "a qualified marker adopts and carries no sentence: write `**§ <projectpath>:<id>**` alone on its paragraph".to_string(),
        }),
    }
    true
}

fn reject_stray_sign(path: &Path, line: &str, idx: usize, scan: &mut Scan) {
    // § q3ckz9sm8.b@53s42
    if line_opens_with_sign(line) {
        return;
    }
    let searchable = mask_non_declare(line);
    if SIGN_RE.is_match(&searchable)
        || PROVISIONAL_DECLARE_RE.is_match(&searchable)
        || QUALIFIED_RE.is_match(&searchable)
    {
        scan.form_errors.push(FormError {
            loc: Location {
                path: path.to_path_buf(),
                line: idx + 1,
            },
            message: "§ does not open a paragraph".to_string(),
        });
        return;
    }
    // § q3ckz9sm8.c@xbqae
    if parse_heading(line).is_some() && searchable.contains('§') {
        scan.form_errors.push(FormError {
            loc: Location {
                path: path.to_path_buf(),
                line: idx + 1,
            },
            message: "a heading never carries `§`: it is a boundary and binds nothing. Move the law to a paragraph of its own, or write the sign in backticks".to_string(),
        });
    }
    // § end q3ckz9sm8.c
}

pub(crate) fn rewrite_parse_form(body: &str) -> String {
    // § dvd9ggj68@mtcwr
    let lines: Vec<&str> = body.lines().collect();
    let fence = fence_mask(&lines);
    let mut out = Vec::with_capacity(lines.len().saturating_mul(2));
    for (i, line) in lines.iter().enumerate() {
        if fence[i] {
            out.push((*line).to_string());
            continue;
        }
        let (plain, marks) = unmark(line).unwrap_or_else(|| (line.to_string(), Marks::default()));
        // § wqhsnrn8a.g@dxym8
        let next = rewrite_clause_indent(&rewrite_carrying_bold(&plain));
        if letter_token(&next).is_some() {
            if let Some(prev) = out.last() {
                if !prev.is_empty() {
                    out.push(String::new());
                }
            }
        }
        // § end wqhsnrn8a.g
        out.push(remark(&next, marks));
    }
    let mut joined = out.join("\n");
    if body.ends_with('\n') {
        joined.push('\n');
    }
    joined
}

fn rewrite_carrying_bold(line: &str) -> String {
    // § q3ckz9sm8.a@w2pye
    if !line_opens_with_sign(line) || carrying_block(line).is_none() {
        return line.to_string();
    }
    if paragraph_carrying_is_bold(line) {
        return line.to_string();
    }
    let (indent, body) = split_indent(line);
    format!("{}**{}**", " ".repeat(indent), body.trim_end())
}

fn rewrite_clause_indent(line: &str) -> String {
    let Some((letter, rest)) = letter_token(line) else {
        return line.to_string();
    };
    let want = 2 * letter.len().saturating_sub(1);
    let item = if rest.is_empty() {
        format!("- ({letter})")
    } else {
        format!("- ({letter}) {rest}")
    };
    format!("{}{item}", " ".repeat(want))
}

fn paragraph_carrying_is_bold(raw: &str) -> bool {
    let t = raw.trim();
    (t.starts_with("**§") || t.starts_with("**(§")) && t.ends_with("**") && t.len() > 4
}

fn lint_duplicate_ids(scan: &mut Scan) {
    // § cmx8g7zp2.d@067at
    let mut anchors: HashMap<&str, &Law> = HashMap::new();
    let mut taken = Vec::new();
    for law in &scan.laws {
        for alias in &law.aliases {
            match anchors.get(alias.as_str()) {
                Some(first) if first.loc != law.loc => taken.push(FormError {
                    loc: law.loc.clone(),
                    message: format!(
                        "alias anchor `{alias}` is also kept by § {} at {}:{}: an alias anchor is a taken id",
                        first.id,
                        first.loc.path.display(),
                        first.loc.line
                    ),
                }),
                _ => {
                    anchors.insert(alias, law);
                }
            }
        }
    }
    for law in &scan.laws {
        if let Some(keeper) = anchors.get(law.id.as_str()).filter(|k| k.loc != law.loc) {
            taken.push(FormError {
                loc: law.loc.clone(),
                message: format!(
                    "§ {} is an alias anchor of § {} at {}:{}, so it names that law: an alias anchor is a taken id. Reword this carrying sentence and run `silcrow accept {}`",
                    law.id,
                    keeper.id,
                    keeper.loc.path.display(),
                    keeper.loc.line,
                    law.id
                ),
            });
        }
    }
    scan.form_errors.extend(taken);
    // § cmx8g7zp2.a@kbnz7
    let mut first: HashMap<String, Location> = HashMap::new();
    for law in &scan.laws {
        // § fxas3vhge.a@kcday
        if hash::is_provisional_id(&law.id) {
            continue;
        }
        // § end fxas3vhge.a
        if let Some(first_loc) = first.get(&law.id) {
            scan.form_errors.push(FormError {
                loc: law.loc.clone(),
                message: format!(
                    "duplicate id `{}` (first at {}:{})",
                    law.id,
                    first_loc.path.display(),
                    first_loc.line
                ),
            });
        } else {
            first.insert(law.id.clone(), law.loc.clone());
        }
    }
    // § end cmx8g7zp2.a
}

fn mask_re(text: &str, re: &Regex) -> String {
    let mut out = text.to_string();
    let spans: Vec<_> = re.find_iter(text).map(|m| (m.start(), m.end())).collect();
    for (start, end) in spans {
        out.replace_range(start..end, &" ".repeat(end - start));
    }
    out
}

/// `line` with each code span blanked byte for byte, its backticks included. A run of
/// backticks opens a span that the next run of the same length closes, as in markdown and as
/// the id canonicalisation reads it, so a double-backtick span may hold a single backtick. An
/// unclosed run is prose.
pub(crate) fn mask_inline_code(line: &str) -> String {
    // § nth5nbchz.c@73dyq
    let bytes = line.as_bytes();
    let run = |at: usize| bytes[at..].iter().take_while(|&&b| b == b'`').count();
    let mut out = String::with_capacity(line.len());
    let (mut prose, mut i) = (0, 0);
    while i < bytes.len() {
        if bytes[i] != b'`' {
            i += 1;
            continue;
        }
        let open = run(i);
        let mut j = i + open;
        let close = loop {
            if j >= bytes.len() {
                break None;
            }
            if bytes[j] != b'`' {
                j += 1;
                continue;
            }
            let n = run(j);
            if n == open {
                break Some(j + n);
            }
            j += n;
        };
        match close {
            Some(end) => {
                out.push_str(&line[prose..i]);
                out.push_str(&" ".repeat(end - i));
                prose = end;
                i = end;
            }
            None => i += open,
        }
    }
    out.push_str(&line[prose..]);
    out
}

fn capture_id(caps: &regex::Captures) -> Option<String> {
    for i in 1..=4 {
        if let Some(m) = caps.get(i) {
            return Some(m.as_str().to_string());
        }
    }
    None
}

fn parse_heading(line: &str) -> Option<(usize, String)> {
    let caps = HEADING_RE.captures(line.trim_end())?;
    Some((caps[1].len(), caps[2].to_string()))
}

fn parse_bullet(line: &str) -> Option<(usize, &str)> {
    let (indent, rest) = split_indent(line);
    for prefix in ["- ", "* ", "+ "] {
        if let Some(body) = rest.strip_prefix(prefix) {
            return Some((indent, body));
        }
    }
    let digits = rest.bytes().take_while(|b| b.is_ascii_digit()).count();
    if digits > 0 {
        if let Some(body) = rest.get(digits..)?.strip_prefix(". ") {
            return Some((indent, body));
        }
    }
    None
}

fn letter_token(line: &str) -> Option<(String, &str)> {
    // § wqhsnrn8a.a@rekxf
    let body = split_indent(line).1.strip_prefix("- ")?;
    let caps = LETTER_RE.captures(body)?;
    let letter = caps.get(1)?.as_str().to_string();
    let rest = body[caps.get(0)?.end()..].trim_start();
    Some((letter, rest))
}

fn split_indent(line: &str) -> (usize, &str) {
    let mut cols = 0;
    let mut bytes = 0;
    for (i, c) in line.char_indices() {
        match c {
            ' ' => {
                cols += 1;
                bytes = i + 1;
            }
            '\t' => {
                cols += 4;
                bytes = i + 1;
            }
            _ => break,
        }
    }
    (cols, &line[bytes..])
}

fn clean_body(s: &str) -> String {
    let unaliased = hash::strip_aliases(s);
    let stripped = SIGN_RE.replace_all(&unaliased, "");
    let collapsed = collapse_ws(&stripped.replace("~~", ""));
    let trimmed = collapsed.trim_matches(|c: char| c == '*' || c == '_');
    tidy_punct(&collapse_ws(trimmed))
}

fn tidy_punct(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    let chars: Vec<char> = s.chars().collect();
    for (i, c) in chars.iter().enumerate() {
        if *c == ' ' && i + 1 < chars.len() && ".,;:!?".contains(chars[i + 1]) {
            continue;
        }
        out.push(*c);
    }
    out
}

fn has_carrying_text(text: &str) -> bool {
    text.chars().any(|c| c.is_alphanumeric())
}

/// `(x) **Retired.**` is the burned letter on the default branch.
fn is_tombstone(body: &str) -> bool {
    // § mstqr8xqs.b@rjyaq
    body.trim() == "**Retired.**"
}

fn is_struck(s: &str) -> bool {
    // § zrj8yeg6g.a@wg2qq
    mask_inline_code(s).contains("~~")
}

fn collapse_ws(s: &str) -> String {
    s.split_whitespace().collect::<Vec<_>>().join(" ")
}

static HEAD_MARK_RE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(&format!(
        r#"^(\s*(?:\*\*)?\s*)(?:\(\s*§\s*<a\s+id="{ID}">{ID}</a>\s*\)|§[!?]{{0,2}}\s*<a\s+id="{ID}">{ID}</a>|\(\s*§\s*{ID}\s*\)|§[!?]{{0,2}}\s+{ID}\b|§[!?]{{0,2}}\s*\+[a-z0-9-]+)(?:\s*<a\s+id="{ID}"\s*></a>)*\s*"#
    ))
    .expect("head mark regex")
});

/// Which lines of a note sit inside a code fence, fence lines included.
pub(crate) fn fenced(text: &str) -> Vec<bool> {
    fence_mask(&text.lines().collect::<Vec<_>>())
}

/// A law head with its marker, its anchor, and its alias anchors taken out.
pub(crate) fn demark_head(line: &str) -> String {
    HEAD_MARK_RE.replace(line, "${1}").into_owned()
}

/// A note line with each cite link replaced by its text, outside inline code, as
/// `extract_pointers` reads them.
pub(crate) fn uncite(line: &str) -> String {
    // Masked byte for byte, unlike `mask_inline_code`, so a match offset is an offset of `line`.
    let mut masked = String::with_capacity(line.len());
    let mut in_code = false;
    for c in line.chars() {
        if c == '`' {
            in_code = !in_code;
        }
        if in_code || c == '`' {
            masked.extend(std::iter::repeat_n(' ', c.len_utf8()));
        } else {
            masked.push(c);
        }
    }
    let mut spans: Vec<(usize, usize, String)> = Vec::new();
    for m in MD_LINK_RE.find_iter(&masked) {
        let Some(caps) = MD_LINK_RE.captures(&line[m.start()..m.end()]) else {
            continue;
        };
        if cite_target(&caps[1], &caps[2]).is_some() {
            spans.push((m.start(), m.end(), caps[1].to_string()));
        }
    }
    if spans.is_empty() {
        return line.to_string();
    }
    spans.sort();
    let mut out = String::with_capacity(line.len());
    let mut at = 0;
    for (start, end, text) in spans {
        if start < at {
            continue;
        }
        out.push_str(&line[at..start]);
        out.push_str(&text);
        at = end;
    }
    out.push_str(&line[at..]);
    out
}

/// A line that holds nothing but references: once every cite link and `§` mention is taken
/// out, no letter or digit is left. Inline code counts as content.
pub(crate) fn is_reference_only(line: &str) -> bool {
    if line.contains('`') {
        return false;
    }
    let unlinked = MD_LINK_RE.replace_all(line, |caps: &regex::Captures<'_>| {
        if cite_target(&caps[1], &caps[2]).is_some() {
            String::new()
        } else {
            caps[0].to_string()
        }
    });
    let rest = QUALIFIED_RE.replace_all(&unlinked, "");
    let rest = MENTION_RE.replace_all(&rest, "");
    !rest.chars().any(char::is_alphanumeric)
}

pub(crate) fn display_path(path: &Path, root: &Path) -> String {
    path.strip_prefix(root)
        .unwrap_or(path)
        .to_string_lossy()
        .replace('\\', "/")
}

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

    #[test]
    fn a_decision_note_with_an_html_comment_is_a_defect() {
        let note = "# N\n\n<!-- a plain html comment -->\n\nProse <!-- inline --> here, `<!-- quoted -->` not.\n\n```\n<!-- fenced -->\n```\n";
        let scan = scan_text(Path::new("docs/decisions/n.md"), note);
        let lines: Vec<usize> = scan
            .form_errors
            .iter()
            .filter(|e| e.message.contains("HTML comment"))
            .map(|e| e.loc.line)
            .collect();
        assert_eq!(lines, vec![3, 5]);
    }

    #[test]
    fn a_struck_clause_a_tombstone_or_an_alias_anchor_no_law_holds_is_a_leftover() {
        let s = scan("# N\n\n<a id=\"abcdefgh9\"></a>\n\n- (b) **Retired.**\n\n- (c) ~~Gone.~~\n\n- (d) Context.\n\n**§ <a id=\"abcdefgh1\">abcdefgh1</a><a id=\"abcdefgh2\"></a> Kept.**\n\n- (a) ~~Struck.~~\n\n- (b) **Retired.**\n\n```\n- (e) ~~Fenced.~~\n```\n");
        let lines: Vec<usize> = s.form_errors.iter().map(|e| e.loc.line).collect();
        assert_eq!(lines, [3, 5, 7, 9], "{:?}", s.form_errors);
        assert!(s.form_errors[0].message.contains("alias anchor"));
        assert!(s.form_errors[1].message.contains("tombstone"));
        assert!(s.form_errors[3].message.contains("attaches to no law"));
    }

    #[test]
    fn a_clause_item_a_heading_cuts_from_its_head_fails() {
        let s = scan("# N\n\n**§ abcdefgh1 Kept.**\n\n## Inserted\n\n- (a) First.\n\n- (b) Second.\n\n**§ abcdefgh2 Other.**\n\n- (a) Held.\n");
        let lines: Vec<usize> = s.form_errors.iter().map(|e| e.loc.line).collect();
        assert_eq!(lines, [7, 9], "{:?}", s.form_errors);
        assert!(s.laws[0].clauses.is_empty());
        assert_eq!(
            letters_of(&Scan {
                laws: s.laws[1..].to_vec(),
                ..Scan::default()
            }),
            ["a"]
        );
    }

    #[test]
    fn a_duplicate_letter_is_reported_once() {
        let s = scan("**§ abcdefgh1 Kept.**\n\n- (a) One.\n\n- (a) Again.\n");
        assert_eq!(s.form_errors.len(), 1, "{:?}", s.form_errors);
    }

    #[test]
    fn a_heading_never_carries_the_sign() {
        let s = scan("# N\n\n## § Heading words\n\n## The `§` sign\n");
        let lines: Vec<usize> = s.form_errors.iter().map(|e| e.loc.line).collect();
        assert_eq!(lines, [3], "{:?}", s.form_errors);
        assert!(s.form_errors[0].message.contains("heading never carries"));
    }

    #[test]
    fn a_single_letter_after_a_later_one_warns() {
        let s = scan("**§ abcdefgh1 Kept.**\n\n- (a) One.\n\n- (c) Three.\n\n- (ca) Narrow.\n\n- (b) Two.\n\n- (d) Four.\n");
        let lines: Vec<usize> = s.lints.iter().map(|l| l.loc.line).collect();
        assert_eq!(lines, [9], "{:?}", s.lints);
        assert!(s.lints[0]
            .message
            .contains("(b) of § abcdefgh1 is written after (c)"));
        assert!(s.form_errors.is_empty(), "{:?}", s.form_errors);
    }

    #[test]
    fn an_id_an_alias_anchor_keeps_is_taken() {
        let s = scan_notes(&[(
            PathBuf::from("docs/decisions/t.md"),
            "**§ <a id=\"abcdefgh1\">abcdefgh1</a><a id=\"abcdefgh2\"></a> Kept.**\n\n**§ <a id=\"abcdefgh2\">abcdefgh2</a> Again.**\n\n**§ <a id=\"abcdefgh3\">abcdefgh3</a><a id=\"abcdefgh2\"></a> Third.**\n".to_string(),
        )]);
        let found: Vec<(usize, bool)> = s
            .form_errors
            .iter()
            .map(|e| (e.loc.line, e.message.contains("taken id")))
            .collect();
        assert_eq!(found, [(5, true), (3, true)], "{:?}", s.form_errors);
    }

    #[test]
    fn a_line_of_references_alone_holds_no_word() {
        assert!(is_reference_only("- § abcdefgh1"));
        assert!(is_reference_only("- [lib:abcdefgh1](../n.md#abcdefgh1)."));
        assert!(!is_reference_only(
            "See [abcdefgh1](n.md#abcdefgh1) for history."
        ));
        assert!(!is_reference_only("- § abcdefgh1 `code`"));
        assert!(!is_reference_only("- [a page](guide.md)"));
    }

    #[test]
    fn a_fenced_doc_marker_is_not_a_marker() {
        let text = "Prose.\n```\n<!-- § abcdefgh1.a -->\n```\n<!-- § abcdefgh2 -->\n";
        let mut scan = Scan::default();
        extract_markers(Path::new("docs/guide.md"), text, &mut scan);
        let ids: Vec<_> = scan.pointers.iter().map(|p| p.name.as_str()).collect();
        assert_eq!(ids, ["abcdefgh2"]);
    }

    #[test]
    fn an_indented_code_block_holds_no_marker_or_mention() {
        let text = "Prose.\n\n    <!-- § abcdefgh1.a -->\n    see § abcdefgh3\n\n- item\n\n    <!-- § abcdefgh2 -->\n";
        let mut scan = Scan::default();
        extract_markers(Path::new("docs/guide.md"), text, &mut scan);
        extract_mentions(Path::new("docs/guide.md"), text, &mut scan);
        let ids: Vec<_> = scan.pointers.iter().map(|p| p.name.as_str()).collect();
        assert_eq!(ids, ["abcdefgh2"]);
        assert!(scan.mentions.is_empty(), "{:?}", scan.mentions);
    }

    #[test]
    fn the_agents_md_block_holds_no_mention_or_cite() {
        let text = "<silcrow notes=\"docs/decisions/**/*.md\">\n- Locality: see § abcdefgh1 and [abcdefgh2](docs/decisions/n.md#abcdefgh2).\n</silcrow>\n\nSee § abcdefgh3 and [abcdefgh4](docs/decisions/n.md#abcdefgh4).\n";
        let mut scan = Scan::default();
        extract_mentions(Path::new("AGENTS.md"), text, &mut scan);
        extract_doc_cites(Path::new("AGENTS.md"), text, &mut scan);
        let mentions: Vec<_> = scan.mentions.iter().map(|p| p.name.as_str()).collect();
        let cites: Vec<_> = scan.pointers.iter().map(|p| p.name.as_str()).collect();
        assert_eq!(mentions, ["abcdefgh3"]);
        assert_eq!(cites, ["abcdefgh4"]);
        let mut scan = Scan::default();
        extract_mentions(Path::new("docs/guide.md"), text, &mut scan);
        extract_doc_cites(Path::new("docs/guide.md"), text, &mut scan);
        assert_eq!(scan.mentions.len(), 2, "{:?}", scan.mentions);
        assert_eq!(scan.pointers.len(), 2, "{:?}", scan.pointers);
    }

    #[test]
    fn relative_cite_reads_the_letter_from_the_link_text() {
        let s = scan("# N\n\nSee [abcdefgh1.c](verbs.md#abcdefgh1) and [abcdefgh2](#abcdefgh2).\n");
        let targets: Vec<_> = s.pointers.iter().map(|p| p.target.clone()).collect();
        assert_eq!(
            targets,
            vec![
                Target::Stable {
                    id: "abcdefgh1".into(),
                    letter: Some("c".into())
                },
                Target::Stable {
                    id: "abcdefgh2".into(),
                    letter: None
                },
            ]
        );
    }

    fn scan(md: &str) -> Scan {
        let mut scan = Scan::default();
        parse_note_text(Path::new("docs/decisions/t.md"), md, &mut scan);
        scan
    }

    fn letters_of(s: &Scan) -> Vec<&str> {
        s.laws[0]
            .clauses
            .iter()
            .filter_map(|a| a.letter.as_deref())
            .collect()
    }

    #[test]
    fn a_mention_inside_a_double_backtick_span_is_code() {
        let mut s = Scan::default();
        extract_mentions(
            Path::new("README.md"),
            "Write `` `§ abcdefgh1` `` or ``§ abcdefgh2``, read § abcdefgh3 and `x` § abcdefgh4.\n",
            &mut s,
        );
        let named: Vec<&str> = s.mentions.iter().map(|m| m.name.as_str()).collect();
        assert_eq!(named, ["abcdefgh3", "abcdefgh4"]);
        assert_eq!(mask_inline_code("a ``b`c`` d").len(), "a ``b`c`` d".len());
    }

    #[test]
    fn a_single_letter_gap_without_a_tombstone_warns() {
        let s = scan("**§ abcdefgh1 Law.**\n\n- (a) One.\n\n- (c) Three.\n\n  - (ca) Nested.\n");
        let messages: Vec<&str> = s.lints.iter().map(|l| l.message.as_str()).collect();
        assert_eq!(messages.len(), 1, "{messages:?}");
        assert!(messages[0].starts_with("§ abcdefgh1 writes (c) and not (b)"));
        let s =
            scan("**§ abcdefgh1 Law.**\n\n- (a) ~~One.~~\n\n- (b) **Retired.**\n\n- (c) Three.\n");
        assert!(s.lints.is_empty(), "{:?}", s.lints);
    }

    #[test]
    fn lettered_clauses_are_detected() {
        let s = scan(
            "## Title\n\n**§ abcdefgh1 First idea.**\n- (a) First idea.\n- (b) Second idea.\n",
        );
        assert_eq!(s.form_errors.len(), 0);
        assert_eq!(s.laws.len(), 1);
        assert_eq!(letters_of(&s), ["a", "b"]);
        assert!(s.laws[0].clauses[0].text.contains("First idea"));
        assert!(s.laws[0].clauses[1].text.contains("Second idea"));
    }

    #[test]
    fn unlettered_siblings_are_context() {
        let s = scan(
            "## Title\n\n**§ abcdefgh1 Binding sentence.**\n- (a) Binding sentence.\n- plain context\n  - (aa) nested letter.\n",
        );
        assert_eq!(s.form_errors.len(), 0);
        assert_eq!(letters_of(&s), ["a", "aa"]);
    }

    #[test]
    fn duplicate_letter_is_form_error() {
        let s = scan(
            "## Title\n\n**§ abcdefgh1 First.**\n- (a) First.\n- (a) Duplicate.\n- (b) Other.\n",
        );
        assert!(s.form_errors.iter().any(|e| e
            .message
            .contains("duplicate clause letter (a) for § abcdefgh1")));
        assert_eq!(letters_of(&s), ["a", "b"]);
    }

    #[test]
    fn compound_letter_sorts_between_a_and_b() {
        let s = scan(
            "## Title\n\n**§ abcdefgh1 First.**\n- (a) First.\n- (aa) Compound.\n- (b) Second.\n",
        );
        let mut letters = letters_of(&s);
        letters.sort();
        assert_eq!(letters, ["a", "aa", "b"]);
    }

    #[test]
    fn letter_and_trailing_marker_do_not_declare() {
        let s = scan("## Title\n\n(a) The workload fails open (§ abcdefgh1).\n");
        assert_eq!(s.laws.len(), 0);
        assert!(s
            .form_errors
            .iter()
            .any(|e| e.message.contains("does not open a paragraph")));
    }

    #[test]
    fn section_sign_line_without_letter_has_zero_clauses() {
        let s = scan("## Title\n\n**§ abcdefgh1 The workload fails open.**\n");
        assert_eq!(s.form_errors.len(), 0);
        assert_eq!(s.laws.len(), 1);
        assert_eq!(s.laws[0].id, "abcdefgh1");
        assert!(s.laws[0].clauses.is_empty());
    }

    #[test]
    fn multiple_laws_in_one_section_carry_their_own_text() {
        let s = scan(
            "## Section A\n\n**§ abcdefgh1 First law here.**\n**§ abcdefgh2 Second law here.**\n",
        );
        assert_eq!(s.form_errors.len(), 0);
        assert_eq!(s.laws.len(), 2);
        assert_eq!(s.laws[0].id, "abcdefgh1");
        assert!(s.laws[0].name.contains("First law here"));
        assert_eq!(s.laws[1].id, "abcdefgh2");
        assert!(s.laws[1].name.contains("Second law here"));
    }

    #[test]
    fn section_sign_in_heading_does_not_declare() {
        let s = scan("## Runtime without us § abcdefgh1\n\n(a) fails open.\n");
        assert_eq!(s.laws.len(), 0);
        assert!(s
            .form_errors
            .iter()
            .any(|e| e.message.contains("does not open a paragraph")));
    }

    #[test]
    fn document_without_titles_compiles() {
        let s = scan("**§ abcdefgh1 First law here.**\n**§ abcdefgh2 Second law here.**\n");
        assert_eq!(s.form_errors.len(), 0);
        assert_eq!(s.laws.len(), 2);
        assert!(s.laws[0].name.contains("First law here"));
        assert!(s.laws[1].name.contains("Second law here"));
    }

    #[test]
    fn two_markers_in_one_section_make_two_laws() {
        let s = scan("## Title\n\n**§ abcdefgh1 First.**\n**§ abcdefgh2 Second.**\n");
        assert_eq!(s.form_errors.len(), 0);
        assert_eq!(s.laws.len(), 2);
        assert_eq!(s.laws[0].id, "abcdefgh1");
        assert_eq!(s.laws[1].id, "abcdefgh2");
    }

    #[test]
    fn fenced_section_sign_is_ignored() {
        let s = scan(
            "## Title\n\n```\n§ abcdefgh1\n```\n\n**§ abcdefgh2 Real law.**\n- (a) Real law.\n",
        );
        assert_eq!(s.form_errors.len(), 0);
        assert_eq!(s.laws.len(), 1);
        assert_eq!(s.laws[0].id, "abcdefgh2");
        assert_eq!(s.laws[0].clauses[0].letter.as_deref(), Some("a"));
    }

    #[test]
    fn code_marker_marker_is_implements_pointer() {
        let mut scan = Scan::default();
        extract_markers(
            Path::new("src/foo.rs"),
            "// § abcdefgh1\nfn main() {}\n",
            &mut scan,
        );
        assert_eq!(scan.pointers.len(), 1);
        assert_eq!(scan.pointers[0].kind, PointerKind::Implements);
        match &scan.pointers[0].target {
            Target::Stable { id, letter } => {
                assert_eq!(id, "abcdefgh1");
                assert!(letter.is_none());
            }
            _ => panic!("expected stable target"),
        }
    }

    #[test]
    fn clause_marker_resolves_to_letter() {
        let mut scan = Scan::default();
        extract_markers(Path::new("src/foo.rs"), "// § abcdefgh1.a\n", &mut scan);
        assert_eq!(scan.pointers.len(), 1);
        match &scan.pointers[0].target {
            Target::Stable { id, letter } => {
                assert_eq!(id, "abcdefgh1");
                assert_eq!(letter.as_deref(), Some("a"));
            }
            _ => panic!("expected stable target"),
        }
    }

    #[test]
    fn provisional_declare_is_detected() {
        let s = scan("## Title\n\n**§ +runtime The graph fails open.**\n");
        assert_eq!(s.form_errors.len(), 0);
        assert_eq!(s.laws.len(), 1);
        assert_eq!(s.laws[0].id, "+runtime");
    }

    #[test]
    fn invalid_crockford_id_is_rejected() {
        let s = scan("## Title\n\n**§ abciefgh1 Bad id.**\n");
        assert!(s
            .form_errors
            .iter()
            .any(|e| e.message.contains("Crockford")));
        assert_eq!(s.laws.len(), 0);
    }

    #[test]
    fn doc_html_marker_is_implements_pointer() {
        let mut scan = Scan::default();
        extract_markers(
            Path::new("docs/guide.md"),
            "Some prose.\n<!-- § abcdefgh1 -->\n",
            &mut scan,
        );
        assert_eq!(scan.pointers.len(), 1);
        assert_eq!(scan.pointers[0].kind, PointerKind::Implements);
        match &scan.pointers[0].target {
            Target::Stable { id, letter } => {
                assert_eq!(id, "abcdefgh1");
                assert!(letter.is_none());
            }
            _ => panic!("expected stable target"),
        }
    }

    #[test]
    fn amends_line_is_a_form_error() {
        let md = "## Law\n\n**§ abcdefgh1 Binding sentence.**\n\n## Amendment\n\nAmends § abcdefgh1\n(g) Exported report must carry the retention date.\n";
        let s = scan(md);
        assert!(s
            .form_errors
            .iter()
            .any(|e| e.message.contains("§ does not open a paragraph")));
        assert!(s.laws[0].clauses.is_empty());
    }

    #[test]
    fn bare_floating_marker_is_form_error_not_duplicate_lint() {
        let s = scan("## Title\n\n§ abcdefgh1\n");
        assert!(s
            .form_errors
            .iter()
            .any(|e| e.message.contains("no determinable carrying block")));
        assert!(!s
            .lints
            .iter()
            .any(|l| l.message.contains("no carrying sentence")));
    }

    #[test]
    fn paragraph_law_without_bold_still_declares() {
        let s = scan("## Title\n\n§ abcdefgh1 A binding sentence.\n");
        assert_eq!(s.form_errors.len(), 0);
        assert_eq!(s.laws.len(), 1);
        assert_eq!(s.laws[0].id, "abcdefgh1");
    }

    #[test]
    fn paragraph_law_with_bold_declares() {
        let s = scan("## Title\n\n**§ abcdefgh1 A binding sentence.**\n");
        assert_eq!(s.form_errors.len(), 0);
        assert_eq!(s.laws.len(), 1);
    }

    #[test]
    fn heading_and_trailing_markers_are_form_errors() {
        let s = scan("## Runtime without us § abcdefgh1\n\n(a) fails open (§ abcdefgh2).\n");
        assert_eq!(s.laws.len(), 0);
        assert!(s
            .form_errors
            .iter()
            .any(|e| e.message.contains("does not open a paragraph")));
    }

    #[test]
    fn rewrite_wraps_paragraph_bold() {
        let out = rewrite_parse_form("§ abcdefgh1 A binding sentence.\n");
        assert_eq!(out, "**§ abcdefgh1 A binding sentence.**\n");
    }

    #[test]
    fn rewrite_indents_compound_clause() {
        let out = rewrite_parse_form(
            "**§ abcdefgh1 First.**\n- (a) First.\n- (aa) Compound.\n- (b) Second.\n",
        );
        assert_eq!(
            out,
            "**§ abcdefgh1 First.**\n\n- (a) First.\n\n  - (aa) Compound.\n\n- (b) Second.\n"
        );
    }

    #[test]
    fn lettered_line_outside_a_dash_item_is_form_error() {
        for text in [
            "## T\n\n**§ abcdefgh1 First.**\n\n(a) Prose that opens with a letter.\n",
            "## T\n\n**§ abcdefgh1 First.**\n\n* (a) Other bullet.\n",
        ] {
            let s = scan(text);
            assert!(letters_of(&s).is_empty());
            assert!(
                s.form_errors
                    .iter()
                    .any(|e| e.message.contains("write `- (a)`")),
                "{:?}",
                s.form_errors
            );
        }
    }

    #[test]
    fn attached_table_and_fence_belong_to_the_clause() {
        let s = scan(
            "## T\n\n**§ abcdefgh1 First.**\n\n- (a) Flow:\n\n```mermaid\nA --> B\n```\n\n| k | v |\n| - | - |\n| x | y |\n\nFree prose.\n\n```\nnot attached\n```\n\n- (b) Second.\n",
        );
        assert_eq!(s.form_errors.len(), 0, "{:?}", s.form_errors);
        let a = &s.laws[0].clauses[0];
        assert!(a.body.contains("A --> B"));
        assert!(a.body.contains("| x | y |"));
        assert!(!a.body.contains("Free prose"));
        assert!(!a.body.contains("not attached"));
        assert_eq!(s.laws[0].clauses[1].body, "Second.");
    }

    #[test]
    fn lines_under_a_head_bind_its_law_grain_pin() {
        let s = scan(
            "## T\n\n**§ abcdefgh1 First.**\nStill the head paragraph.\n\n  An indented line.\n\nFree prose.\n\n- (a) Letter.\n",
        );
        assert_eq!(s.form_errors.len(), 0, "{:?}", s.form_errors);
        let law = &s.laws[0];
        assert!(
            law.body.contains("Still the head paragraph."),
            "{}",
            law.body
        );
        assert!(law.body.contains("An indented line."), "{}", law.body);
        assert!(!law.body.contains("Free prose"), "{}", law.body);
        assert_eq!(letters_of(&s), ["a"]);
    }

    #[test]
    fn lettered_table_rows_under_a_head_are_clauses() {
        let s = scan(
            "## T\n\n**§ abcdefgh1 Events.**\n\n| Event | Effect |\n| --- | --- |\n| (a) Declared | minted |\n| (b) Edited | remints |\n\n- (c) After.\n",
        );
        assert_eq!(s.form_errors.len(), 0, "{:?}", s.form_errors);
        assert_eq!(letters_of(&s), ["a", "b", "c"]);
        assert!(s.laws[0].clauses[1].body.contains("remints"));
        assert!(s.laws[0].body.contains("| Event | Effect |"));
    }

    /// The text of a row clause, which `diff` recalls under its header, keeps its letter cell,
    /// so the row has as many cells as the header. Its pinned body does not change.
    #[test]
    fn a_row_clause_keeps_its_letter_cell_in_its_text() {
        let s = scan(
            "## T\n\n**§ abcdefgh1 Bounds.**\n\n| Case | Upper bound |\n| --- | --- |\n| (a) | small is 10 |\n| (b) big | is 100 |\n",
        );
        assert_eq!(s.form_errors.len(), 0, "{:?}", s.form_errors);
        let cells = |row: &str| row.matches('|').count();
        let [a, b] = &s.laws[0].clauses[..] else {
            panic!("two row clauses");
        };
        assert_eq!(a.text, "| (a) | small is 10 |");
        assert_eq!(b.text, "| (b) big | is 100 |");
        for clause in [a, b] {
            assert_eq!(cells(&clause.text), cells("| Case | Upper bound |"));
        }
        assert_eq!(a.body, "| small is 10 |");
        assert_eq!(b.body, "big | is 100 |");
    }

    #[test]
    fn lettered_rows_inside_a_clause_are_labels() {
        let s = scan(
            "## T\n\n**§ abcdefgh1 Events.**\n\n- (a) The table:\n\n| (a) Declared | minted |\n| (b) Edited | remints |\n",
        );
        assert_eq!(s.form_errors.len(), 0, "{:?}", s.form_errors);
        assert_eq!(letters_of(&s), ["a"]);
        assert!(s.laws[0].clauses[0].body.contains("(b) Edited"));
    }

    #[test]
    fn remote_retire_is_form_error() {
        let s = scan("## T\n\n**Retire § abcdefgh1.**\n");
        assert!(s
            .form_errors
            .iter()
            .any(|e| e.message.contains("§ does not open a paragraph")));
    }

    #[test]
    fn compound_without_parent_is_form_error() {
        let s = scan("**§ abcdefgh1 First.**\n- (aa) Orphan.\n");
        assert!(s.form_errors.iter().any(|e| e
            .message
            .contains("compound clause (aa) for § abcdefgh1 has no parent (a)")));
        assert!(s.laws[0].clauses.is_empty());
    }

    #[test]
    fn a_table_row_compound_without_parent_is_form_error() {
        let s = scan("**§ abcdefgh1 First.**\n\n| Row | Rule |\n| --- | --- |\n| (aa) Orphan | x |\n| (b) Next | y |\n");
        assert!(
            s.form_errors.iter().any(|e| e
                .message
                .contains("compound clause (aa) for § abcdefgh1 has no parent (a)")),
            "{:?}",
            s.form_errors
        );
        let letters: Vec<_> = s.laws[0]
            .clauses
            .iter()
            .filter_map(|c| c.letter.clone())
            .collect();
        assert_eq!(letters, vec!["b".to_string()]);
    }

    #[test]
    fn a_misformed_clause_item_is_reported() {
        for line in [
            "-  (b) Two spaces.",
            "-\t(d) A tab.",
            "1) (c) Numbered.",
            "*   (e) Star.",
        ] {
            let s = scan(&format!("**§ abcdefgh1 First.**\n\n- (a) One.\n\n{line}\n"));
            assert!(
                s.form_errors
                    .iter()
                    .any(|e| e.message.contains("opens a line but is not a clause")),
                "{line}: {:?}",
                s.form_errors
            );
        }
    }

    #[test]
    fn compound_before_parent_is_form_error() {
        let s = scan("**§ abcdefgh1 First.**\n- (aa) Early.\n- (a) Parent.\n");
        assert!(s.form_errors.iter().any(|e| e
            .message
            .contains("compound clause (aa) for § abcdefgh1 has no parent (a)")));
    }

    #[test]
    fn fence_after_clause_does_not_declare_or_drop_next() {
        let s = scan("**§ abcdefgh1 First.**\n- (a) Parent.\n```\n§ xyzzzzzz1\n```\n- (b) Next.\n");
        assert_eq!(s.form_errors.len(), 0);
        assert_eq!(s.laws.len(), 1);
        assert_eq!(letters_of(&s), ["a", "b"]);
        assert!(s.laws.iter().all(|law| law.id != "xyzzzzzz1"));
    }

    #[test]
    fn struck_carrying_sentence_withdraws() {
        let s = scan("**§ abcdefgh1 ~~A withdrawn sentence.~~**\n");
        assert_eq!(s.form_errors.len(), 0);
        assert_eq!(s.laws.len(), 1);
        assert!(s.laws[0].struck);
    }

    #[test]
    fn retired_tombstone_is_dead() {
        let s = scan("**§ abcdefgh1 A law.**\n\n- (a) **Retired.**\n\n- (b) Live.\n");
        assert!(s.laws[0].clauses[0].struck);
        assert!(!s.laws[0].clauses[1].struck);
    }

    #[test]
    fn tilde_pair_in_code_span_is_not_a_strike() {
        let s = scan("**§ abcdefgh1 A law.**\n\n- (a) The form is `~~<sentence>~~` on the line.\n");
        assert!(!s.laws[0].struck);
        assert!(!s.laws[0].clauses[0].struck);
    }

    #[test]
    fn qualified_cite_names_its_project() {
        let s = scan("# N\n\nSee [packages/billing:7k2m9x1ab.a](../../packages/billing/docs/decisions/x.md#7k2m9x1ab) and [7k2m9x1ac](#7k2m9x1ac).\n");
        assert_eq!(s.form_errors, vec![]);
        let got: Vec<_> = s
            .pointers
            .iter()
            .map(|p| (p.project.clone(), p.target.clone()))
            .collect();
        assert_eq!(
            got,
            vec![
                (
                    Some("packages/billing".to_string()),
                    Target::Stable {
                        id: "7k2m9x1ab".into(),
                        letter: Some("a".into())
                    }
                ),
                (
                    None,
                    Target::Stable {
                        id: "7k2m9x1ac".into(),
                        letter: None
                    }
                ),
            ]
        );
    }

    #[test]
    fn a_sign_in_parentheses_in_prose_is_a_stray_sign() {
        for reference in ["(§ abcdefgh2)", "(§ packages/billing:abcdefgh2)"] {
            let s = scan(&format!(
                "# N\n\n**§ abcdefgh1 Rule.**\n\n- (a) One *builds on {reference}*.\n\n*builds on {reference}*, more.\n"
            ));
            let lines: Vec<usize> = s.form_errors.iter().map(|e| e.loc.line).collect();
            assert_eq!(lines, [5, 7], "{reference}: {:?}", s.form_errors);
            assert!(s.pointers.is_empty(), "{reference}");
        }
    }

    #[test]
    fn qualified_marker_names_its_project() {
        let mut scan = Scan::default();
        extract_markers(
            Path::new("src/foo.rs"),
            "// § packages/billing:7k2m9x1ab.a@k3n7q\n<!-- § .:7k2m9x1ab -->\n",
            &mut scan,
        );
        let projects: Vec<_> = scan.pointers.iter().map(|p| p.project.as_deref()).collect();
        assert_eq!(projects, vec![Some("packages/billing"), Some(".")]);
    }

    #[test]
    fn a_bare_qualified_paragraph_adopts() {
        let s = scan("## T\n\n**§ packages/billing:7k2m9x1ab**\n\n**§ .:7k2m9x1ac.b**\n");
        assert_eq!(s.form_errors, vec![]);
        assert!(s.laws.is_empty());
        let got: Vec<_> = s
            .adoptions
            .iter()
            .map(|a| (a.project.as_str(), a.id.as_str(), a.letter.as_deref()))
            .collect();
        assert_eq!(
            got,
            vec![
                ("packages/billing", "7k2m9x1ab", None),
                (".", "7k2m9x1ac", Some("b"))
            ]
        );
    }

    #[test]
    fn a_qualified_marker_with_a_sentence_is_a_form_error() {
        let s = scan("**§ billingxx:7k2m9x1ab Some sentence.**\n");
        assert!(s.laws.is_empty());
        assert!(s.adoptions.is_empty());
        assert!(s
            .form_errors
            .iter()
            .any(|e| e.message.contains("carries no sentence")));
    }

    #[test]
    fn a_qualified_marker_in_prose_is_stray() {
        let s = scan("**§ abcdefgh1 A law.**\n\nSee § packages/billing:7k2m9x1ab here.\n");
        assert!(s
            .form_errors
            .iter()
            .any(|e| e.message.contains("does not open a paragraph")));
    }

    #[test]
    fn duplicate_ids_across_notes_are_linted() {
        let mut scan = Scan::default();
        parse_note_text(
            Path::new("docs/decisions/a.md"),
            "**§ abcdefgh1 First law.**\n",
            &mut scan,
        );
        parse_note_text(
            Path::new("docs/decisions/b.md"),
            "**§ abcdefgh1 Second law.**\n",
            &mut scan,
        );
        lint_duplicate_ids(&mut scan);
        assert!(scan
            .form_errors
            .iter()
            .any(|e| e.message.contains("duplicate id `abcdefgh1`")));
    }

    #[test]
    fn a_draft_head_or_clause_reads_as_the_law_written_without_its_mark() {
        let plain = "## T\n\n**§ <a id=\"abcdefgh1\">abcdefgh1</a> A rule holds.**\n\n- (a) One.\n\n  - (aa) Narrowed.\n\n- (b) Two.\n";
        let draft = "## T\n\n**§? <a id=\"abcdefgh1\">abcdefgh1</a> A rule holds.**\n\n- (a)? One.\n\n  - (aa)? Narrowed.\n\n- (b) Two.\n";
        let (p, d) = (scan(plain), scan(draft));
        assert!(d.form_errors.is_empty(), "{:?}", d.form_errors);
        let (pl, dl) = (&p.laws[0], &d.laws[0]);
        assert!(dl.draft && !pl.draft);
        assert!(
            dl.clauses.iter().all(|c| c.draft),
            "a clause of a draft law is a draft"
        );
        let undrafted = |law: &Law| Law {
            draft: false,
            clauses: law
                .clauses
                .iter()
                .map(|c| Clause {
                    draft: false,
                    ..c.clone()
                })
                .collect(),
            ..law.clone()
        };
        assert_eq!(undrafted(dl), undrafted(pl));
    }

    #[test]
    fn a_draft_clause_of_a_law_that_is_none_is_a_draft_alone() {
        let s = scan("**§ abcdefgh1 Rule.**\n\n- (a) One.\n\n- (b)? Two.\n\n- (+)? Three.\n");
        let law = &s.laws[0];
        assert!(!law.draft);
        let drafts: Vec<(&str, bool)> = law
            .clauses
            .iter()
            .map(|c| (c.letter.as_deref().unwrap(), c.draft))
            .collect();
        assert_eq!(drafts, [("a", false), ("b", true)]);
        assert!(s
            .form_errors
            .iter()
            .any(|e| names_provisional_letter(&e.message)));
    }

    #[test]
    fn a_question_mark_anywhere_else_is_text() {
        let note = "**§ abcdefgh1 Does it hold? It does.**\n\n- (a) Why? Because.\n\n- Is (b)? a label.\n\n  `- (c)? quoted`\n\n```\n**§? abcdefgh2 Fenced.**\n- (d)? Fenced.\n```\n\nProse §? and (e)? stay.\n\n- (f)?Glued.\n";
        let s = scan(note);
        assert_eq!(s.laws.len(), 1);
        let law = &s.laws[0];
        assert_eq!(law.name, "Does it hold? It does.");
        assert!(!law.draft);
        assert_eq!(letters_of(&s), ["a"]);
        assert_eq!(law.clauses[0].text, "Why? Because.");
        assert!(!law.clauses[0].draft);
        assert!(law.body.is_empty() || !law.body.contains("(d)"));
        assert_eq!(undraft("Prose §? and (e)? stay."), None);
        assert_eq!(undraft("**§? not a head**"), None);
        assert_eq!(undraft("- (f)?Glued."), None);
    }

    #[test]
    fn a_public_mark_reads_beside_the_draft_mark_and_neither_is_hashed() {
        let scan = |text: &str| scan_text(Path::new("n.md"), text).laws.remove(0);
        let plain = scan("**§ abcdefgh1 A rule holds.**\n");
        for (head, public, draft) in [
            ("§!", true, false),
            ("§!?", true, true),
            ("§?!", true, true),
        ] {
            let law = scan(&format!("**{head} abcdefgh1 A rule holds.**\n"));
            assert_eq!((law.public, law.draft), (public, draft), "{head}");
            assert_eq!(
                (law.id.as_str(), law.name.as_str()),
                (plain.id.as_str(), plain.name.as_str())
            );
        }
        assert_eq!(
            undraft("**§!? abcdefgh1 A rule.**").as_deref(),
            Some("**§! abcdefgh1 A rule.**")
        );
        assert_eq!(
            undraft("**§?! abcdefgh1 A rule.**").as_deref(),
            Some("**§! abcdefgh1 A rule.**")
        );
        assert_eq!(
            redraft("**§! abcdefgh1 A rule.**"),
            "**§!? abcdefgh1 A rule.**"
        );
        assert_eq!(undraft("**§! abcdefgh1 A rule.**"), None);
        assert_eq!(
            plain_heads("+**§!? x\n-**§! x\n+**§? x\n"),
            "+**§ x\n-**§ x\n+**§ x\n"
        );
        let misordered = scan_text(Path::new("n.md"), "**§?! abcdefgh1 A rule holds.**\n");
        assert!(misordered.form_errors[0].message.contains("opens `§!?`"));
        assert_eq!(
            rewrite_parse_form("**§?! abcdefgh1 A rule holds.**\n"),
            "**§!? abcdefgh1 A rule holds.**\n"
        );
    }

    #[test]
    fn fix_form_keeps_the_draft_mark_of_a_head_and_a_clause() {
        let body = "§? abcdefgh1 Rule.\n- (a)? One.\n- (aa)? Narrowed.\n";
        assert_eq!(
            rewrite_parse_form(body),
            "**§? abcdefgh1 Rule.**\n\n- (a)? One.\n\n  - (aa)? Narrowed.\n"
        );
        assert_eq!(
            demark_head("**§? <a id=\"abcdefgh1\">abcdefgh1</a> Rule.**"),
            "**Rule.**"
        );
    }
}