memstead-base 0.24.0

Engine internals for Memstead — store, parser, validators, mem lifecycle, workspace policy. Published as a dependency of the memstead-cli and memstead-mcp products, not as a supported library — pre-1.0, no API stability promise.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
//! Anchors — engine-owned durable provenance records tying an entity to
//! the source artifacts it describes.
//!
//! An anchor is the projection pipeline's single new load-bearing
//! primitive: which artifact (in the medium's own namespace), at which
//! *grain*, under which *provenance class*, at which medium-typed
//! *version*, hashed over the **prepared** artifact form (never raw
//! bytes) where the class carries hash semantics, and the medium's
//! declared *hash stability* — so an unstable-source hash break resolves
//! as [`AnchorState::Recheck`], not [`AnchorState::Drifted`].
//!
//! ## Naming
//!
//! The `Anchor*` family is deliberately distinct from the three
//! provenance-adjacent type families already in the tree — it never
//! reuses `Provenance` / `ProvenanceKind` (the mutation-log record in
//! [`crate::provenance`]), nor `ArchiveProvenance` / `EntityProvenance` /
//! `History` (the authoring-provenance payload in
//! [`memstead_schema::archive_provenance`]). Those stay; anchors are a
//! separate concern (source→entity provenance, not mutation history nor
//! authoring lineage).
//!
//! ## Wire vocabulary (fixed contract)
//!
//! - provenance classes: `anchored` / `derived` / `authored` /
//!   `informed-by`
//! - grains: `span` / `file` / `tree` / `url` / `entity`
//! - hash stability: `stable` / `unstable`
//! - resolution states: `resolves` / `drifted` / `recheck` / `orphaned`
//!
//! The Rust identifiers around this vocabulary are the implementer's
//! choice; the wire strings are the contract and are locked by the
//! `*_wire_strings_are_stable` tests below.
//!
//! ## Storage
//!
//! Anchors persist in an engine-owned sidecar on the mem branch under
//! [`ANCHOR_SIDECAR_PATH`] (`.memstead/anchors.json`) — see
//! [`AnchorSidecar`]. The sidecar is written only through engine commits
//! (the [`crate::backend::MemBackend`] sidecar seam); every external
//! reader already filters the `.memstead/` namespace, so an anchor-only
//! commit yields no entity deltas and does not participate in `_hash`.
//!
//! ## Scope of this module
//!
//! Pure value types, wire (de)serialisation, validation (typed
//! `INVALID_ANCHOR` refusals with recovery detail), and the resolution
//! model. No storage or IO lives here — the backend seam and the
//! mutation/CLI wiring consume these types.

use std::collections::BTreeMap;

use serde::{Deserialize, Serialize};

/// Mem-relative path of the engine-owned anchors sidecar on the mem
/// branch. Lives under the `.memstead/` umbrella every external reader
/// already treats as non-entity, so an anchor-only commit produces zero
/// entity deltas.
pub const ANCHOR_SIDECAR_PATH: &str = ".memstead/anchors.json";

/// The sidecar document schema version every sidecar is written at unless
/// a row needs a newer one. Version 2 added the per-row `last_observed`
/// record; version 1 files load unchanged (the field is absent) and are
/// rewritten as version 2 on the next sidecar write.
pub const ANCHOR_SIDECAR_VERSION: u32 = 2;

/// The version a sidecar carries once any row holds a quoted `span` (with
/// its `span_hash`) or a `pinned` hash source: the two things an engine
/// that reads only versions 1 and 2 cannot understand. The version moves
/// up only when such a row is written ([`AnchorSidecar::required_version`])
/// and a sidecar without one keeps [`ANCHOR_SIDECAR_VERSION`], so nothing
/// written before spans existed changes its bytes. An older engine reading
/// a version-3 sidecar refuses it typed (`unsupported anchors sidecar
/// version 3`); it never loads the rows with the span dropped.
pub const ANCHOR_SIDECAR_SPAN_VERSION: u32 = 3;

/// Every sidecar version this engine reads. Anything else refuses typed:
/// a document written by a later engine is not parsed optimistically.
pub const ANCHOR_SIDECAR_VERSIONS_READ: &[u32] = &[1, 2, 3];

/// Stable typed error code returned when an `anchors[]` element is
/// malformed. Mirrors the engine's other typed-envelope codes; the whole
/// mutation refuses and the entity is not written.
pub const INVALID_ANCHOR_CODE: &str = "INVALID_ANCHOR";

/// The pinned sentinel a publish-time redaction writes into every
/// artifact reference (`artifact`, `derived_from` entries). A fixed,
/// visibly-artificial form rather than an empty string: the anchor entry
/// stays readable (class, counts, `at_version`, hash — the trust
/// metadata), while the reference discloses nothing — and an empty
/// reference stays what it always was, malformed
/// ([`AnchorSidecar::validate_artifact_references`]).
pub const REDACTED_ARTIFACT_SENTINEL: &str = "[redacted]";

// ---------------------------------------------------------------------------
// Provenance class
// ---------------------------------------------------------------------------

/// The epistemic standing of an anchor — how the entity relates to the
/// artifact it references.
///
/// - [`Anchored`](Self::Anchored) — the entity directly reflects specific
///   artifact content (carries hash semantics).
/// - [`Derived`](Self::Derived) — the entity was computed/synthesised from
///   one or more input artifacts (carries hash semantics; lists inputs).
/// - [`Authored`](Self::Authored) — a human/agent authored the entity with
///   the artifact in view (no hash semantics; excluded from drift
///   adjudication).
/// - [`InformedBy`](Self::InformedBy) — the artifact informed the entity
///   without a content-fidelity claim (no hash semantics; excluded from
///   drift adjudication).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum AnchorProvenanceClass {
    Anchored,
    Derived,
    Authored,
    InformedBy,
}

impl AnchorProvenanceClass {
    /// Every wire string, in declaration order — the allowed set a
    /// refusal echoes for recovery.
    pub const WIRE_VALUES: &'static [&'static str] =
        &["anchored", "derived", "authored", "informed-by"];

    /// Stable wire form.
    pub fn as_wire(&self) -> &'static str {
        match self {
            AnchorProvenanceClass::Anchored => "anchored",
            AnchorProvenanceClass::Derived => "derived",
            AnchorProvenanceClass::Authored => "authored",
            AnchorProvenanceClass::InformedBy => "informed-by",
        }
    }

    /// Inverse of [`Self::as_wire`]; `None` for an unknown string so the
    /// validator can refuse it typed rather than misclassify.
    pub fn from_wire(s: &str) -> Option<Self> {
        match s {
            "anchored" => Some(AnchorProvenanceClass::Anchored),
            "derived" => Some(AnchorProvenanceClass::Derived),
            "authored" => Some(AnchorProvenanceClass::Authored),
            "informed-by" => Some(AnchorProvenanceClass::InformedBy),
            _ => None,
        }
    }

    /// Whether this class carries hash semantics. `anchored` and
    /// `derived` assert content fidelity and participate in hash-drift
    /// adjudication; `authored` and `informed-by` do not — a content
    /// change under them produces no drift state, and supplying a hash on
    /// them is a validation refusal.
    pub fn is_hash_bearing(&self) -> bool {
        matches!(
            self,
            AnchorProvenanceClass::Anchored | AnchorProvenanceClass::Derived
        )
    }
}

// ---------------------------------------------------------------------------
// Grain
// ---------------------------------------------------------------------------

/// The granularity of the artifact reference an anchor carries.
///
/// `span` / `file` / `tree` select within a path-shaped namespace; `url`
/// selects a web resource; `entity` selects another mem's entity. The
/// medium-capability matrix ([`crate::binding::medium_capabilities`])
/// decides which grains a given medium's namespace can support — a
/// mismatch (e.g. `span` on a `url`-namespace medium) refuses typed at
/// validation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum AnchorGrain {
    Span,
    File,
    Tree,
    Url,
    Entity,
}

impl AnchorGrain {
    /// Every wire string, in declaration order.
    pub const WIRE_VALUES: &'static [&'static str] = &["span", "file", "tree", "url", "entity"];

    /// Stable wire form.
    pub fn as_wire(&self) -> &'static str {
        match self {
            AnchorGrain::Span => "span",
            AnchorGrain::File => "file",
            AnchorGrain::Tree => "tree",
            AnchorGrain::Url => "url",
            AnchorGrain::Entity => "entity",
        }
    }

    /// Inverse of [`Self::as_wire`]; `None` for an unknown string.
    pub fn from_wire(s: &str) -> Option<Self> {
        match s {
            "span" => Some(AnchorGrain::Span),
            "file" => Some(AnchorGrain::File),
            "tree" => Some(AnchorGrain::Tree),
            "url" => Some(AnchorGrain::Url),
            "entity" => Some(AnchorGrain::Entity),
            _ => None,
        }
    }

    /// Whether this grain can be expressed in the medium's declared anchor
    /// namespace (the `anchor_namespace` string from the E2 capability
    /// matrix: `path` / `path+commit` / `entity` / `url`).
    ///
    /// - `span` / `file` / `tree` require a path-shaped namespace
    ///   (`path` or `path+commit`);
    /// - `url` is admitted beside every namespace: a URL is an absolute
    ///   reference that never enters a path or entity namespace, so it
    ///   collides with nothing there — and the engine never observes it
    ///   itself, so no medium capability is claimed by admitting it;
    /// - `entity` requires the `entity` namespace.
    pub fn supported_by_namespace(&self, anchor_namespace: &str) -> bool {
        let path_shaped = matches!(anchor_namespace, "path" | "path+commit");
        match self {
            AnchorGrain::Span | AnchorGrain::File | AnchorGrain::Tree => path_shaped,
            AnchorGrain::Url => true,
            AnchorGrain::Entity => anchor_namespace == "entity",
        }
    }

    /// Whether this grain selects within a path-shaped namespace.
    pub fn is_path_shaped(&self) -> bool {
        matches!(
            self,
            AnchorGrain::Span | AnchorGrain::File | AnchorGrain::Tree
        )
    }
}

// ---------------------------------------------------------------------------
// Hash stability
// ---------------------------------------------------------------------------

/// The medium's declared hash stability — whether a change in the
/// prepared-content hash is a reliable drift signal.
///
/// A `stable` medium's hash break resolves [`AnchorState::Drifted`]; an
/// `unstable` medium's hash break resolves [`AnchorState::Recheck`]
/// (the hash may have moved for reasons unrelated to the entity's claim,
/// so the engine flags it for re-examination rather than asserting drift).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum AnchorHashStability {
    Stable,
    Unstable,
}

impl AnchorHashStability {
    /// Every wire string.
    pub const WIRE_VALUES: &'static [&'static str] = &["stable", "unstable"];

    /// Stable wire form.
    pub fn as_wire(&self) -> &'static str {
        match self {
            AnchorHashStability::Stable => "stable",
            AnchorHashStability::Unstable => "unstable",
        }
    }

    /// Inverse of [`Self::as_wire`]; `None` for an unknown string.
    pub fn from_wire(s: &str) -> Option<Self> {
        match s {
            "stable" => Some(AnchorHashStability::Stable),
            "unstable" => Some(AnchorHashStability::Unstable),
            _ => None,
        }
    }
}

// ---------------------------------------------------------------------------
// Medium-typed version
// ---------------------------------------------------------------------------

/// A medium-typed pinned version the anchor was recorded against.
///
/// Which variant applies follows from the medium's namespace: a git /
/// `path+commit` medium pins a [`Commit`](Self::Commit); a graph / `entity`
/// medium pins a [`Snapshot`](Self::Snapshot) token; a web / `url` medium
/// pins an [`Etag`](Self::Etag). A plain `path` medium (mtime change
/// signal, no retrievable version) records **absent** — represented as
/// `None` on [`Anchor::at_version`], never a variant here.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", content = "value", rename_all = "lowercase")]
pub enum AnchorVersion {
    /// A git commit id (`path+commit` / git namespace).
    Commit(String),
    /// A graph snapshot token (`entity` namespace).
    Snapshot(String),
    /// A web ETag (`url` namespace).
    Etag(String),
}

// ---------------------------------------------------------------------------
// Anchor
// ---------------------------------------------------------------------------

/// One durable anchor record: an entity's provenance tie to a single
/// source artifact.
///
/// This is the persisted + read shape. Malformed wire input is refused
/// upstream via [`AnchorInput::validate`], which produces this strict type
/// only when every rule holds.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Anchor {
    /// Artifact reference in the medium's own namespace — a repo-relative
    /// path, a `path@commit`, a URL, or an entity id, interpreted per
    /// [`Self::grain`] and the medium.
    pub artifact: String,
    /// The granularity of [`Self::artifact`].
    pub grain: AnchorGrain,
    /// The anchor's epistemic standing.
    pub class: AnchorProvenanceClass,
    /// The medium-typed pinned version, or `None` when the medium has no
    /// retrievable version (plain `path` / mtime).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub at_version: Option<AnchorVersion>,
    /// Content hash over the **prepared** artifact form (never raw bytes),
    /// present only when [`Self::class`] carries hash semantics. `None`
    /// for `authored` / `informed-by`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub hash: Option<String>,
    /// The medium's declared hash stability — governs whether a hash break
    /// resolves `drifted` or `recheck`.
    pub hash_stability: AnchorHashStability,
    /// For a `derived` class: the input artifact refs the entity was
    /// derived from. Empty for every other class.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub derived_from: Vec<String>,
    /// `hash(D)` of the binding that produced this anchor, when a
    /// binding produced it. `None` for a manually-authored anchor with no
    /// producing binding.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub binding: Option<String>,
    /// The NAME of the source (as declared in the producing binding's
    /// `sources[]`) that produced this anchor — so a discovery run can
    /// be measured per entry point. Optional and additive: pre-existing
    /// sidecars load unchanged and are never backfilled (a guessed
    /// provenance is worse than an absent one). Validated against the
    /// producing binding's declared names only when [`Self::binding`]
    /// still resolves in the workspace.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub source: Option<String>,
    /// The verbatim words this row quotes from the artifact (sidecar
    /// version 3), on the `url`, `span` and `file` grains. A row carrying a
    /// span is adjudicated on the span's PRESENCE in the observed text (in
    /// the canonical span form, [`crate::preparation::canonical_span_form`]),
    /// not on the document hash: it resolves while the words stand, whatever
    /// else on the page changed, and reads [`AnchorState::SpanAbsent`] once
    /// they are gone. Part of the row's identity beside artifact, grain and
    /// class, so several spans on one document are several rows. `None` on
    /// every row written before spans existed, which adjudicates exactly as
    /// before.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub span: Option<String>,
    /// The hash over the canonical form of [`Self::span`], computed by the
    /// engine at write (a caller never supplies it). Present exactly when
    /// `span` is.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub span_hash: Option<String>,
    /// A row whose locator or quoted span could NOT be checked against the
    /// artifact at write time (consistency-sweep 03/03). The write path
    /// deliberately reads no source content, so the check is possible only
    /// where the caller supplied `content`; elsewhere the anchor is accepted
    /// and this records that its span is unverified, rather than letting a
    /// later surface report it as adjudicated. Set on a `span`-grain row
    /// with an unchecked line-range locator, and on any row whose `span`
    /// was written without `content`; cleared once a recorded observation
    /// adjudicates the span. Serialized only when true, so an existing
    /// sidecar is unchanged.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub span_unvalidated: bool,
    /// Who established this row's [`Self::hash`] baseline. `None` on every
    /// row written before the field existed, which is honest: the baseline's
    /// origin was not recorded then and guessing it would be worse than
    /// admitting it. Set at write and at backfill from then on, so a reader
    /// can tell an author-pinned baseline from an engine-inferred one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub hash_source: Option<AnchorHashSource>,
    /// The most recent observation recorded for this row (sidecar version
    /// 2): when it was made, the prepared-content hash it saw, and the state
    /// it resolved. Written for grains the engine cannot observe itself —
    /// a `url` row adjudicated from an observer-supplied observation — so
    /// the row can age visibly (`unobserved for N days`) instead of resting
    /// in `unobserved` forever. Path and entity rows are observed live on
    /// every pass and carry none. Absent on every version-1 row.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub last_observed: Option<AnchorObservation>,
}

/// One recorded observation of an anchor's artifact (the `last_observed`
/// record of a sidecar row).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AnchorObservation {
    /// When the observation was made — second-granularity ISO-8601 UTC
    /// (`YYYY-MM-DDTHH:MM:SSZ`), as supplied by the observer or stamped by
    /// the engine at recording time.
    pub at: String,
    /// The prepared-content hash the observation saw; `None` when the
    /// observer reported the artifact absent.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub hash: Option<String>,
    /// The state the row resolved to against that observation.
    pub state: AnchorState,
}

/// Who established an anchor's hash baseline. A baseline that resets with no trace makes drift
/// unfalsifiable, so the origin is recorded rather than inferred.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum AnchorHashSource {
    /// The writer supplied the hash, or the content the engine hashed.
    Author,
    /// A completed verify filled a hash-less row from what it observed.
    Backfill,
    /// The engine hashed the target as it stood at write time: an
    /// `entity`-grain row of a hash-bearing class written without a hash
    /// while its target was loaded takes the target's prepared hash then,
    /// so the next verify reads it against the target as it was when the
    /// claim was made, never against a later state. Sidecar version 3.
    Pinned,
}

impl Anchor {
    /// Whether `other`, as a caller supplied it, restates this stored row:
    /// equal on every field a caller writes (artifact, grain, class,
    /// version, stability, derivation, binding, source, span validation)
    /// and, when the caller named a hash, on the hash too. The engine-set
    /// fields (`hash_source`, `last_observed`, a backfilled hash the caller
    /// did not name) do not count: a re-pin that restates the row is a
    /// no-op, not a fresh baseline.
    pub fn same_as_supplied(&self, other: &Anchor) -> bool {
        self.artifact == other.artifact
            && self.grain == other.grain
            && self.class == other.class
            && self.at_version == other.at_version
            && self.hash_stability == other.hash_stability
            && self.derived_from == other.derived_from
            && self.binding == other.binding
            && self.source == other.source
            && same_span(self.span.as_deref(), other.span.as_deref())
            && self.span_unvalidated == other.span_unvalidated
            && other
                .hash
                .as_ref()
                .is_none_or(|h| Some(h) == self.hash.as_ref())
    }
}

/// Whether two optional spans name the same words: both absent, or both
/// present and equal in the canonical span form. The one span identity
/// rule, shared by the merge, the no-op check, the duplicate refusal and
/// the unset selector, so a span re-sent with different line breaks or
/// quote marks is the same row everywhere.
pub fn same_span(a: Option<&str>, b: Option<&str>) -> bool {
    match (a, b) {
        (None, None) => true,
        (Some(a), Some(b)) => {
            crate::preparation::canonical_span_form(a) == crate::preparation::canonical_span_form(b)
        }
        _ => false,
    }
}

impl AnchorHashSource {
    pub fn as_wire(self) -> &'static str {
        match self {
            AnchorHashSource::Author => "author",
            AnchorHashSource::Backfill => "backfill",
            AnchorHashSource::Pinned => "pinned",
        }
    }
}

// ---------------------------------------------------------------------------
// Span locators
// ---------------------------------------------------------------------------

/// What a `span` anchor's locator (everything after the first `#`) selects.
///
/// Two forms are legal and the distinction is not cosmetic. A LINE RANGE is
/// checkable against content the write path already holds; a UNIT KEY is a
/// delivery preparation's own key (`dated-entries` writes
/// `<path>#<iso-stamp>`), whose validity only that preparation can judge, and
/// which the existing unit-absent refusal already covers where content is
/// supplied. Anything the engine can check, it checks; anything it cannot, it
/// records as unchecked.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SpanLocator<'a> {
    /// `L<start>` or `L<start>-L<end>`, 1-based and inclusive.
    Lines { start: usize, end: usize },
    /// A preparation's delivery-unit key, opaque here.
    Unit(&'a str),
}

/// Parse a `span` artifact reference's locator, or say why it cannot be one.
/// `Ok(None)` means the reference carries no locator at all.
///
/// **No locator is not a refusal**, and that is a deliberate line. A
/// `span`-grain reference naming a bare path addresses its whole file, which
/// is what a span's hash covers anyway with no preparation declared, and such
/// anchors are written today. Refusing them would be a new wall across a
/// working flow, which the no-new-walls rule forbids.
///
/// The refusals are the shapes that can never address anything: an EMPTY
/// locator (`path#`, which announces a span and then names none), and a
/// locator that announces itself as a line range by its `L` prefix and then
/// contradicts itself (no digits, a zero line, an end before its start). A
/// locator that does not look like a line range is a unit key and is accepted
/// here, because this function cannot know a preparation's key grammar and
/// refusing what it cannot judge would break every `dated-entries` anchor.
pub fn parse_span_locator(artifact: &str) -> Result<Option<SpanLocator<'_>>, &'static str> {
    let locator = match artifact.split_once('#') {
        None => return Ok(None),
        Some((_, loc)) if loc.trim().is_empty() => {
            return Err("the span locator after `#` is empty");
        }
        Some((_, loc)) => loc,
    };
    // Only an `L`-prefixed locator claims to be a line range. Everything else
    // is a unit key and is not this function's to judge.
    let looks_like_lines = locator.starts_with('L')
        && locator[1..]
            .chars()
            .next()
            .is_some_and(|c| c.is_ascii_digit());
    if !looks_like_lines {
        return Ok(Some(SpanLocator::Unit(locator)));
    }
    let (start_raw, end_raw) = match locator.split_once('-') {
        None => (locator, locator),
        Some((a, b)) => (a, b),
    };
    let num = |part: &str| -> Option<usize> {
        part.strip_prefix('L')
            .filter(|d| !d.is_empty() && d.chars().all(|c| c.is_ascii_digit()))
            .and_then(|d| d.parse::<usize>().ok())
    };
    let (Some(start), Some(end)) = (num(start_raw), num(end_raw)) else {
        return Err("a line-range span locator must read `L<start>` or `L<start>-L<end>`");
    };
    if start == 0 {
        return Err("line numbers are 1-based, so `L0` addresses nothing");
    }
    if end < start {
        return Err("a line-range span locator ends before it starts");
    }
    Ok(Some(SpanLocator::Lines { start, end }))
}

// ---------------------------------------------------------------------------
// Validation
// ---------------------------------------------------------------------------

/// A permissive wire-shaped anchor element as it arrives on a mutation's
/// `anchors[]` parameter. All fields are optional / string-typed so an
/// unknown class or grain surfaces as a typed [`AnchorValidationError`]
/// with recovery detail rather than an opaque serde failure. Call
/// [`Self::validate`] to obtain a strict [`Anchor`].
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct AnchorInput {
    #[serde(default)]
    pub artifact: Option<String>,
    #[serde(default)]
    pub grain: Option<String>,
    #[serde(default)]
    pub class: Option<String>,
    #[serde(default)]
    pub at_version: Option<AnchorVersion>,
    #[serde(default)]
    pub hash: Option<String>,
    /// The observed artifact CONTENT (UTF-8 text), for the engine to compute
    /// `hash` from through its preparation registry
    /// ([`crate::preparation::supplied_content_hash`]) — the write-time
    /// observation for a grain the engine cannot observe itself: a `url`
    /// anchor, because the engine never fetches. Accepted for the `span` /
    /// `file` / `url` grains; mutually exclusive with `hash`; refused on a
    /// non-hash class and on the `entity` / `tree` grains, whose prepared
    /// form is never computed from supplied bytes.
    #[serde(default)]
    pub content: Option<String>,
    /// The verbatim words the entity quotes from the artifact. Accepted on
    /// the `url` / `span` / `file` grains of a hash-bearing class; refused
    /// beside `hash` (the engine computes the span hash itself), on the
    /// `entity` / `tree` grains (never prepared from supplied text), and
    /// when empty. With `content`, the write refuses unless the span occurs
    /// in it (canonical form); without `content`, the row is recorded with
    /// the span unverified.
    #[serde(default)]
    pub span: Option<String>,
    #[serde(default)]
    pub hash_stability: Option<String>,
    #[serde(default)]
    pub derived_from: Option<Vec<String>>,
    #[serde(default)]
    pub binding: Option<String>,
    #[serde(default)]
    pub source: Option<String>,
}

/// A permissive wire-shaped `anchors_unset[]` element — an explicit
/// removal selector on the update surface. Each entry names an `artifact`
/// and may narrow by `grain` and/or `class`; a bare artifact selects every
/// anchor on it. String-typed like [`AnchorInput`] so an unknown grain or
/// class refuses typed (`INVALID_ANCHOR`) rather than silently selecting
/// nothing forever. Call [`Self::validate`] to obtain a strict
/// [`AnchorUnset`].
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct AnchorUnsetInput {
    #[serde(default)]
    pub artifact: Option<String>,
    #[serde(default)]
    pub grain: Option<String>,
    #[serde(default)]
    pub class: Option<String>,
    /// Narrow to the one row quoting this span (compared in the canonical
    /// span form). Absent selects rows with or without a span.
    #[serde(default)]
    pub span: Option<String>,
}

impl AnchorUnsetInput {
    /// Validate this wire element into a strict [`AnchorUnset`], or refuse
    /// typed. Rules: artifact present and non-empty; grain / class, when
    /// supplied, must be known wire strings (absent means "any").
    pub fn validate(&self) -> Result<AnchorUnset, AnchorValidationError> {
        let artifact = self
            .artifact
            .as_deref()
            .map(str::trim)
            .filter(|s| !s.is_empty())
            .map(str::to_string)
            .ok_or(AnchorValidationError::MissingArtifact)?;
        let grain = match self.grain.as_deref() {
            None => None,
            Some(s) => Some(AnchorGrain::from_wire(s).ok_or_else(|| {
                AnchorValidationError::UnknownGrain {
                    got: Some(s.to_string()),
                    allowed: AnchorGrain::WIRE_VALUES,
                }
            })?),
        };
        let class = match self.class.as_deref() {
            None => None,
            Some(s) => Some(AnchorProvenanceClass::from_wire(s).ok_or_else(|| {
                AnchorValidationError::UnknownClass {
                    got: Some(s.to_string()),
                    allowed: AnchorProvenanceClass::WIRE_VALUES,
                }
            })?),
        };
        let span = self
            .span
            .as_deref()
            .map(crate::preparation::canonical_span_form)
            .filter(|s| !s.is_empty());
        Ok(AnchorUnset {
            artifact,
            grain,
            class,
            span,
        })
    }
}

/// A validated explicit-removal selector: which of an entity's anchors an
/// update's `anchors_unset[]` entry removes. Selection is by artifact,
/// optionally narrowed by grain and/or class; a selector matching nothing
/// is a no-op (removal is idempotent — its job in recovery flows is "make
/// sure this is gone").
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AnchorUnset {
    /// Artifact reference to remove anchors from, exactly as stored.
    pub artifact: String,
    /// When present, only anchors of this grain are removed.
    pub grain: Option<AnchorGrain>,
    /// When present, only anchors of this class are removed.
    pub class: Option<AnchorProvenanceClass>,
    /// When present (canonical span form), only the row quoting this span
    /// is removed; absent, span rows and span-less rows alike are selected.
    pub span: Option<String>,
}

impl AnchorUnset {
    /// Whether this selector removes `anchor`.
    pub fn matches(&self, anchor: &Anchor) -> bool {
        anchor.artifact == self.artifact
            && self.grain.is_none_or(|g| anchor.grain == g)
            && self.class.is_none_or(|c| anchor.class == c)
            && self.span.as_deref().is_none_or(|s| {
                anchor
                    .span
                    .as_deref()
                    .is_some_and(|have| crate::preparation::canonical_span_form(have) == s)
            })
    }
}

/// A typed `INVALID_ANCHOR` refusal. The whole mutation refuses and the
/// entity is not written; [`Self::detail`] carries the recovery payload
/// (offending value + allowed set) the agent fixes from.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum AnchorValidationError {
    /// Provenance class is absent or not one of the allowed wire strings.
    #[error("unknown anchor provenance class {got:?}; allowed: {}", allowed.join(", "))]
    UnknownClass {
        got: Option<String>,
        allowed: &'static [&'static str],
    },
    /// Grain is absent or not one of the allowed wire strings.
    #[error("unknown anchor grain {got:?}; allowed: {}", allowed.join(", "))]
    UnknownGrain {
        got: Option<String>,
        allowed: &'static [&'static str],
    },
    /// Hash stability, when supplied, is not an allowed wire string.
    #[error("unknown anchor hash stability {got:?}; allowed: {}", allowed.join(", "))]
    UnknownHashStability {
        got: String,
        allowed: &'static [&'static str],
    },
    /// The artifact reference is missing or empty.
    #[error("anchor is missing its artifact reference")]
    MissingArtifact,
    /// A content hash (or content to hash) was supplied on a class that
    /// carries no hash semantics (`authored` / `informed-by`).
    #[error("anchor class '{class}' carries no hash semantics — a content hash is not permitted")]
    HashOnNonHashClass { class: &'static str },
    /// Both `hash` and `content` were supplied — the engine computes the
    /// hash from content, so a supplied hash beside it is ambiguous.
    #[error(
        "anchor supplies both `hash` and `content`; supply one — the engine computes the hash from `content`"
    )]
    ContentAndHash,
    /// `content` was supplied for a grain whose prepared form is never
    /// computed from supplied bytes: `entity` (computed from the live graph)
    /// or `tree` (whose prepared form, under a code map, is enumerated by
    /// the engine).
    #[error(
        "anchor grain '{grain}' does not accept `content`: its prepared form is not computed \
         from supplied bytes (accepted for span / file / url)"
    )]
    ContentNotAcceptedForGrain { grain: &'static str },
    /// `content` was supplied for a `<path>#<key>` unit under a delivery
    /// preparation, but the content yields no unit with that key.
    #[error(
        "anchor artifact {artifact:?} names a delivery unit the supplied `content` does not \
         yield; supply the whole file's content, or address a unit it contains"
    )]
    UnitAbsentFromContent { artifact: String },
    /// A `span`-grain anchor whose locator is missing, empty, or announces a
    /// line range and then contradicts itself. Refused at write: such a row
    /// can never address anything, and accepting it produces an anchor that
    /// is unadjudicable from birth.
    #[error("anchor artifact {artifact:?} is not a usable span reference: {reason}")]
    SpanLocatorUnusable {
        artifact: String,
        reason: &'static str,
    },
    /// A `span`-grain anchor whose line range lies outside the content the
    /// caller supplied. Only fires where content is in hand — the write path
    /// reads no source, and where it cannot check, the row records that
    /// instead (`span_unvalidated`).
    #[error(
        "anchor artifact {artifact:?} names lines the supplied `content` does not have \
         (it has {lines} line(s)); address a range the artifact contains"
    )]
    SpanOutsideContent { artifact: String, lines: usize },
    /// One payload named the same `(artifact, grain, class, span)` identity
    /// twice. That identity is the sidecar's merge key, so the later
    /// occurrence silently replaced the earlier one and the caller was never
    /// told an anchor it wrote had gone missing. A LATER call replacing the
    /// stored row is unaffected: the unit of this refusal is one payload.
    #[error(
        "the anchors payload names {artifact:?} at grain `{grain}` and class `{class}`{} more \
         than once; that identity is one row, so the repeats would silently collapse to the \
         last one: send it once, or vary the grain, class or span",
        span.as_deref().map(|s| format!(" with span {s:?}")).unwrap_or_default()
    )]
    DuplicateAnchorTriple {
        artifact: String,
        grain: &'static str,
        class: &'static str,
        span: Option<String>,
    },
    /// Both `span` and `hash` were supplied. The engine computes a span
    /// row's hashes itself (the span hash from the span, the document hash
    /// from `content`), so a supplied hash beside a span is ambiguous.
    #[error(
        "anchor supplies both `span` and `hash`; the engine computes a span row's hashes \
         itself: supply the span with `content`, or a hash without a span"
    )]
    SpanAndHash,
    /// A `span` that is empty after canonicalisation names no words and can
    /// never be found.
    #[error(
        "anchor `span` is empty: a quoted span must carry at least one non-whitespace character"
    )]
    SpanEmpty,
    /// A `span` was supplied on a grain whose prepared form is never computed
    /// from supplied text (`entity`, `tree`), so the words could never be
    /// looked for.
    #[error(
        "anchor grain '{grain}' does not accept `span`: its prepared form is never computed \
         from supplied text (accepted for url / span / file)"
    )]
    SpanNotAcceptedForGrain { grain: &'static str },
    /// The canonical form of the supplied `span` does not occur in the
    /// canonical form of the supplied `content`: the observation the writer
    /// handed over does not carry the words the entity quotes.
    #[error(
        "anchor artifact {artifact:?}: the span {span:?} does not occur in the supplied \
         `content` (compared in the canonical span form: NFC, whitespace runs to one space, \
         soft hyphens and line-end hyphens removed, typographic quotes, dashes and ligatures \
         to ASCII; everything else exact); quote the words as the artifact carries them"
    )]
    SpanAbsentFromContent { artifact: String, span: String },
    /// A `source` was supplied but is empty after trimming — a source
    /// name, when present, must be one of the producing binding's
    /// declared names, and an empty string can never be one.
    #[error("anchor `source`, when present, must be a non-empty source name")]
    EmptySource,
    /// The anchor's `source` is not among the sources declared by its
    /// own (resolvable) producing binding. Carries the declared names
    /// as the recovery payload. Only fires when the `binding` hash
    /// still resolves in this workspace — an orphaned or since-edited
    /// binding accepts any non-empty name, deliberately: a legacy
    /// anchor whose binding was renamed keeps writing as long as its
    /// artifact reference is alive under the workspace-relative
    /// fallback (`mem_commands::source_dialect_anchors_join_fallback_collide_and_refuse`).
    #[error(
        "anchor `source` {got:?} is not declared by the anchor's producing binding; \
         declared sources: {}",
        declared.join(", ")
    )]
    SourceNotDeclared { got: String, declared: Vec<String> },
    /// A path-grain artifact reference that resolves under NO candidate
    /// join — neither source-relative (joined onto the declaring source's
    /// pointer, decision 26) nor workspace-relative. Refused at write time
    /// so the mutation never stores a silently dead (orphaned-at-birth)
    /// reference; the payload names every candidate tried so the agent can
    /// fix the dialect.
    #[error(
        "anchor artifact {artifact:?} resolves under no candidate path (tried: {}); artifact \
         paths are source-relative (joined onto the source's pointer) or workspace-relative — \
         write the path exactly as the brief lists it",
        candidates.join(", ")
    )]
    ArtifactUnresolvable {
        artifact: String,
        candidates: Vec<String>,
    },
    /// The grain cannot be expressed in the medium's anchor namespace
    /// (per the E2 capability matrix), e.g. `span` on a non-path medium.
    #[error(
        "anchor grain '{grain}' is unsupported by a '{medium_type}' medium: its \
         '{anchor_namespace}' namespace does not admit that grain"
    )]
    GrainNamespaceUnsupported {
        grain: &'static str,
        medium_type: String,
        anchor_namespace: &'static str,
    },
    /// A path-shaped grain (`span` / `file` / `tree`) names a URL. A URL
    /// never enters a path namespace: the web resource is addressed by the
    /// `url` grain, and a page coordinate inside it is not a path span.
    #[error(
        "anchor grain '{grain}' selects within a path namespace, but its artifact '{artifact}'          is a URL — a URL never enters a path namespace; use `grain: url` for the resource"
    )]
    PathGrainOnUrlArtifact {
        grain: &'static str,
        artifact: String,
    },
}

/// Whether an artifact string is URL-shaped (`<scheme>://…`).
pub fn looks_like_url(artifact: &str) -> bool {
    let Some((scheme, rest)) = artifact.split_once("://") else {
        return false;
    };
    !rest.is_empty()
        && scheme
            .chars()
            .next()
            .is_some_and(|c| c.is_ascii_alphabetic())
        && scheme
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'))
}

impl AnchorValidationError {
    /// The stable typed code — always [`INVALID_ANCHOR_CODE`].
    pub fn code(&self) -> &'static str {
        INVALID_ANCHOR_CODE
    }

    /// Structured recovery detail for the typed envelope: the offending
    /// field, its bad value, and the allowed set where one applies.
    pub fn detail(&self) -> BTreeMap<String, serde_json::Value> {
        let mut d = BTreeMap::new();
        match self {
            AnchorValidationError::UnknownClass { got, allowed } => {
                d.insert("field".into(), "class".into());
                d.insert("got".into(), serde_json::json!(got));
                d.insert("allowed".into(), serde_json::json!(allowed));
            }
            AnchorValidationError::UnknownGrain { got, allowed } => {
                d.insert("field".into(), "grain".into());
                d.insert("got".into(), serde_json::json!(got));
                d.insert("allowed".into(), serde_json::json!(allowed));
            }
            AnchorValidationError::UnknownHashStability { got, allowed } => {
                d.insert("field".into(), "hash_stability".into());
                d.insert("got".into(), serde_json::json!(got));
                d.insert("allowed".into(), serde_json::json!(allowed));
            }
            AnchorValidationError::MissingArtifact => {
                d.insert("field".into(), "artifact".into());
            }
            AnchorValidationError::EmptySource => {
                d.insert("field".into(), "source".into());
            }
            AnchorValidationError::SourceNotDeclared { got, declared } => {
                d.insert("field".into(), "source".into());
                d.insert("got".into(), serde_json::json!(got));
                d.insert("declared".into(), serde_json::json!(declared));
            }
            AnchorValidationError::HashOnNonHashClass { class } => {
                d.insert("field".into(), "hash".into());
                d.insert("class".into(), serde_json::json!(class));
            }
            AnchorValidationError::ContentAndHash => {
                d.insert("field".into(), "content".into());
                d.insert(
                    "expected".into(),
                    serde_json::json!("either `hash` or `content`, never both"),
                );
            }
            AnchorValidationError::ContentNotAcceptedForGrain { grain } => {
                d.insert("field".into(), "content".into());
                d.insert("grain".into(), serde_json::json!(grain));
                d.insert(
                    "accepted_grains".into(),
                    serde_json::json!(["span", "file", "url"]),
                );
            }
            AnchorValidationError::UnitAbsentFromContent { artifact } => {
                d.insert("field".into(), "content".into());
                d.insert("got".into(), serde_json::json!(artifact));
            }
            AnchorValidationError::SpanLocatorUnusable { artifact, reason } => {
                d.insert("field".into(), "artifact".into());
                d.insert("got".into(), serde_json::json!(artifact));
                d.insert("expected".into(), serde_json::json!(reason));
            }
            AnchorValidationError::SpanOutsideContent { artifact, lines } => {
                d.insert("field".into(), "artifact".into());
                d.insert("got".into(), serde_json::json!(artifact));
                d.insert("content_lines".into(), serde_json::json!(lines));
            }
            AnchorValidationError::DuplicateAnchorTriple {
                artifact,
                grain,
                class,
                span,
            } => {
                d.insert("field".into(), "anchors".into());
                d.insert(
                    "got".into(),
                    serde_json::json!({
                        "artifact": artifact, "grain": grain, "class": class, "span": span
                    }),
                );
                d.insert(
                    "expected".into(),
                    serde_json::json!(
                        "each (artifact, grain, class, span) identity at most once per payload"
                    ),
                );
            }
            AnchorValidationError::SpanAndHash => {
                d.insert("field".into(), "span".into());
                d.insert(
                    "expected".into(),
                    serde_json::json!("either `span` (with `content`) or `hash`, never both"),
                );
            }
            AnchorValidationError::SpanEmpty => {
                d.insert("field".into(), "span".into());
            }
            AnchorValidationError::SpanNotAcceptedForGrain { grain } => {
                d.insert("field".into(), "span".into());
                d.insert("grain".into(), serde_json::json!(grain));
                d.insert(
                    "accepted_grains".into(),
                    serde_json::json!(["url", "span", "file"]),
                );
            }
            AnchorValidationError::SpanAbsentFromContent { artifact, span } => {
                d.insert("field".into(), "span".into());
                d.insert("artifact".into(), serde_json::json!(artifact));
                d.insert("got".into(), serde_json::json!(span));
                d.insert(
                    "expected".into(),
                    serde_json::json!(
                        "the span, in the canonical span form, occurring in the canonical form \
                         of `content`"
                    ),
                );
            }
            AnchorValidationError::ArtifactUnresolvable {
                artifact,
                candidates,
            } => {
                d.insert("field".into(), "artifact".into());
                d.insert("got".into(), serde_json::json!(artifact));
                d.insert("candidates_tried".into(), serde_json::json!(candidates));
                d.insert(
                    "expected".into(),
                    serde_json::json!(
                        "a source-relative path (joined onto the source's pointer) or a \
                         workspace-relative path that resolves to an existing artifact"
                    ),
                );
            }
            AnchorValidationError::GrainNamespaceUnsupported {
                grain,
                medium_type,
                anchor_namespace,
            } => {
                d.insert("field".into(), "grain".into());
                d.insert("grain".into(), serde_json::json!(grain));
                d.insert("medium_type".into(), serde_json::json!(medium_type));
                d.insert(
                    "anchor_namespace".into(),
                    serde_json::json!(anchor_namespace),
                );
            }
            AnchorValidationError::PathGrainOnUrlArtifact { grain, artifact } => {
                d.insert("field".into(), "grain".into());
                d.insert("grain".into(), serde_json::json!(grain));
                d.insert("got".into(), serde_json::json!(artifact));
                d.insert(
                    "expected".into(),
                    serde_json::json!(
                        "`grain: url` for a web resource — a URL never enters a path namespace"
                    ),
                );
            }
        }
        d
    }
}

impl AnchorInput {
    /// Validate this wire element into a strict [`Anchor`], or refuse
    /// typed.
    ///
    /// `medium` — the resolving medium's `(type_name, anchor_namespace)`
    /// pair, when the mutation resolved one. When `Some`, the grain is
    /// checked against the namespace (the capability-matrix refusal);
    /// when `None` (no medium context — a manually-authored anchor), the
    /// namespace check is skipped and only the vocabulary + hash-semantics
    /// rules apply.
    ///
    /// Rules enforced (each a typed [`AnchorValidationError`]):
    /// - class present and known;
    /// - grain present and known;
    /// - artifact reference present and non-empty;
    /// - a hash (or content to hash) is supplied only on a hash-bearing
    ///   class; `content` and `hash` are mutually exclusive; `content` is
    ///   accepted only for the grains whose prepared form the registry
    ///   computes from supplied bytes (`span` / `file` / `url`), and then
    ///   `hash` is the registry's prepared hash of it;
    /// - hash stability, when supplied, is a known wire string (defaults
    ///   per grain when absent — `url` unstable, every other grain stable);
    /// - grain supported by the medium's namespace (when `medium` given).
    pub fn validate(&self, medium: Option<(&str, &str)>) -> Result<Anchor, AnchorValidationError> {
        let class = match self
            .class
            .as_deref()
            .and_then(AnchorProvenanceClass::from_wire)
        {
            Some(c) => c,
            None => {
                return Err(AnchorValidationError::UnknownClass {
                    got: self.class.clone(),
                    allowed: AnchorProvenanceClass::WIRE_VALUES,
                });
            }
        };
        let grain = match self.grain.as_deref().and_then(AnchorGrain::from_wire) {
            Some(g) => g,
            None => {
                return Err(AnchorValidationError::UnknownGrain {
                    got: self.grain.clone(),
                    allowed: AnchorGrain::WIRE_VALUES,
                });
            }
        };

        let artifact = self
            .artifact
            .as_deref()
            .map(str::trim)
            .filter(|s| !s.is_empty())
            .map(str::to_string)
            .ok_or(AnchorValidationError::MissingArtifact)?;

        // Hash stability: default per grain when absent (`url` unstable,
        // every other grain stable); refuse an unknown supplied value.
        let hash_stability = match self.hash_stability.as_deref() {
            None => crate::preparation::default_hash_stability(grain),
            Some(s) => AnchorHashStability::from_wire(s).ok_or_else(|| {
                AnchorValidationError::UnknownHashStability {
                    got: s.to_string(),
                    allowed: AnchorHashStability::WIRE_VALUES,
                }
            })?,
        };

        // A hash is only meaningful on a hash-bearing class. A quoted span
        // is a fidelity claim ("the artifact says these words"), so it is
        // one too.
        let hash = self
            .hash
            .as_deref()
            .map(str::trim)
            .filter(|s| !s.is_empty())
            .map(str::to_string);
        if (hash.is_some() || self.content.is_some() || self.span.is_some())
            && !class.is_hash_bearing()
        {
            return Err(AnchorValidationError::HashOnNonHashClass {
                class: class.as_wire(),
            });
        }
        // The quoted span: the engine computes its hashes, so a supplied
        // hash beside it is refused; an empty span names nothing; the
        // `entity` and `tree` grains are never prepared from supplied text.
        // Checked against `content` where the caller supplied it (the words
        // must occur, in the canonical span form); recorded as unverified
        // where they did not.
        let span = match self.span.as_deref() {
            None => None,
            Some(_) if hash.is_some() => return Err(AnchorValidationError::SpanAndHash),
            Some(raw) => {
                if crate::preparation::canonical_span_form(raw).is_empty() {
                    return Err(AnchorValidationError::SpanEmpty);
                }
                if matches!(grain, AnchorGrain::Entity | AnchorGrain::Tree) {
                    return Err(AnchorValidationError::SpanNotAcceptedForGrain {
                        grain: grain.as_wire(),
                    });
                }
                if let Some(content) = self.content.as_deref()
                    && !crate::preparation::span_occurs(raw, content)
                {
                    return Err(AnchorValidationError::SpanAbsentFromContent {
                        artifact: artifact.clone(),
                        span: raw.trim().to_string(),
                    });
                }
                Some(raw.trim().to_string())
            }
        };
        let span_hash = span.as_deref().map(crate::preparation::span_hash);
        let mut span_unvalidated = span.is_some() && self.content.is_none();
        // Supplied content: the engine computes the prepared hash through the
        // preparation registry (touchpoint A at write time) — the one way a
        // `url` anchor's recorded hash is ever the engine's prepared form.
        let hash = match self.content.as_deref() {
            None => hash,
            Some(_) if hash.is_some() => return Err(AnchorValidationError::ContentAndHash),
            Some(content) => {
                match crate::preparation::supplied_content_hash(grain, content.as_bytes()) {
                    Some(h) => Some(h),
                    None => {
                        return Err(AnchorValidationError::ContentNotAcceptedForGrain {
                            grain: grain.as_wire(),
                        });
                    }
                }
            }
        };

        // The span-grain locator (consistency-sweep 03/03). A locator that
        // can never address anything is refused here, context-free, because
        // no medium context can rescue it. Where the caller supplied content,
        // a line range is checked against it; where they did not, the row
        // carries `span_unvalidated` so no later surface reports it as
        // adjudicated.
        if grain == AnchorGrain::Span {
            let locator = parse_span_locator(&artifact).map_err(|reason| {
                AnchorValidationError::SpanLocatorUnusable {
                    artifact: artifact.clone(),
                    reason,
                }
            })?;
            match (locator, self.content.as_deref()) {
                (Some(SpanLocator::Lines { end, .. }), Some(content)) => {
                    let lines = content.lines().count();
                    if end > lines {
                        return Err(AnchorValidationError::SpanOutsideContent {
                            artifact: artifact.clone(),
                            lines,
                        });
                    }
                }
                // A unit key with content in hand is the existing
                // unit-absent refusal's business, at the seam that knows the
                // source's preparation; a check here would have to guess it.
                (Some(SpanLocator::Unit(_)), Some(_)) => {}
                // No locator addresses the whole artifact, and the existence
                // gate already checks that the artifact is there. Nothing is
                // left unchecked, so nothing is recorded as unchecked.
                (None, _) => {}
                (Some(_), None) => span_unvalidated = true,
            }
        }

        // A path-shaped grain never names a URL: the resource is the `url`
        // grain's business, whatever medium the mem sits beside.
        if grain.is_path_shaped() && looks_like_url(&artifact) {
            return Err(AnchorValidationError::PathGrainOnUrlArtifact {
                grain: grain.as_wire(),
                artifact,
            });
        }

        // Grain must be expressible in the medium's namespace (a `url`
        // grain is admitted beside every medium — see
        // [`AnchorGrain::supported_by_namespace`]).
        if let Some((medium_type, namespace)) = medium
            && !grain.supported_by_namespace(namespace)
        {
            // Resolve the namespace to its `&'static str` so the error
            // carries a stable value even though the input came borrowed.
            let anchor_namespace = match namespace {
                "path" => "path",
                "path+commit" => "path+commit",
                "entity" => "entity",
                "url" => "url",
                _ => "path",
            };
            return Err(AnchorValidationError::GrainNamespaceUnsupported {
                grain: grain.as_wire(),
                medium_type: medium_type.to_string(),
                anchor_namespace,
            });
        }

        // `source`, when present, must be non-empty. (Whether it names a
        // source the producing binding actually declares is checked at
        // the engine seam, which can resolve the binding hash — this
        // context-free validator cannot.)
        let source = match self.source.as_deref() {
            None => None,
            Some(raw) => {
                let trimmed = raw.trim();
                if trimmed.is_empty() {
                    return Err(AnchorValidationError::EmptySource);
                }
                Some(trimmed.to_string())
            }
        };

        Ok(Anchor {
            artifact,
            grain,
            class,
            at_version: self.at_version.clone(),
            // A hash present at this point came from the writer, directly or
            // as content the engine hashed. The backfill stamps its own.
            hash_source: hash.is_some().then_some(AnchorHashSource::Author),
            hash,
            hash_stability,
            derived_from: self.derived_from.clone().unwrap_or_default(),
            binding: self
                .binding
                .as_deref()
                .map(str::trim)
                .filter(|s| !s.is_empty())
                .map(str::to_string),
            source,
            span,
            span_hash,
            span_unvalidated,
            last_observed: None,
        })
    }
}

// ---------------------------------------------------------------------------
// Prepared-content hash
// ---------------------------------------------------------------------------

/// Compute the **prepared-content hash** of a path-grain artifact's bytes —
/// the value [`Anchor::hash`] records and hash-drift adjudication compares.
///
/// The prepared form is a deliberate, minimal canonicalization that keeps the
/// hash stable across meaningless byte noise while preserving every
/// content-bearing byte. For UTF-8 text:
///
/// - a leading BOM (U+FEFF) is stripped;
/// - CRLF / lone-CR line endings normalize to LF;
/// - trailing newlines are trimmed (final-newline presence is noise).
///
/// Interior whitespace is untouched — trailing spaces inside a line can be
/// content (markdown hard breaks), so only the two classic cross-tool noise
/// sources (encoding marks, line-ending convention) and the final-newline
/// question are canonicalized. Non-UTF-8 (binary) bytes hash as-is — no text
/// canonicalization applies to them.
///
/// The hash form reuses the house convention — SHA-256, lowercase hex,
/// truncated to 16 characters — shared by entity content hashes
/// ([`crate::entity::parser::compute_hash`]) and the change-detection digest
/// aggregate, so the engine keeps one hash shape rather than growing a
/// second normalization.
pub fn prepared_content_hash(bytes: &[u8]) -> String {
    use sha2::{Digest as _, Sha256};
    let digest = match std::str::from_utf8(bytes) {
        Ok(text) => {
            let text = text.strip_prefix('\u{feff}').unwrap_or(text);
            let normalized = text.replace("\r\n", "\n").replace('\r', "\n");
            Sha256::digest(normalized.trim_end_matches('\n').as_bytes())
        }
        Err(_) => Sha256::digest(bytes),
    };
    crate::hex_lower(&digest)[..16].to_string()
}

/// One verify-observed prepared-content hash, addressed to the anchor(s) it
/// backfills: the `(entity, artifact)` pair a hash-less hash-bearing anchor
/// is keyed by in the sidecar, plus the hash the observation computed. The
/// verify pass collects these; the engine's sidecar writer records them.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ObservedArtifactHash {
    /// The entity id (`mem--slug`) whose anchor the hash belongs to.
    pub entity: String,
    /// The anchor's artifact reference, exactly as stored.
    pub artifact: String,
    /// The prepared-content hash observed for the artifact.
    pub hash: String,
}

// ---------------------------------------------------------------------------
// Supplied observations
// ---------------------------------------------------------------------------

/// Typed code for a malformed supplied observation row.
pub const INVALID_OBSERVATION_CODE: &str = "INVALID_OBSERVATION";

/// One observer-supplied observation row, as it arrives on the wire
/// (`memstead verify-anchors --observations`): permissive and string-typed
/// so a malformed row refuses with a typed [`ObservationValidationError`]
/// before any state changes. The engine never fetches; for a grain it
/// cannot observe itself (`url`) this is how an observation enters the one
/// resolution funnel.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct SuppliedObservationInput {
    /// The anchor's artifact reference, exactly as stored (a URL for a
    /// `url` row).
    #[serde(default)]
    pub artifact: Option<String>,
    /// The prepared-content hash the observer computed. Exactly one of
    /// `hash`, `content`, `absent: true`.
    #[serde(default)]
    pub hash: Option<String>,
    /// The observed artifact CONTENT (UTF-8 text); the engine hashes it
    /// under the same canonicalization the write path applies to a `url`
    /// anchor's `content`.
    #[serde(default)]
    pub content: Option<String>,
    /// The observer could not retrieve the artifact.
    #[serde(default)]
    pub absent: Option<bool>,
    /// When the observation was made (ISO-8601 UTC, `YYYY-MM-DDTHH:MM:SSZ`
    /// or a bare `YYYY-MM-DD`). Defaults to the engine's clock at the run.
    #[serde(default)]
    pub observed_at: Option<String>,
}

/// What an observer saw for one artifact.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SuppliedOutcome {
    /// The artifact was retrieved; `hash` is its prepared-content hash
    /// under the default canonicalization, and `content` the retrieved text
    /// when the observer supplied it rather than a hash — kept so the
    /// resolution site can re-prepare it under the anchor's source
    /// preparation (a `quoted-phrase` url anchor is adjudicated on the
    /// phrase, not on the whole page), exactly as the write path does for
    /// an anchor's `content`.
    Present {
        hash: String,
        content: Option<String>,
    },
    /// The observer could not retrieve the artifact.
    Absent,
}

/// A validated supplied observation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SuppliedObservation {
    pub artifact: String,
    /// ISO-8601 timestamp of the observation.
    pub at: String,
    pub outcome: SuppliedOutcome,
}

/// Why a supplied observation row was refused.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum ObservationValidationError {
    #[error("observation row {row}: `artifact` is required and must be non-empty")]
    MissingArtifact { row: usize },
    #[error(
        "observation row {row} (`{artifact}`): give exactly one of `hash`, `content`, or \
         `absent: true`"
    )]
    OutcomeAmbiguous { row: usize, artifact: String },
    #[error(
        "observation row {row} (`{artifact}`): `observed_at` '{got}' is not an ISO-8601 \
         timestamp (`YYYY-MM-DDTHH:MM:SSZ`) or date (`YYYY-MM-DD`)"
    )]
    BadTimestamp {
        row: usize,
        artifact: String,
        got: String,
    },
    #[error("observation rows name `{artifact}` more than once (rows {first} and {second})")]
    DuplicateArtifact {
        artifact: String,
        first: usize,
        second: usize,
    },
}

impl ObservationValidationError {
    /// The stable typed code — always [`INVALID_OBSERVATION_CODE`].
    pub fn code(&self) -> &'static str {
        INVALID_OBSERVATION_CODE
    }

    /// Structured recovery detail for the typed envelope.
    pub fn detail(&self) -> BTreeMap<String, serde_json::Value> {
        let mut d = BTreeMap::new();
        match self {
            ObservationValidationError::MissingArtifact { row } => {
                d.insert("row".into(), serde_json::json!(row));
                d.insert("field".into(), "artifact".into());
            }
            ObservationValidationError::OutcomeAmbiguous { row, artifact } => {
                d.insert("row".into(), serde_json::json!(row));
                d.insert("artifact".into(), serde_json::json!(artifact));
                d.insert(
                    "expected".into(),
                    serde_json::json!("exactly one of `hash`, `content`, `absent: true`"),
                );
            }
            ObservationValidationError::BadTimestamp { row, artifact, got } => {
                d.insert("row".into(), serde_json::json!(row));
                d.insert("artifact".into(), serde_json::json!(artifact));
                d.insert("field".into(), "observed_at".into());
                d.insert("got".into(), serde_json::json!(got));
            }
            ObservationValidationError::DuplicateArtifact {
                artifact,
                first,
                second,
            } => {
                d.insert("artifact".into(), serde_json::json!(artifact));
                d.insert("rows".into(), serde_json::json!([first, second]));
            }
        }
        d
    }
}

/// Accept `YYYY-MM-DD` or `YYYY-MM-DDTHH:MM:SSZ` (any `T…Z` time part of the
/// second-granularity form).
fn timestamp_is_wellformed(ts: &str) -> bool {
    let b = ts.as_bytes();
    let date_ok = b.len() >= 10
        && b[..10].iter().enumerate().all(|(i, c)| {
            if i == 4 || i == 7 {
                *c == b'-'
            } else {
                c.is_ascii_digit()
            }
        });
    if !date_ok {
        return false;
    }
    if b.len() == 10 {
        return true;
    }
    b.len() == 20
        && b[10] == b'T'
        && b[19] == b'Z'
        && b[11..19].iter().enumerate().all(|(i, c)| {
            if i == 2 || i == 5 {
                *c == b':'
            } else {
                c.is_ascii_digit()
            }
        })
}

/// Validate a batch of supplied observation rows; all-or-nothing, so a
/// malformed row refuses before any state changes. `now` is the timestamp
/// stamped on rows that carry no `observed_at`. Returns the observations
/// keyed by artifact.
pub fn validate_supplied_observations(
    rows: &[SuppliedObservationInput],
    now: &str,
) -> Result<BTreeMap<String, SuppliedObservation>, ObservationValidationError> {
    let mut out: BTreeMap<String, SuppliedObservation> = BTreeMap::new();
    let mut first_row: BTreeMap<String, usize> = BTreeMap::new();
    for (i, row) in rows.iter().enumerate() {
        let n = i + 1;
        let artifact = row
            .artifact
            .as_deref()
            .map(str::trim)
            .filter(|s| !s.is_empty())
            .ok_or(ObservationValidationError::MissingArtifact { row: n })?
            .to_string();
        let absent = row.absent.unwrap_or(false);
        let given = usize::from(row.hash.is_some())
            + usize::from(row.content.is_some())
            + usize::from(absent);
        if given != 1 {
            return Err(ObservationValidationError::OutcomeAmbiguous { row: n, artifact });
        }
        let at = match row.observed_at.as_deref().map(str::trim) {
            None | Some("") => now.to_string(),
            Some(ts) if timestamp_is_wellformed(ts) => ts.to_string(),
            Some(ts) => {
                return Err(ObservationValidationError::BadTimestamp {
                    row: n,
                    artifact,
                    got: ts.to_string(),
                });
            }
        };
        if let Some(first) = first_row.get(&artifact) {
            return Err(ObservationValidationError::DuplicateArtifact {
                artifact,
                first: *first,
                second: n,
            });
        }
        let outcome = if absent {
            SuppliedOutcome::Absent
        } else if let Some(hash) = &row.hash {
            SuppliedOutcome::Present {
                hash: hash.trim().to_string(),
                content: None,
            }
        } else {
            let content = row.content.clone().unwrap_or_default();
            SuppliedOutcome::Present {
                hash: prepared_content_hash(content.as_bytes()),
                content: Some(content),
            }
        };
        first_row.insert(artifact.clone(), n);
        out.insert(
            artifact.clone(),
            SuppliedObservation {
                artifact,
                at,
                outcome,
            },
        );
    }
    Ok(out)
}

/// Days since the Unix epoch of an ISO timestamp's date part, for aging a
/// recorded observation (`unobserved for N days`). `None` when the string
/// does not start with a well-formed `YYYY-MM-DD`.
pub fn iso_days_since_epoch(ts: &str) -> Option<i64> {
    if !timestamp_is_wellformed(ts) {
        return None;
    }
    let y: i64 = ts[..4].parse().ok()?;
    let m: u32 = ts[5..7].parse().ok()?;
    let d: u32 = ts[8..10].parse().ok()?;
    if !(1..=12).contains(&m) || !(1..=31).contains(&d) {
        return None;
    }
    let y = if m <= 2 { y - 1 } else { y };
    let era = if y >= 0 { y } else { y - 399 } / 400;
    let yoe = y - era * 400;
    let mp = ((m + 9) % 12) as i64;
    let doy = (153 * mp + 2) / 5 + d as i64 - 1;
    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
    Some(era * 146097 + doe - 719468)
}

/// Whole days between a recorded observation and `now` (both ISO), floored
/// at zero; `None` when either fails to parse.
pub fn days_between(observed_at: &str, now: &str) -> Option<u64> {
    let a = iso_days_since_epoch(observed_at)?;
    let b = iso_days_since_epoch(now)?;
    Some((b - a).max(0) as u64)
}

// ---------------------------------------------------------------------------
// Resolution
// ---------------------------------------------------------------------------

/// The resolved state of one anchor against the current medium.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum AnchorState {
    /// The artifact is present and matches (hash equal, or a non-hash
    /// class whose artifact still exists).
    Resolves,
    /// The artifact is present but its prepared-content hash differs and
    /// the medium is `stable` — a real content drift.
    Drifted,
    /// The artifact is present but drift cannot be asserted — the medium
    /// is `unstable`, or the hash is unavailable on one side. Flagged for
    /// re-examination, never reported as drift.
    Recheck,
    /// The artifact the anchor references is no longer present in the
    /// medium.
    Orphaned,
    /// The artifact is present but the words the row quotes (its `span`)
    /// no longer occur in it. The claim's basis is gone while the document
    /// stands: not `drifted` (the row's claim is the span, not the page)
    /// and not `orphaned` (the artifact is there). Only a row carrying a
    /// span can read this.
    #[serde(rename = "span_absent")]
    SpanAbsent,
}

impl AnchorState {
    /// Every state, in the order the vocabulary is documented. The one
    /// list; a new variant must join it (the match in [`Self::describe`]
    /// refuses to compile without it, and [`Self::vocabulary_help`] and the
    /// round-trip test read it).
    pub const ALL: [AnchorState; 5] = [
        AnchorState::Resolves,
        AnchorState::Drifted,
        AnchorState::Recheck,
        AnchorState::Orphaned,
        AnchorState::SpanAbsent,
    ];

    /// Stable wire form.
    pub fn as_wire(&self) -> &'static str {
        match self {
            AnchorState::Resolves => "resolves",
            AnchorState::Drifted => "drifted",
            AnchorState::Recheck => "recheck",
            AnchorState::Orphaned => "orphaned",
            AnchorState::SpanAbsent => "span_absent",
        }
    }

    /// The one-line meaning of each state — the documentation every
    /// surface that names the vocabulary reads from (the CLI help and the
    /// reference rendered from it, [`Self::vocabulary_help`]).
    pub fn describe(&self) -> &'static str {
        match self {
            AnchorState::Resolves => "the artifact is present and matches",
            AnchorState::Drifted => {
                "present, hash differs, the medium is stable, so a real content drift"
            }
            AnchorState::Recheck => {
                "present, but drift cannot be asserted (unstable medium, or a hash missing on one side)"
            }
            AnchorState::Orphaned => "the artifact the anchor references is gone from the medium",
            AnchorState::SpanAbsent => {
                "present, but the words the row quotes (its span) no longer occur in it"
            }
        }
    }

    /// The vocabulary as a help paragraph, one line per state, rendered
    /// from [`Self::ALL`] and [`Self::describe`] so a surface never carries
    /// its own list of states.
    pub fn vocabulary_help() -> String {
        let mut s = String::from("Anchor states (the artifact end of an anchor):\n");
        for state in Self::ALL {
            s.push_str(&format!("  {:<11} {}\n", state.as_wire(), state.describe()));
        }
        s.push_str(
            "Not states: `dangling` (a sidecar row whose entity the mem no longer holds) and \
             `unobserved` (the pass did not reach the artifact) are conditions of the \
             measurement, counted apart.",
        );
        s
    }
}

/// The positive anchor resolution figure, carried with the population it
/// was computed over. A resolution count read on its own is read as
/// health, and every W3 finding of the 2026-08 consistency sweep was a bare
/// figure that meant less than it looked; this type makes the defect a
/// construction error instead of a lint finding. It cannot be built
/// without a population statement, it prints only through [`Display`]
/// (the count and the statement in one sentence) or [`Self::ratio`], and
/// its serde form carries the three fields together, so no renderer, JSON
/// or markdown, reaches the raw count.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(try_from = "RawFigure")]
pub struct AnchorResolutionFigure {
    /// Anchors that resolved clean.
    resolves: usize,
    /// What the figure was computed over and how much of it the pass could
    /// not adjudicate. Never empty.
    population: String,
    /// Whether the pass adjudicated everything it counted.
    fully_adjudicated: bool,
}

/// The wire shape [`AnchorResolutionFigure`] deserializes through, so a
/// figure read back from JSON without a population is refused too.
#[derive(Deserialize)]
struct RawFigure {
    resolves: usize,
    population: String,
    fully_adjudicated: bool,
}

/// The one construction refusal: a figure with no population statement.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("an anchor resolution figure cannot exist without the population it was computed over")]
pub struct FigureWithoutPopulation;

impl TryFrom<RawFigure> for AnchorResolutionFigure {
    type Error = FigureWithoutPopulation;
    fn try_from(raw: RawFigure) -> Result<Self, Self::Error> {
        Self::new(raw.resolves, raw.population, raw.fully_adjudicated)
    }
}

impl AnchorResolutionFigure {
    /// The only constructor: refuses an empty population statement.
    pub fn new(
        resolves: usize,
        population: impl Into<String>,
        fully_adjudicated: bool,
    ) -> Result<Self, FigureWithoutPopulation> {
        let population = population.into();
        if population.trim().is_empty() {
            return Err(FigureWithoutPopulation);
        }
        Ok(Self {
            resolves,
            population,
            fully_adjudicated,
        })
    }

    /// The figure of a pass that counted nothing because it could not
    /// read its rows: zero, with the reason as its population. The reason
    /// is the statement, so it is checked like any other.
    pub(crate) fn uncounted(why: impl Into<String>) -> Self {
        Self::new(0, why, false).expect("an uncounted figure names why it counted nothing")
    }

    /// What the count was computed over.
    pub fn population(&self) -> &str {
        &self.population
    }

    /// Whether the pass adjudicated everything it counted.
    pub fn fully_adjudicated(&self) -> bool {
        self.fully_adjudicated
    }

    /// The count as a ratio over `denominator`, followed by the population:
    /// `388/422 (91.9%) over 424 counted row(s) …`. The percentage never
    /// travels without the statement.
    pub fn ratio(&self, denominator: usize) -> String {
        if denominator == 0 {
            format!("{}/{denominator} (n/a) {}", self.resolves, self.population)
        } else {
            let pct = (self.resolves as f64) * 100.0 / (denominator as f64);
            format!(
                "{}/{denominator} ({pct:.1}%) {}",
                self.resolves, self.population
            )
        }
    }

    /// Read a figure back from a JSON object that carries the three fields
    /// (`resolves`, `population`, `fully_adjudicated`) — the shape every
    /// surface serializes — so a renderer of JSON prints through the type
    /// too. `None` when a field is missing or the population is empty.
    pub fn from_json(v: &serde_json::Value) -> Option<Self> {
        Self::new(
            v.get("resolves")?.as_u64()? as usize,
            v.get("population")?.as_str()?,
            v.get("fully_adjudicated")?.as_bool()?,
        )
        .ok()
    }

    /// The bare count, for a test assertion and nothing else: a renderer
    /// prints through [`Display`] or [`Self::ratio`]. Compiled for tests
    /// only (this crate's own, or a downstream crate's under the
    /// `test-support` feature), so no shipping code can reach it.
    #[cfg(any(test, feature = "test-support"))]
    pub fn count_for_assertions(&self) -> usize {
        self.resolves
    }
}

impl Default for AnchorResolutionFigure {
    fn default() -> Self {
        Self::uncounted("population unknown: no row was counted")
    }
}

impl std::fmt::Display for AnchorResolutionFigure {
    /// The count and its population in one sentence: `388 over 424 counted
    /// row(s): 422 adjudicated, 2 not (…)`.
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{} {}", self.resolves, self.population)
    }
}

/// What the engine observed about an anchor's artifact when resolving.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ArtifactObservation {
    /// The artifact could not be found in the medium.
    Absent,
    /// The artifact is present; `current_hash` is its prepared-content
    /// hash when the medium could compute one (`None` when the medium has
    /// no hash for it this pass — e.g. enumeration without preparation).
    Present { current_hash: Option<String> },
}

/// Resolve one anchor against a current observation, honouring the class's
/// hash semantics and the medium's declared stability.
///
/// - `authored` / `informed-by` are excluded from hash-drift adjudication:
///   they [`Resolves`](AnchorState::Resolves) as long as the artifact
///   exists, [`Orphaned`](AnchorState::Orphaned) when it does not — a
///   content change never produces a drift state for them.
/// - `anchored` / `derived` compare the recorded prepared-content hash to
///   the current one: equal ⇒ resolves; different ⇒ `drifted` on a stable
///   medium, `recheck` on an unstable one; unavailable on either side ⇒
///   `recheck` (cannot adjudicate).
pub fn resolve_anchor(anchor: &Anchor, observation: &ArtifactObservation) -> AnchorState {
    let current_hash = match observation {
        ArtifactObservation::Absent => return AnchorState::Orphaned,
        ArtifactObservation::Present { current_hash } => current_hash,
    };
    // A row quoting a span is adjudicated on the span's presence
    // ([`resolve_span_anchor`]); a present observation that reaches here
    // for such a row carried no text to look in, so nothing can be asserted.
    if anchor.span.is_some() {
        return AnchorState::Recheck;
    }
    if !anchor.class.is_hash_bearing() {
        return AnchorState::Resolves;
    }
    match (&anchor.hash, current_hash) {
        (Some(recorded), Some(current)) if recorded == current => AnchorState::Resolves,
        (Some(_), Some(_)) => match anchor.hash_stability {
            AnchorHashStability::Stable => AnchorState::Drifted,
            AnchorHashStability::Unstable => AnchorState::Recheck,
        },
        // Missing hash on either side — cannot adjudicate drift.
        _ => AnchorState::Recheck,
    }
}

/// Resolve a row that quotes a `span` against the observed TEXT of its
/// artifact: [`Resolves`](AnchorState::Resolves) while the span occurs in
/// the text (canonical span form), whatever the document's hash did, and
/// [`SpanAbsent`](AnchorState::SpanAbsent) once it does not. The document
/// hash is the observation's business (it is kept and shown as the row's
/// observed hash); the state answers the row's claim, which is the span.
/// A row without a span is not this function's to judge and resolves by
/// its hash ([`resolve_anchor`]).
pub fn resolve_span_anchor(anchor: &Anchor, text: &str) -> AnchorState {
    match anchor.span.as_deref() {
        Some(span) if crate::preparation::span_occurs(span, text) => AnchorState::Resolves,
        Some(_) => AnchorState::SpanAbsent,
        None => AnchorState::Recheck,
    }
}

/// Per-entity provenance-class + grain composition, computed from an
/// entity's anchor list. Tree-grain fan-out is surfaced distinctly so a
/// single entity anchored to a large tree is never laundered into
/// full per-file credit — the count of tree anchors is visible on its own
/// axis, and downstream reads the fan-out counts from resolution.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct EntityAnchorComposition {
    /// Anchor count keyed by provenance-class wire string.
    pub by_class: BTreeMap<String, usize>,
    /// Anchor count keyed by grain wire string.
    pub by_grain: BTreeMap<String, usize>,
    /// The `derived_from` input lists of every `derived` anchor, in
    /// anchor order: the derived-input provenance.
    pub derived_inputs: Vec<Vec<String>>,
    /// Artifact refs of every `tree`-grain anchor — the fan-out axis. A
    /// tree anchor is one row here regardless of how many files the tree
    /// contains; the file count is an observation resolution supplies, not
    /// a credit this composition grants.
    pub tree_grain_artifacts: Vec<String>,
}

/// Compose an entity's anchors into class/grain counts, derived inputs,
/// and the tree-grain fan-out axis.
pub fn compose_entity_anchors(anchors: &[Anchor]) -> EntityAnchorComposition {
    let mut comp = EntityAnchorComposition::default();
    for a in anchors {
        *comp
            .by_class
            .entry(a.class.as_wire().to_string())
            .or_insert(0) += 1;
        *comp
            .by_grain
            .entry(a.grain.as_wire().to_string())
            .or_insert(0) += 1;
        if a.class == AnchorProvenanceClass::Derived {
            comp.derived_inputs.push(a.derived_from.clone());
        }
        if a.grain == AnchorGrain::Tree {
            comp.tree_grain_artifacts.push(a.artifact.clone());
        }
    }
    comp
}

// ---------------------------------------------------------------------------
// Sidecar document
// ---------------------------------------------------------------------------

/// The engine-owned anchors sidecar document persisted at
/// [`ANCHOR_SIDECAR_PATH`] on the mem branch: entity id → its anchors.
///
/// Written only through engine commits (the [`crate::backend::MemBackend`]
/// sidecar seam). Rename rewrites the key atomically in the same commit as
/// the entity move; delete drops the key in the same commit as the entity
/// delete.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AnchorSidecar {
    /// Document schema version.
    pub version: u32,
    /// Entity id (`mem--slug`) → its anchors. An entity with no anchors
    /// carries no key (an empty vec is pruned on write).
    #[serde(default)]
    pub entities: BTreeMap<String, Vec<Anchor>>,
}

impl Default for AnchorSidecar {
    fn default() -> Self {
        Self {
            version: ANCHOR_SIDECAR_VERSION,
            entities: BTreeMap::new(),
        }
    }
}

impl AnchorSidecar {
    /// Parse sidecar bytes; an absent/empty payload yields an empty
    /// document so callers need not special-case a fresh mem.
    pub fn from_bytes(bytes: &[u8]) -> Result<Self, serde_json::Error> {
        if bytes.iter().all(u8::is_ascii_whitespace) {
            return Ok(Self::default());
        }
        let sidecar: Self = serde_json::from_slice(bytes)?;
        // The version field is a contract, not decoration. Every sibling
        // store refuses an unknown one — the binding record with
        // `UNKNOWN_BINDING_VERSION`, the workspace stores with
        // `WORKSPACE_STORE_FORMAT_MISMATCH` — and this one silently accepted
        // it, so a sidecar written by a future engine parsed as whatever
        // today's field names happened to match and verified CLEAN. Reading
        // an unknown format optimistically is how a measurement ends up
        // confidently describing something it does not understand.
        if !ANCHOR_SIDECAR_VERSIONS_READ.contains(&sidecar.version) {
            return Err(serde::de::Error::custom(format!(
                "unsupported anchors sidecar version {} (this engine reads versions {}) — \
                 the file was written by a different engine; upgrade, or remove the sidecar \
                 to re-record anchors",
                sidecar.version,
                ANCHOR_SIDECAR_VERSIONS_READ
                    .iter()
                    .map(u32::to_string)
                    .collect::<Vec<_>>()
                    .join(", ")
            )));
        }
        // An older readable version is upgraded in memory: the rows are
        // unchanged (a version-2 field is simply absent on them) and the
        // next write persists the version the rows require: version 2
        // unless a row carries a span or a pinned hash source.
        let mut sidecar = sidecar;
        sidecar.version = sidecar.required_version();
        Ok(sidecar)
    }

    /// The version this document's rows require: [`ANCHOR_SIDECAR_SPAN_VERSION`]
    /// once any row carries a quoted `span` or a `pinned` hash source (the
    /// two things an engine reading only versions 1 and 2 cannot
    /// understand), [`ANCHOR_SIDECAR_VERSION`] otherwise. The version moves
    /// only when such a row is written, so a sidecar written before spans
    /// existed re-saves with the version it had.
    pub fn required_version(&self) -> u32 {
        let needs_v3 = self
            .entities
            .values()
            .flatten()
            .any(|a| a.span.is_some() || a.hash_source == Some(AnchorHashSource::Pinned));
        if needs_v3 {
            ANCHOR_SIDECAR_SPAN_VERSION
        } else {
            ANCHOR_SIDECAR_VERSION
        }
    }

    /// Serialise to canonical pretty JSON with a trailing newline —
    /// diff-friendly on the mem branch. The written `version` is
    /// [`Self::required_version`], whatever the in-memory field says.
    pub fn to_bytes(&self) -> Vec<u8> {
        #[derive(Serialize)]
        struct Wire<'a> {
            version: u32,
            entities: &'a BTreeMap<String, Vec<Anchor>>,
        }
        let wire = Wire {
            version: self.required_version(),
            entities: &self.entities,
        };
        let mut s = serde_json::to_string_pretty(&wire).expect("anchor sidecar serialises");
        s.push('\n');
        s.into_bytes()
    }

    /// The anchors recorded for `entity_id`, or an empty slice.
    pub fn get(&self, entity_id: &str) -> &[Anchor] {
        self.entities
            .get(entity_id)
            .map(Vec::as_slice)
            .unwrap_or(&[])
    }

    /// Replace `entity_id`'s anchors. An empty list prunes the key so the
    /// sidecar never accumulates empty rows.
    pub fn set(&mut self, entity_id: &str, anchors: Vec<Anchor>) {
        if anchors.is_empty() {
            self.entities.remove(entity_id);
        } else {
            self.entities.insert(entity_id.to_string(), anchors);
        }
    }

    /// Merge `incoming` into `entity_id`'s anchor row after applying
    /// `unsets` — the write-path set arithmetic.
    ///
    /// Unset applies **first**: each selector removes its matching anchors
    /// (a selector matching nothing is a no-op). Then each incoming anchor
    /// **replaces** the surviving anchor with the same
    /// `(artifact, grain, class, span)` identity in place, and **appends**
    /// otherwise — untouched anchors keep their bytes and their position.
    /// The span is part of the identity: two spans on one document are two
    /// rows, and a re-pin that omits the span never touches a span row.
    /// Writing anchors never removes an anchor the call did not name in
    /// `unsets`; an empty `incoming` merges nothing. A row emptied by
    /// unsets prunes its key so the sidecar never accumulates empty rows.
    pub fn merge(
        &mut self,
        entity_id: &str,
        unsets: &[AnchorUnset],
        incoming: Vec<Anchor>,
        rebaseline: bool,
    ) -> bool {
        let mut row = self.entities.remove(entity_id).unwrap_or_default();
        let before = row.len();
        row.retain(|a| !unsets.iter().any(|u| u.matches(a)));
        let mut changed = row.len() != before;
        for anchor in incoming {
            match row.iter_mut().find(|e| {
                e.artifact == anchor.artifact
                    && e.grain == anchor.grain
                    && e.class == anchor.class
                    && same_span(e.span.as_deref(), anchor.span.as_deref())
            }) {
                Some(existing) => {
                    // The same triple replaces the row. A row identical to the stored one on every
                    // caller-supplied field is a no-op: nothing is written
                    // and the caller hears so. Otherwise the stored row goes,
                    // baseline included: a re-pin that names no hash is
                    // written hash-less for the next verify to backfill
                    // against the artifact as it now is, which is what a
                    // re-pin after a sync repair means. A caller who
                    // supplies a hash sets that baseline directly. (The
                    // 2026-08 consistency sweep carried the stored baseline
                    // forward instead, which left every one-update repair
                    // reading `drifted` against the content it had just
                    // repaired; the re-pin is itself recorded, so nothing is
                    // lost by re-baselining.)
                    // `rebaseline` is the update that also rewrote the
                    // entity's content (a sync repair): its anchors were
                    // drawn from the artifact as it now is, so a restated
                    // row still moves the baseline; on an anchors-only
                    // update a restated row is a no-op.
                    if !rebaseline && existing.same_as_supplied(&anchor) {
                        continue;
                    }
                    *existing = anchor;
                    changed = true;
                }
                None => {
                    row.push(anchor);
                    changed = true;
                }
            }
        }
        if !row.is_empty() {
            self.entities.insert(entity_id.to_string(), row);
        }
        changed
    }

    /// Blank every artifact reference — `artifact` and each `derived_from`
    /// entry — to [`REDACTED_ARTIFACT_SENTINEL`], keeping everything else:
    /// class, grain, `at_version`, hash, hash-stability, binding, source,
    /// and the per-entity anchor counts. Redact, not strip: a consumer
    /// still reads *how strongly* each entity claims fidelity to a source
    /// without learning *which* source. Publish-time only by design — no
    /// engine path calls this against workspace state.
    pub fn redact_artifact_references(&mut self) {
        for anchors in self.entities.values_mut() {
            for anchor in anchors {
                anchor.artifact = REDACTED_ARTIFACT_SENTINEL.to_string();
                for input in &mut anchor.derived_from {
                    *input = REDACTED_ARTIFACT_SENTINEL.to_string();
                }
            }
        }
    }

    /// Structural check on artifact references: every `artifact` and every
    /// `derived_from` entry must be non-empty. The mutation surface never
    /// admits an empty reference (`INVALID_ANCHOR`), so a sidecar carrying
    /// one is corruption — including a botched redaction that blanked to
    /// nothing instead of the pinned sentinel. Returns the first offence.
    pub fn validate_artifact_references(&self) -> Result<(), String> {
        for (entity_id, anchors) in &self.entities {
            for anchor in anchors {
                if anchor.artifact.trim().is_empty() {
                    return Err(format!(
                        "entity `{entity_id}` carries an anchor with an empty artifact \
                         reference"
                    ));
                }
                if anchor.derived_from.iter().any(|d| d.trim().is_empty()) {
                    return Err(format!(
                        "entity `{entity_id}` carries an anchor with an empty \
                         `derived_from` entry"
                    ));
                }
            }
        }
        Ok(())
    }

    /// Drop `entity_id`'s anchors entirely (delete leg). Idempotent.
    pub fn remove(&mut self, entity_id: &str) {
        self.entities.remove(entity_id);
    }

    /// Move `from`'s anchors to `to` (rename leg), leaving zero rows under
    /// the old id. No-op when `from` has no anchors. When `to` already has
    /// anchors they are overwritten — a rename onto a live id is refused
    /// upstream, so this is the residual-stub case only.
    pub fn rename(&mut self, from: &str, to: &str) {
        if let Some(anchors) = self.entities.remove(from) {
            self.entities.insert(to.to_string(), anchors);
        }
    }

    /// Whether the document holds no anchors for any entity.
    pub fn is_empty(&self) -> bool {
        self.entities.is_empty()
    }
}

#[cfg(test)]
mod figure_and_vocabulary;
#[cfg(test)]
mod tests;