memstead-base 0.26.1

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
//! Check records — the engine-recorded act of verification.
//!
//! A check is an agent recording "entity E checked, verdict ok |
//! failed, via method M". It is engine state, never entity content:
//! absent from markdown and `content_hash`, and it produces no mem
//! commit — checking-touches-nothing is what makes check-staleness
//! computable. Records are append-only JSONL under the workspace
//! store (`.memstead/state/checks/checks.jsonl`); a newer check of
//! the same kind supersedes older ones for state derivation but
//! never erases them (kinds derive independently, see [`CheckKind`]).
//!
//! Unlike the friction ledger next door, recording here is NOT
//! best-effort: a check the ledger failed to persist must refuse —
//! the caller believes the act was recorded, and a silently dropped
//! check is exactly the self-report dishonesty this tier exists to
//! end. For the same reason there is no rotation cap: check history
//! is the substrate process state derives from, not disposable
//! telemetry.
//!
//! Each record carries provenance (actor, client, declared
//! role) plus the entity's `content_hash` at check time. State
//! derivation compares that hash against the current one:
//!
//! - no record            → `never_checked`
//! - hash matches, ok     → `checked_ok`
//! - hash matches, failed → `check_failed`
//! - hash differs         → `check_stale` (whatever the verdict was,
//!   it no longer speaks to the current content — stated, never
//!   silently carried forward)
//!
//! A `conformance` record additionally carries the mem's schema pin
//! and goes stale when the pin moves ([`derive_state_pinned`]): the
//! prose it judged against is no longer the prose in force.

use std::collections::BTreeMap;
use std::io::Write;
use std::path::{Path, PathBuf};

use serde::{Deserialize, Serialize};

/// The closed verdict vocabulary. Nuance goes in the method note or
/// in process-mem entities — never in new verdict values.
pub const VERDICTS: [&str; 2] = ["ok", "failed"];

/// The closed kind vocabulary. `verification` is the default and
/// today's behaviour: "I checked this entity's content". `conformance`
/// is the semantic judgment "this entity satisfies its type's
/// schema prose (`write_rules` / `writing_guidance`)" — recorded with
/// the mem's schema pin, stamped by the engine at record time, so the
/// verdict's freshness against both the content AND the prose version
/// stays computable. A third kind is a separate decision; closed
/// kinds keep health aggregation well-defined, matching the closed
/// verdict vocabulary.
pub const CHECK_KINDS: [&str; 2] = ["verification", "conformance"];

/// Prefix of a caller-declared check kind the engine records verbatim
/// and never interprets: `x-<name>`, `name` lowercase letters, digits
/// and hyphens. The prefix makes the declaration deliberate — a typo of
/// an engine kind cannot silently become a new kind — mirroring the
/// rule that a third ENGINE kind is a separate decision. Foreign kinds
/// never influence `check_state`; health lists them by count.
pub const FOREIGN_KIND_PREFIX: &str = "x-";

/// The typed code for a malformed finding.
pub const INVALID_CHECK_FINDING_CODE: &str = "INVALID_CHECK_FINDING";

/// A batch of checks refused whole because entries failed validation;
/// nothing is recorded. Each failed entry carries its index, its id and
/// the typed errors it met.
#[derive(Debug, Clone, thiserror::Error)]
#[error(
    "batch check refused: {} of {total} entr(ies) failed validation, nothing recorded",
    failed_entries.len()
)]
pub struct CheckBatchRefused {
    pub failed_entries: Vec<serde_json::Value>,
    pub total: usize,
}

impl CheckBatchRefused {
    pub fn code(&self) -> &'static str {
        "BATCH_REFUSED"
    }

    pub fn details(&self) -> serde_json::Value {
        serde_json::json!({ "failed_entries": self.failed_entries })
    }
}

/// A check kind from the closed vocabulary.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CheckKind {
    Verification,
    Conformance,
}

/// What a caller may declare as a check's kind: one of the engine's
/// two kinds, or a foreign `x-<name>` kind recorded verbatim.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RecordKind {
    Engine(CheckKind),
    Foreign(String),
}

impl RecordKind {
    /// Parse a wire kind: an engine kind, an `x-` kind (name non-empty,
    /// lowercase letters, digits and hyphens), or `None` for anything
    /// else — the vocabulary the refusal names is [`CHECK_KINDS`] plus
    /// the `x-<name>` form.
    pub fn from_wire(s: &str) -> Option<Self> {
        if let Some(k) = CheckKind::from_wire(s) {
            return Some(Self::Engine(k));
        }
        // ONE grammar, declared beside the schema's constraint
        // vocabulary so a `transition_requires_self_check` declaration
        // and a recorded check agree on what a kind may look like.
        s.starts_with(FOREIGN_KIND_PREFIX)
            .then(|| memstead_schema::check_kind_wire_is_well_formed(s))
            .filter(|ok| *ok)
            .map(|_| Self::Foreign(s.to_string()))
    }

    /// The engine kind, when this is one.
    pub fn engine_kind(&self) -> Option<CheckKind> {
        match self {
            Self::Engine(k) => Some(*k),
            Self::Foreign(_) => None,
        }
    }

    /// Stable wire form.
    pub fn as_wire(&self) -> &str {
        match self {
            Self::Engine(k) => k.as_str(),
            Self::Foreign(s) => s.as_str(),
        }
    }

    /// The vocabulary sentence a refusal carries.
    pub fn vocabulary_hint() -> String {
        format!(
            "{}, or a caller-declared `{FOREIGN_KIND_PREFIX}<name>` kind (lowercase letters, digits, hyphens) the engine records verbatim and never interprets",
            CHECK_KINDS.join(", ")
        )
    }
}

/// A structured finding riding a check record: WHAT failed (or what was
/// observed) in a locatable form, so a `failed` verdict never forces
/// the author to re-derive the failure from a free-text method note.
/// `code` in `UPPER_SNAKE` is the engine's namespace and must name a
/// health condition ([`crate::ops::strict::HEALTH_CONDITIONS`]); any
/// other spelling is the checker's own vocabulary. The wrapper shape is
/// fixed and refuses unknown keys.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CheckFinding {
    /// The checker's finding code (`hidden-premise`, `stale-source`, …).
    pub code: String,
    /// The section key the finding concerns, when it concerns one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub section: Option<String>,
    /// One or two sentences a reader can act on.
    pub message: String,
    /// What the finding rests on: a quote, a coordinate, a reference.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub evidence: Option<String>,
}

impl CheckFinding {
    /// The shape sentence every refusal names.
    pub const SHAPE: &'static str =
        "{code: <non-empty>, message: <non-empty>, section?: <key>, evidence?: <text>}";

    /// `code` and `message` are required and non-empty; `section` and
    /// `evidence`, when present, are non-empty too.
    pub fn validate(&self) -> Result<(), String> {
        if self.code.trim().is_empty() {
            return Err(format!(
                "finding.code is required and must be non-empty — shape {}",
                Self::SHAPE
            ));
        }
        if self.message.trim().is_empty() {
            return Err(format!(
                "finding.message is required and must be non-empty — shape {}",
                Self::SHAPE
            ));
        }
        if self.section.as_deref().is_some_and(|s| s.trim().is_empty()) {
            return Err(format!(
                "finding.section, when given, must be non-empty — shape {}",
                Self::SHAPE
            ));
        }
        if self
            .evidence
            .as_deref()
            .is_some_and(|s| s.trim().is_empty())
        {
            return Err(format!(
                "finding.evidence, when given, must be non-empty — shape {}",
                Self::SHAPE
            ));
        }
        Ok(())
    }

    /// Parse and validate a finding from JSON (the CLI's `--finding` and
    /// batch entries, the MCP param). An unknown key, a missing required
    /// key, or an empty value is one typed refusal naming the shape.
    pub fn from_json(value: serde_json::Value) -> Result<Self, InvalidCheckFinding> {
        let finding: CheckFinding =
            serde_json::from_value(value).map_err(|e| InvalidCheckFinding {
                reason: format!("finding does not match the shape {} ({e})", Self::SHAPE),
            })?;
        finding
            .validate()
            .map_err(|reason| InvalidCheckFinding { reason })?;
        Ok(finding)
    }
}

/// A check finding that does not match its shape: one refusal, the same
/// on every surface, naming the shape it must match.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("{reason}")]
pub struct InvalidCheckFinding {
    pub reason: String,
}

impl InvalidCheckFinding {
    pub fn code(&self) -> &'static str {
        INVALID_CHECK_FINDING_CODE
    }

    pub fn details(&self) -> serde_json::Value {
        serde_json::json!({ "shape": CheckFinding::SHAPE })
    }
}

impl CheckKind {
    /// Parse a wire value; `None` for anything outside the vocabulary.
    pub fn from_wire(s: &str) -> Option<Self> {
        match s {
            "verification" => Some(Self::Verification),
            "conformance" => Some(Self::Conformance),
            _ => None,
        }
    }

    pub fn as_str(self) -> &'static str {
        match self {
            Self::Verification => "verification",
            Self::Conformance => "conformance",
        }
    }
}

/// A check verdict from the closed vocabulary.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Verdict {
    Ok,
    Failed,
}

impl Verdict {
    /// Parse a wire value; `None` for anything outside the vocabulary.
    pub fn from_wire(s: &str) -> Option<Self> {
        match s {
            "ok" => Some(Self::Ok),
            "failed" => Some(Self::Failed),
            _ => None,
        }
    }

    pub fn as_str(self) -> &'static str {
        match self {
            Self::Ok => "ok",
            Self::Failed => "failed",
        }
    }
}

/// The reason a record was carried to a new `entity_hash` by the engine
/// across a status transition it licensed ([`CheckLedger::carry_transition`]).
pub const CARRY_REASON_TRANSITION: &str = "transition";

/// The reason a sealed record was re-keyed to the archived entity bytes
/// at export ([`SealedChecks::rekey_entity`]).
pub const CARRY_REASON_EXPORT: &str = "export";

/// Set on a record the engine carried to a new `entity_hash`: the hash
/// the record was keyed to before, and why it moved. Two reasons exist.
/// `transition`: a status write passed a `transition_requires_self_check`
/// gate on the strength of this record, and the write itself moved the
/// entity's hash, so the record that licensed the write is re-keyed to
/// the content the write produced. `export`: a sealed export rewrote the
/// entity's bytes (a hierarchical mem's self-qualified links follow the
/// archive name, and the canonical re-pack re-renders every entity), so
/// a record fresh at export is re-keyed to the archived bytes. In both
/// cases only a record whose hash matched the pre-rewrite content moves;
/// a stale record keeps its old hash and stays stale. Every other field
/// is the original act's, identity included, so independence still reads
/// the record as the checker's.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CarriedFrom {
    /// The `entity_hash` the record carried before it was moved.
    pub hash: String,
    /// [`CARRY_REASON_TRANSITION`] or [`CARRY_REASON_EXPORT`].
    pub reason: String,
    /// On a transition carry: the line's place in its carry chain (1 for a
    /// line carried from a checker's own record, one more for each carry
    /// onward). A carried line supersedes only records of a lower depth,
    /// which orders a chain that returns to an earlier hash (two gated
    /// values on one field, written in one second) without a clock.
    /// Absent on export carries and on lines earlier engines wrote, which
    /// read as depth 1.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub depth: Option<u32>,
}

impl CarriedFrom {
    pub fn transition(hash: &str) -> Self {
        Self::transition_at(hash, 1)
    }

    /// A transition carry at `depth` in its chain.
    pub fn transition_at(hash: &str, depth: u32) -> Self {
        Self {
            hash: hash.to_string(),
            reason: CARRY_REASON_TRANSITION.to_string(),
            depth: Some(depth),
        }
    }

    /// The line's depth in its carry chain (see [`Self::depth`]).
    pub fn chain_depth(&self) -> u32 {
        self.depth.unwrap_or(1)
    }

    pub fn export(hash: &str) -> Self {
        Self {
            hash: hash.to_string(),
            reason: CARRY_REASON_EXPORT.to_string(),
            depth: None,
        }
    }
}

/// One recorded check — the full ledger line.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CheckRecord {
    /// Unix epoch seconds at record time: the engine's clock when the
    /// line was written, never caller-supplied.
    pub ts: u64,
    /// Unix epoch seconds at which the check was MADE, when the caller
    /// said so (`observed_at` on `memstead check`, a `--from` row and
    /// `memstead_check`): a recorder transcribing checks that were made
    /// earlier, or out of order, states the time of each act here and
    /// `ts` keeps the time of the transcription. It is the record's time
    /// of the act ([`CheckRecord::act_time`]: `observed_at` where present,
    /// `ts` otherwise), and the newest record of a kind is the one whose
    /// act is latest ([`CheckLedger::in_standing_order`]), never the one
    /// the ledger happens to hold last. Absent on every line written
    /// without it, so existing ledgers parse unchanged.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub observed_at: Option<u64>,
    /// Full entity id (`mem--slug`).
    pub entity: String,
    /// `ok` | `failed`.
    pub verdict: String,
    /// Optional free-text method note ("diffed against source spec",
    /// "re-ran the derivation").
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub method: Option<String>,
    /// The entity's `content_hash` at check time — the staleness
    /// baseline.
    pub entity_hash: String,
    /// Recorded actor identity (provenance).
    pub actor: String,
    /// Recorded client identity (`name@version`), when known.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub client: Option<String>,
    /// The caller-declared role, or `"unspecified"` — recorded
    /// honestly; downstream gates treat unspecified as
    /// cannot-confirm, never as any real role.
    pub role: String,
    /// The caller-declared identity: an opaque
    /// caller-chosen string, the ONLY comparator the independence
    /// gate uses. Absent on ledger lines written before identities
    /// existed and on identity-less callers — both downgrade every
    /// comparison to `unconfirmable`, never to a guessed category.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub identity: Option<String>,
    /// The check kind, from [`CHECK_KINDS`]. Absent on ledger lines
    /// written before kinds existed AND on freshly recorded
    /// `verification` checks — both read as `verification`, so an
    /// existing ledger upgrades with no migration and a kind-omitted
    /// caller's lines stay byte-identical to before.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub kind: Option<String>,
    /// For `conformance` records: the mem's schema pin
    /// (`name@x.y.z`) as stamped by the engine at record time — never
    /// caller-supplied, so a verdict cannot claim a prose version the
    /// caller never read. Absent on `verification` records.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub schema_ref: Option<String>,
    /// The structured finding the checker attached, when one was.
    /// Absent on every line written before findings existed and on
    /// finding-less checks — serde-default, so every existing line
    /// still parses and finding-less lines stay byte-identical.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub finding: Option<CheckFinding>,
    /// Set on a line the engine carried across a rename: the id the
    /// check was recorded under before the entity took its current id.
    /// Every other field is the original act's, hash included, so the
    /// state derived under the new id stays honest — a rename rewrites
    /// the file (title, self-links, timestamps), so the carried record
    /// reads `check_stale` until someone checks the renamed entity; what
    /// the carry prevents is the ledger losing the entity (`never_checked`
    /// under the new id, an unreachable row under the old). Absent on
    /// every line a checker wrote.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub renamed_from: Option<String>,
    /// Set on a line the engine carried to a new `entity_hash` (a
    /// licensed transition, a sealed export): the hash it was keyed to
    /// before and the reason. Absent on every line a checker wrote.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub carried_from: Option<CarriedFrom>,
    /// The write whose result the check saw: the backend-native reference
    /// of the entity's last write when the record was made (a commit sha
    /// on a git-branch mem, the ledger line's timestamp token on a folder
    /// mem), stamped by the engine. Independence on an entity that is not a
    /// plan criterion compares the checker with every identity that wrote
    /// the entity up to and including this write, in write order, so a
    /// write in the same second before or after the check is told apart
    /// without a clock. A carried line keeps its source's. Absent on every
    /// line an earlier engine wrote: those are read against every write at
    /// or before their `ts`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub checked_write: Option<String>,
}

/// How far past the engine's clock an entity's newest act may lie for a
/// new local check to be stamped one second after it
/// ([`CheckLedger::record_local`]). Well inside [`OBSERVED_AT_SKEW_SECS`],
/// so a stamped row never reads as dated in the future on another machine.
pub const LOCAL_TIE_WINDOW_SECS: u64 = 60;

/// The largest lead an `observed_at` may have over the engine's clock
/// before it refuses as "in the future": two machines' clocks disagree by
/// seconds, a transcription of a check that has not happened yet is a
/// mistake.
pub const OBSERVED_AT_SKEW_SECS: u64 = 300;

/// Parse a caller-supplied `observed_at` (`YYYY-MM-DDTHH:MM:SSZ` or a
/// bare `YYYY-MM-DD`) against the engine's clock `now` (epoch seconds):
/// epoch seconds on success, the refusal reason otherwise (a shape the
/// parser does not read, or an instant more than
/// [`OBSERVED_AT_SKEW_SECS`] ahead of `now`). One parser for the CLI, the
/// batch file and the MCP tool, so the three cannot drift.
pub fn parse_observed_at(raw: &str, now: u64) -> Result<u64, String> {
    let s = raw.trim();
    let Some(at) = crate::engine::due::parse_iso_utc_seconds(s) else {
        return Err(format!(
            "observed_at {raw:?} is not an ISO-8601 UTC instant (`YYYY-MM-DDTHH:MM:SSZ`) \
             or a civil date (`YYYY-MM-DD`)"
        ));
    };
    if at > now.saturating_add(OBSERVED_AT_SKEW_SECS) {
        return Err(format!(
            "observed_at {raw:?} lies in the future (the engine's clock reads {now} epoch \
             seconds); a check is recorded after it was made, never before"
        ));
    }
    Ok(at)
}

impl CheckRecord {
    /// The time of the act: `observed_at` where the recorder stated one,
    /// `ts` otherwise. The newest record of a kind is the one with the
    /// latest act ([`CheckLedger::in_standing_order`]).
    pub fn act_time(&self) -> u64 {
        self.observed_at.unwrap_or(self.ts)
    }

    /// The record's ENGINE kind, legacy lines included: an absent or
    /// unrecognised kind reads as `verification`, which is exactly what
    /// every pre-kind line was; a foreign `x-<name>` kind is `None` —
    /// recorded, listed, never aggregated into a state.
    pub fn resolved_kind(&self) -> Option<CheckKind> {
        match self.kind.as_deref() {
            None => Some(CheckKind::Verification),
            Some(k) if k.starts_with(FOREIGN_KIND_PREFIX) => None,
            Some(k) => Some(CheckKind::from_wire(k).unwrap_or(CheckKind::Verification)),
        }
    }

    /// The foreign kind, when the record carries one.
    pub fn foreign_kind(&self) -> Option<&str> {
        self.kind
            .as_deref()
            .filter(|k| k.starts_with(FOREIGN_KIND_PREFIX))
    }
}

/// Derived per-entity check state.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CheckState {
    NeverChecked,
    CheckedOk,
    CheckFailed,
    CheckStale,
}

impl CheckState {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::NeverChecked => "never_checked",
            Self::CheckedOk => "checked_ok",
            Self::CheckFailed => "check_failed",
            Self::CheckStale => "check_stale",
        }
    }
}

/// Derive the state from the newest record (if any) and the entity's
/// current `content_hash`. Hash-only: this is the `verification`
/// derivation, and stays the whole story for that kind — a schema
/// re-pin never stales a verification verdict.
pub fn derive_state(latest: Option<&CheckRecord>, current_hash: &str) -> CheckState {
    derive_state_pinned(latest, current_hash, None)
}

/// Derive the state with schema-pin awareness: beyond the hash
/// comparison, a record that carries a `schema_ref` (a `conformance`
/// record) is stale when the mem's current pin differs from the
/// recorded one — the prose the verdict judged against is no longer
/// the prose in force. A mem that has since lost its pin entirely
/// stales the verdict the same way. Records without a `schema_ref`
/// (every `verification` record) are unaffected by the pin argument.
pub fn derive_state_pinned(
    latest: Option<&CheckRecord>,
    current_hash: &str,
    current_schema_ref: Option<&str>,
) -> CheckState {
    match latest {
        None => CheckState::NeverChecked,
        Some(rec) if rec.entity_hash != current_hash => CheckState::CheckStale,
        Some(rec)
            if rec.schema_ref.is_some() && rec.schema_ref.as_deref() != current_schema_ref =>
        {
            CheckState::CheckStale
        }
        Some(rec) if rec.verdict == "failed" => CheckState::CheckFailed,
        Some(_) => CheckState::CheckedOk,
    }
}

/// The ledger's directory under the workspace store:
/// `<root>/.memstead/state/checks/`.
fn checks_dir(workspace_root: &Path) -> PathBuf {
    workspace_root
        .join(crate::workspace_store::WORKSPACE_STORE_DIR)
        .join("state")
        .join("checks")
}

/// The ledger file path for a workspace. Private to this module with the
/// raw read: every reader elsewhere gets rows only in standing order.
fn check_ledger_path(workspace_root: &Path) -> PathBuf {
    checks_dir(workspace_root).join("checks.jsonl")
}

/// Append/read handle for a workspace's check ledger.
#[derive(Debug, Clone)]
pub struct CheckLedger {
    path: PathBuf,
}

impl CheckLedger {
    pub fn for_workspace(workspace_root: &Path) -> Self {
        Self {
            path: check_ledger_path(workspace_root),
        }
    }

    /// Append one record. One `write` syscall of one complete line on
    /// an `O_APPEND` handle — concurrent writers interleave whole
    /// lines, never tear them. Errors propagate: a check that did not
    /// persist must refuse at the surface.
    pub fn record(&self, rec: &CheckRecord) -> std::io::Result<()> {
        if let Some(dir) = self.path.parent() {
            std::fs::create_dir_all(dir)?;
        }
        let mut line = serde_json::to_string(rec).map_err(std::io::Error::other)?;
        line.push('\n');
        let mut f = std::fs::OpenOptions::new()
            .create(true)
            .append(true)
            .open(&self.path)?;
        f.write_all(line.as_bytes())
    }

    /// Append one check this engine just made, stamped so it never ties
    /// with an earlier act on the same entity: `ts` is the engine's clock,
    /// and when the entity's newest act already sits at or up to
    /// [`LOCAL_TIE_WINDOW_SECS`] past it (a re-check within the same
    /// second as the last one, say after an edit), `ts` moves to one
    /// second past that act. Whole-second clocks would otherwise tie the
    /// two, and the tie would go to the rows' bytes, which could stand
    /// the check of the replaced content over the check just made. A
    /// record whose caller stated `observed_at` is appended as stated:
    /// the caller named the time of the act. Returns the record as
    /// appended.
    pub fn record_local(&self, mut rec: CheckRecord) -> std::io::Result<CheckRecord> {
        if rec.observed_at.is_none() {
            let newest = self
                .raw_lines()
                .iter()
                .filter(|r| r.entity == rec.entity)
                .map(CheckRecord::act_time)
                .max();
            if let Some(newest) = newest
                && newest >= rec.ts
                && newest <= rec.ts.saturating_add(LOCAL_TIE_WINDOW_SECS)
            {
                rec.ts = newest + 1;
            }
        }
        self.record(&rec)?;
        Ok(rec)
    }

    /// Carry every record of `old` across a rename to `new`: each line
    /// keyed by the old id is appended again under the new id with
    /// `renamed_from` set, in ledger order, as one write of whole lines.
    /// The originals stay — the ledger is append-only and they remain the
    /// record of what was checked under that id. Returns the number of
    /// lines carried; zero (and no write) when the old id has none.
    pub fn carry_rename(&self, old: &str, new: &str) -> std::io::Result<usize> {
        let carried: Vec<CheckRecord> = self
            .raw_lines()
            .into_iter()
            .filter(|r| r.entity == old)
            .map(|mut r| {
                r.entity = new.to_string();
                r.renamed_from = Some(old.to_string());
                r
            })
            .collect();
        if carried.is_empty() {
            return Ok(0);
        }
        let mut lines = String::new();
        for rec in &carried {
            lines.push_str(&serde_json::to_string(rec).map_err(std::io::Error::other)?);
            lines.push('\n');
        }
        let mut f = std::fs::OpenOptions::new()
            .create(true)
            .append(true)
            .open(&self.path)?;
        f.write_all(lines.as_bytes())?;
        Ok(carried.len())
    }

    /// Carry the record that licensed a status transition across the
    /// write it licensed: the newest record of `entity` under the wire
    /// `kind` is appended again with `post_hash` as its `entity_hash` and
    /// `carried_from: {hash: pre_hash, reason: "transition"}`, if and
    /// only if it is fresh at `pre_hash` and confirming (`ok`). A stale
    /// or failed record is not carried (it did not license anything),
    /// and equal hashes carry nothing. Every other field stays the
    /// original act's, identity included. Returns whether a line was
    /// appended.
    pub fn carry_transition(
        &self,
        entity: &str,
        kind: &str,
        pre_hash: &str,
        post_hash: &str,
    ) -> std::io::Result<bool> {
        if pre_hash == post_hash {
            return Ok(false);
        }
        let Some(latest) = self.latest_for_wire_kind(entity, kind) else {
            return Ok(false);
        };
        if latest.entity_hash != pre_hash || latest.verdict != Verdict::Ok.as_str() {
            return Ok(false);
        }
        let depth = latest
            .carried_from
            .as_ref()
            .map_or(1, |c| c.chain_depth() + 1);
        let carried = CheckRecord {
            entity_hash: post_hash.to_string(),
            carried_from: Some(CarriedFrom::transition_at(pre_hash, depth)),
            ..latest
        };
        self.record(&carried)?;
        Ok(true)
    }

    /// The records of one mem's entities, in standing order
    /// ([`Self::in_standing_order`]): every record whose entity id is
    /// qualified by `mem`.
    pub fn rows_for_mem(&self, mem: &str) -> Vec<CheckRecord> {
        let prefix = format!("{mem}--");
        standing_order(
            self.raw_lines()
                .into_iter()
                .filter(|r| r.entity.starts_with(&prefix))
                .collect(),
        )
    }

    /// The transport form of one mem's rows ([`Self::transport_lines`]).
    pub fn transport_lines_for_mem(&self, mem: &str) -> Vec<u8> {
        Self::transport_lines(&self.rows_for_mem(mem))
    }

    /// The transport form of a set of records: one JSON line per
    /// record, ordered by timestamp then by the line's bytes, exact
    /// duplicates dropped, a trailing newline. The same records give
    /// the same bytes on every machine, so a publish that changed
    /// nothing writes nothing.
    pub fn transport_lines(records: &[CheckRecord]) -> Vec<u8> {
        let mut lines: Vec<(u64, String)> = records
            .iter()
            .filter_map(|r| serde_json::to_string(r).ok().map(|s| (r.ts, s)))
            .collect();
        lines.sort();
        lines.dedup();
        let mut out = Vec::new();
        for (_, line) in lines {
            out.extend_from_slice(line.as_bytes());
            out.push(b'\n');
        }
        out
    }

    /// Union `lines` (the transport form, from another machine) into
    /// this ledger: every record not already present is appended; a
    /// record already present (the same bytes) is skipped, so a round
    /// trip adds nothing. Unparseable lines are skipped. Rows keep every
    /// field they arrived with: identity, role, hash, timestamps; nothing
    /// is rewritten on import, and a merged row counts by its own fields
    /// (its time of the act places it, never its arrival).
    ///
    /// A row whose time of the act lies more than
    /// [`OBSERVED_AT_SKEW_SECS`] ahead of `now` (the receiving engine's
    /// clock) is refused as a local record with such a time is, and named
    /// in the outcome: ordered by time, a row from a machine with a wrong
    /// clock would otherwise stand for good.
    pub fn merge_transport_lines(&self, lines: &[u8], now: u64) -> std::io::Result<MergedRows> {
        let present: std::collections::HashSet<String> = self
            .raw_lines()
            .iter()
            .filter_map(|r| serde_json::to_string(r).ok())
            .collect();
        let mut out = MergedRows::default();
        for line in String::from_utf8_lossy(lines).lines() {
            let Ok(rec) = serde_json::from_str::<CheckRecord>(line) else {
                continue;
            };
            let Ok(canonical) = serde_json::to_string(&rec) else {
                continue;
            };
            if present.contains(&canonical) {
                continue;
            }
            if rec.act_time() > now.saturating_add(OBSERVED_AT_SKEW_SECS) {
                out.refused.push(RefusedCheckRow {
                    entity: rec.entity.clone(),
                    kind: sealed_kind_of(&rec),
                    act_time: rec.act_time(),
                    identity: rec.identity.clone(),
                    reason: format!(
                        "the row's time of the act ({}) lies more than {OBSERVED_AT_SKEW_SECS} \
                         seconds ahead of this engine's clock ({now}); a check is recorded after \
                         it was made, never before",
                        rec.act_time()
                    ),
                });
                continue;
            }
            self.record(&rec)?;
            out.appended += 1;
        }
        Ok(out)
    }

    /// The ledger's lines in arrival order. Private by construction:
    /// arrival order is not an order any reading may rest on (two machines
    /// holding the same rows hold them in different orders), so every
    /// reader outside this module gets rows only through
    /// [`Self::in_standing_order`] and the lookups built on it. A missing
    /// ledger is an empty one; unparseable lines are skipped (a torn tail
    /// must not poison the readable history).
    fn raw_lines(&self) -> Vec<CheckRecord> {
        let Ok(content) = std::fs::read_to_string(&self.path) else {
            return Vec::new();
        };
        content
            .lines()
            .filter_map(|l| serde_json::from_str(l).ok())
            .collect()
    }

    /// Every record, in standing order: the one order every reader of a
    /// standing folds, so the last row of any (entity, kind) group, and of
    /// any narrower group of one entity's rows, is that group's newest
    /// record. The order is derived from the rows alone, so two machines
    /// holding the same rows derive the same newest whatever order their
    /// ledgers hold them in:
    ///
    /// 1. a carried line supersedes every record of the same entity and
    ///    kind whose `entity_hash` is its `carried_from.hash` and whose act
    ///    is no later than the carried line's (they are keyed to content
    ///    the carry replaced; a check made later, after the content came
    ///    back to that hash, is a new act) and that stand lower in the carry
    ///    chain ([`CarriedFrom::depth`]); superseded rows come first;
    /// 2. among the rest, the earlier time of the act comes first
    ///    ([`CheckRecord::act_time`]);
    /// 3. remaining ties are ordered by the rows' canonical bytes, never
    ///    by ledger position.
    pub fn in_standing_order(&self) -> Vec<CheckRecord> {
        standing_order(self.raw_lines())
    }

    /// The newest record for one entity, of any kind
    /// ([`Self::in_standing_order`]). State derivation is per (entity,
    /// kind) — use [`Self::latest_for_kind`] there; this remains the
    /// "what happened last" accessor.
    pub fn latest_for(&self, entity: &str) -> Option<CheckRecord> {
        self.in_standing_order()
            .into_iter()
            .rev()
            .find(|r| r.entity == entity)
    }

    /// The newest record for one entity of one kind. A later check of
    /// the OTHER kind never supersedes it: the two derivations answer
    /// different questions.
    pub fn latest_for_kind(&self, entity: &str, kind: CheckKind) -> Option<CheckRecord> {
        self.in_standing_order()
            .into_iter()
            .rev()
            .find(|r| r.entity == entity && r.resolved_kind() == Some(kind))
    }

    /// The newest record for one entity of one WIRE kind: an engine
    /// kind resolves as [`Self::latest_for_kind`] (legacy kind-less
    /// lines read as `verification`); a foreign `x-<name>` kind matches
    /// the recorded kind verbatim. The lookup a `transition_requires_self_check`
    /// gate declares its kind against.
    pub fn latest_for_wire_kind(&self, entity: &str, kind: &str) -> Option<CheckRecord> {
        match CheckKind::from_wire(kind) {
            Some(k) => self.latest_for_kind(entity, k),
            None => self
                .in_standing_order()
                .into_iter()
                .rev()
                .find(|r| r.entity == entity && r.kind.as_deref() == Some(kind)),
        }
    }
}

/// What [`CheckLedger::merge_transport_lines`] did with a set of rows
/// from another machine.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct MergedRows {
    /// Rows appended to the local ledger.
    pub appended: usize,
    /// Rows refused, each named.
    pub refused: Vec<RefusedCheckRow>,
}

/// A merged row the receiving engine refused: its time of the act lies
/// beyond the clock skew allowance ahead of the receiving clock.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RefusedCheckRow {
    /// Full entity id (`mem--slug`).
    pub entity: String,
    /// Wire kind.
    pub kind: String,
    /// The row's time of the act, epoch seconds.
    pub act_time: u64,
    /// The row's declared identity, when it carries one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub identity: Option<String>,
    /// Why it was refused.
    pub reason: String,
}

/// Sort rows into standing order (see [`CheckLedger::in_standing_order`]).
/// The one place the order is decided.
fn standing_order(rows: Vec<CheckRecord>) -> Vec<CheckRecord> {
    // Each carried line: (entity, kind, hash it left, its time of the act,
    // its depth in the carry chain).
    let carries: Vec<(String, String, String, u64, Option<u32>)> = rows
        .iter()
        .filter_map(|r| {
            r.carried_from.as_ref().map(|c| {
                (
                    r.entity.clone(),
                    sealed_kind_of(r),
                    c.hash.clone(),
                    r.act_time(),
                    c.depth,
                )
            })
        })
        .collect();
    // A row is superseded by a carried line of its entity and kind that
    // left the row's hash, when the row's act is no later than the
    // carried line's (a check made later at that hash, after the content
    // came back to it, is a new act and competes by its time), and when the
    // row stands lower in the carry chain (a checker's own record is depth
    // 0). The depth orders a chain that returns to an earlier hash, which
    // two gated values on one field written in one second produce: every
    // line of it shares the source's times, and only the last carry stands.
    // A line an earlier engine carried has no depth and supersedes as it
    // always did; a row without a depth stands below every depth.
    let depth_of = |r: &CheckRecord| r.carried_from.as_ref().and_then(|c| c.depth).unwrap_or(0);
    let superseded = |r: &CheckRecord| {
        let kind = sealed_kind_of(r);
        let depth = depth_of(r);
        carries.iter().any(|(entity, k, left, at, d)| {
            *entity == r.entity
                && *k == kind
                && *left == r.entity_hash
                && r.act_time() <= *at
                && d.is_none_or(|d| depth < d)
        })
    };
    let mut keyed: Vec<(bool, u64, String, CheckRecord)> = rows
        .into_iter()
        .map(|r| {
            let sup = superseded(&r);
            let bytes = serde_json::to_string(&r).unwrap_or_default();
            (!sup, r.act_time(), bytes, r)
        })
        .collect();
    keyed.sort_by(|a, b| (a.0, a.1, &a.2).cmp(&(b.0, b.1, &b.2)));
    keyed.into_iter().map(|(_, _, _, r)| r).collect()
}

// ---------------------------------------------------------------------------
// Sealed check records: the archive member
// ---------------------------------------------------------------------------

/// Version of the sealed check-records member
/// (`.memstead/checks.json`, [`memstead_schema::ARCHIVE_CHECKS_PATH`]).
/// Read back by the archive mount; a reader tells "absent" from
/// "not carried" by this line inside the member, so the published
/// archive format number never moves for it.
pub const SEALED_CHECKS_VERSION: u32 = 1;

/// One sealed check record: the fields of the ledger line the archive
/// carries, nothing invented. `kind` is the map key it sits under, the
/// entity is the map key above that (its mem-relative path, so the
/// member survives a remount under another mem name). The transport
/// client and the structured finding stay in the workspace ledger: the
/// archive answers state, and state derives from these fields alone.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SealedCheck {
    /// Unix epoch seconds at record time.
    pub ts: u64,
    /// When the check was made, as the caller stated it (see
    /// [`CheckRecord::observed_at`]); absent when nobody did.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub observed_at: Option<u64>,
    /// `ok` | `failed`.
    pub verdict: String,
    /// The free-text method note, after the export's private-pattern
    /// redaction (the same classes the provenance member applies).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub method: Option<String>,
    /// The entity's `content_hash` at check time: the freshness
    /// baseline the mount compares against the sealed entity.
    pub entity_hash: String,
    /// Recorded actor category (`cli`, `agent`, ...).
    pub actor: String,
    /// The declared role, or `unspecified`.
    pub role: String,
    /// The declared identity, verbatim: a handle, never a person.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub identity: Option<String>,
    /// The schema pin a `conformance` record was judged against.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub schema_ref: Option<String>,
    /// The id the check was recorded under before a rename carried it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub renamed_from: Option<String>,
    /// The hash the record was keyed to before the engine carried it,
    /// and why (a licensed transition on the source mem, or the export's
    /// own rewrite of the entity bytes).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub carried_from: Option<CarriedFrom>,
    /// The author≠checker independence reading
    /// ([`crate::engine::independence::Independence`], wire form:
    /// `confirmed_independent`, `self_checked`, `unconfirmable`) the
    /// export derived for this record from the mem's provenance at
    /// export time. The archive records no history at the engine seam,
    /// so the reading cannot be re-derived on the mount; sealed here it
    /// is the fact an immutable archive carries. Absent from a member an
    /// older writer sealed: the mount then reads `unconfirmable`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub independence: Option<String>,
    /// The trust class of the TEXT this row carries — its `method` note and
    /// its finding message ([`crate::render::OriginClass`], wire form
    /// `first-party` / `third-party`), as the exporting workspace
    /// classified it ([`crate::Engine::check_row_origin_class`]).
    ///
    /// A check row's prose is written by whatever agent recorded the check,
    /// which in a workspace that points a foreign model or a transcribed
    /// outside finding at its ledger is not the workspace itself. Sealed
    /// here for the same reason `independence` is: the mount records no
    /// identity roster, so the reading cannot be re-derived on it.
    ///
    /// Absent when the exporting deployment declared no owner identities
    /// (the row then inherits its mem's class, which is what every reader
    /// did before this field) and on every member an older writer sealed.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub origin: Option<String>,
}

impl SealedCheck {
    /// The archive form of a ledger line, with no independence reading
    /// yet (the export derives and sets it; see
    /// [`crate::ops::export::build_redacted_sealed_checks`]).
    pub fn from_record(rec: &CheckRecord) -> Self {
        Self {
            ts: rec.ts,
            observed_at: rec.observed_at,
            verdict: rec.verdict.clone(),
            method: rec.method.clone(),
            entity_hash: rec.entity_hash.clone(),
            actor: rec.actor.clone(),
            role: rec.role.clone(),
            identity: rec.identity.clone(),
            schema_ref: rec.schema_ref.clone(),
            renamed_from: rec.renamed_from.clone(),
            carried_from: rec.carried_from.clone(),
            independence: None,
            origin: None,
        }
    }

    /// The sealed independence reading, parsed; `None` when the member
    /// carries none (an older writer) or a value outside the vocabulary.
    pub fn sealed_independence(&self) -> Option<crate::engine::independence::Independence> {
        self.independence
            .as_deref()
            .and_then(crate::engine::independence::Independence::from_wire)
    }

    /// The sealed trust class of the row's prose, parsed; `None` when the
    /// member seals none, which is every member an older writer sealed and
    /// every export from a deployment that declared no owner identities.
    /// The reader falls back to the mem's class then, as it did before the
    /// field existed.
    ///
    /// This is the one reader that makes the sealed field load-bearing, and
    /// it matters exactly where the mem grain cannot answer: a deployment
    /// that vouches for an installed archive as first-party
    /// ([`crate::Engine::declare_mem_origin`]) still must not serve a row
    /// the publisher's own foreign checker wrote as its own prose.
    pub fn sealed_origin(&self) -> Option<crate::render::OriginClass> {
        match self.origin.as_deref()? {
            "first-party" => Some(crate::render::OriginClass::FirstParty),
            "third-party" => Some(crate::render::OriginClass::ThirdParty),
            _ => None,
        }
    }

    /// The ledger form under `entity_id` and the wire `kind` the record
    /// sits under, so every derivation ([`derive_state`],
    /// [`derive_state_pinned`]) and every surface that renders a
    /// [`CheckRecord`] reads a sealed record the way it reads a ledger
    /// line. A `verification` kind stays omitted, as the ledger writes it.
    pub fn to_record(&self, entity_id: &str, kind: &str) -> CheckRecord {
        CheckRecord {
            ts: self.ts,
            observed_at: self.observed_at,
            entity: entity_id.to_string(),
            verdict: self.verdict.clone(),
            method: self.method.clone(),
            entity_hash: self.entity_hash.clone(),
            actor: self.actor.clone(),
            client: None,
            role: self.role.clone(),
            identity: self.identity.clone(),
            kind: (kind != CheckKind::Verification.as_str()).then(|| kind.to_string()),
            schema_ref: self.schema_ref.clone(),
            finding: None,
            renamed_from: self.renamed_from.clone(),
            carried_from: self.carried_from.clone(),
            checked_write: None,
        }
    }
}

/// The sealed check-records member: per entity (keyed by mem-relative
/// path) the latest record per kind (keyed by wire kind:
/// `verification`, `conformance`, or a foreign `x-<name>`).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SealedChecks {
    pub version: u32,
    #[serde(default)]
    pub entities: BTreeMap<String, BTreeMap<String, SealedCheck>>,
}

impl SealedChecks {
    /// An empty member of the current version.
    pub fn new() -> Self {
        Self {
            version: SEALED_CHECKS_VERSION,
            entities: BTreeMap::new(),
        }
    }

    /// The latest sealed record of one entity (by mem-relative path)
    /// under one wire kind.
    pub fn latest(&self, entity_path: &str, kind: &str) -> Option<&SealedCheck> {
        self.entities
            .get(entity_path)
            .and_then(|kinds| kinds.get(kind))
    }

    /// Every sealed kind of one entity, in key order.
    pub fn kinds_of(&self, entity_path: &str) -> impl Iterator<Item = (&str, &SealedCheck)> {
        self.entities
            .get(entity_path)
            .into_iter()
            .flat_map(|kinds| kinds.iter().map(|(k, v)| (k.as_str(), v)))
    }

    /// Re-key every record of one entity that is fresh at `pre_hash` to
    /// `post_hash`, marking it `carried_from: {hash: pre_hash, reason:
    /// "export"}`: the export rewrote the entity's bytes (links retargeted
    /// to the archive name, the canonical re-render), and a record that
    /// was fresh against the source content stays fresh against the
    /// archived content. A record keyed to any other hash was stale
    /// before the export and keeps its hash, so it still reads stale on
    /// the mount. Equal hashes change nothing; every other field, the
    /// sealed independence reading included, stays as sealed. Returns the
    /// number of records moved.
    pub fn rekey_entity(&mut self, entity_path: &str, pre_hash: &str, post_hash: &str) -> usize {
        if pre_hash == post_hash {
            return 0;
        }
        let Some(kinds) = self.entities.get_mut(entity_path) else {
            return 0;
        };
        let mut moved = 0;
        for rec in kinds.values_mut() {
            if rec.entity_hash == pre_hash {
                rec.entity_hash = post_hash.to_string();
                rec.carried_from = Some(CarriedFrom::export(pre_hash));
                moved += 1;
            }
        }
        moved
    }

    /// Serialise to the canonical member bytes (pretty JSON, trailing
    /// newline), deterministic for a given content: both maps are
    /// ordered.
    pub fn to_archive_bytes(&self) -> Result<Vec<u8>, serde_json::Error> {
        let mut s = serde_json::to_string_pretty(self)?;
        s.push('\n');
        Ok(s.into_bytes())
    }

    /// Parse the member bytes. Shape only; [`Self::validate`] checks the
    /// vocabulary and the entity roster.
    pub fn from_archive_bytes(bytes: &[u8]) -> Result<Self, serde_json::Error> {
        serde_json::from_slice(bytes)
    }

    /// The validator's shape check: the version this engine reads, every
    /// kind in the vocabulary, every verdict in the vocabulary, a
    /// non-empty hash, actor and role, and every entity path one the
    /// archive carries (`carried` is the set of mem-relative entity
    /// paths). The error names the first offending record.
    pub fn validate(&self, carried: &std::collections::BTreeSet<String>) -> Result<(), String> {
        if self.version != SEALED_CHECKS_VERSION {
            return Err(format!(
                "version {} is not the version this engine reads ({SEALED_CHECKS_VERSION})",
                self.version
            ));
        }
        for (path, kinds) in &self.entities {
            if !carried.contains(path) {
                return Err(format!(
                    "entity `{path}` names no entity the archive carries"
                ));
            }
            for (kind, rec) in kinds {
                let at = format!("entity `{path}`, kind `{kind}`");
                if RecordKind::from_wire(kind).is_none() {
                    return Err(format!(
                        "{at}: the kind is not one of {}",
                        RecordKind::vocabulary_hint()
                    ));
                }
                if Verdict::from_wire(&rec.verdict).is_none() {
                    return Err(format!(
                        "{at}: verdict `{}` is not one of {}",
                        rec.verdict,
                        VERDICTS.join(", ")
                    ));
                }
                if rec.entity_hash.trim().is_empty() {
                    return Err(format!("{at}: entity_hash is empty"));
                }
                if rec.actor.trim().is_empty() {
                    return Err(format!("{at}: actor is empty"));
                }
                if rec.role.trim().is_empty() {
                    return Err(format!("{at}: role is empty"));
                }
                if let Some(reading) = rec.independence.as_deref()
                    && crate::engine::independence::Independence::from_wire(reading).is_none()
                {
                    return Err(format!(
                        "{at}: independence `{reading}` is not one of {}",
                        crate::engine::independence::Independence::vocabulary_hint()
                    ));
                }
                // The trust class is publisher-supplied bytes on an
                // installed archive, so the vocabulary is closed here as
                // the independence reading's is: an unknown token is
                // refused with a typed error rather than parsed into
                // something a reader would treat as a class.
                if let Some(origin) = rec.origin.as_deref()
                    && rec.sealed_origin().is_none()
                {
                    return Err(format!(
                        "{at}: origin `{origin}` is not one of first-party | third-party"
                    ));
                }
            }
        }
        Ok(())
    }
}

impl Default for SealedChecks {
    fn default() -> Self {
        Self::new()
    }
}

/// The wire kind a ledger line sits under in the sealed member: an
/// engine kind by its resolved name (a legacy kind-less line is
/// `verification`), a foreign kind verbatim.
pub fn sealed_kind_of(rec: &CheckRecord) -> String {
    match rec.resolved_kind() {
        Some(k) => k.as_str().to_string(),
        None => rec.kind.clone().unwrap_or_default(),
    }
}

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

    fn rec(entity: &str, verdict: &str, hash: &str) -> CheckRecord {
        CheckRecord {
            ts: 1,
            observed_at: None,
            entity: entity.to_string(),
            verdict: verdict.to_string(),
            method: None,
            entity_hash: hash.to_string(),
            actor: "cli".to_string(),
            client: None,
            role: "checker".to_string(),
            identity: None,
            kind: None,
            schema_ref: None,
            finding: None,
            renamed_from: None,
            carried_from: None,
            checked_write: None,
        }
    }

    fn at(entity: &str, verdict: &str, hash: &str, ts: u64) -> CheckRecord {
        CheckRecord {
            ts,
            ..rec(entity, verdict, hash)
        }
    }

    fn line(r: &CheckRecord) -> Vec<u8> {
        let mut l = serde_json::to_vec(r).unwrap();
        l.push(b'\n');
        l
    }

    /// The newest record of a kind is the one made last, whatever order
    /// the ledger holds the lines in: a merged row older than the local
    /// one does not displace it, a merged row made later does.
    #[test]
    fn a_merged_row_stands_by_its_time_of_the_act_not_its_arrival() {
        let now = 10_000;
        let tmp = TempDir::new().unwrap();
        let ledger = CheckLedger::for_workspace(tmp.path());
        ledger.record(&at("m--e", "ok", "h1", 200)).unwrap();
        let merged = ledger
            .merge_transport_lines(&line(&at("m--e", "failed", "h1", 100)), now)
            .unwrap();
        assert_eq!(merged.appended, 1);
        let standing = ledger
            .latest_for_kind("m--e", CheckKind::Verification)
            .unwrap();
        assert_eq!((standing.verdict.as_str(), standing.ts), ("ok", 200));

        ledger
            .merge_transport_lines(&line(&at("m--e", "failed", "h1", 300)), now)
            .unwrap();
        let standing = ledger
            .latest_for_kind("m--e", CheckKind::Verification)
            .unwrap();
        assert_eq!((standing.verdict.as_str(), standing.ts), ("failed", 300));
    }

    /// `observed_at` is the time of the act: checks transcribed out of
    /// order stand by it, not by the transcription time `ts`.
    #[test]
    fn checks_recorded_out_of_order_stand_by_observed_at() {
        let tmp = TempDir::new().unwrap();
        let ledger = CheckLedger::for_workspace(tmp.path());
        let mut later = at("m--e", "ok", "h1", 500);
        later.observed_at = Some(400);
        let mut earlier = at("m--e", "failed", "h1", 501);
        earlier.observed_at = Some(100);
        ledger.record(&later).unwrap();
        ledger.record(&earlier).unwrap();
        let standing = ledger.latest_for_wire_kind("m--e", "verification").unwrap();
        assert_eq!(standing.verdict, "ok");
    }

    /// A carried line shares its source's times by construction; it
    /// supersedes every record of the entity and kind keyed to the hash
    /// it was carried from, whatever the bytes would say.
    #[test]
    fn a_carried_line_stands_over_its_source() {
        for order in [false, true] {
            let tmp = TempDir::new().unwrap();
            let ledger = CheckLedger::for_workspace(tmp.path());
            let mut source = at("m--e", "ok", "h1", 100);
            source.kind = Some("x-approval".into());
            let carried = CheckRecord {
                entity_hash: "h2".into(),
                carried_from: Some(CarriedFrom::transition("h1")),
                checked_write: None,
                ..source.clone()
            };
            // A second record at the source's hash, same second: also
            // keyed to the replaced content, also superseded.
            let mut sibling = at("m--e", "ok", "zz-sibling", 100);
            sibling.entity_hash = "h1".into();
            sibling.kind = Some("x-approval".into());
            sibling.method = Some("zzzz".into());
            let mut rows = vec![source.clone(), carried.clone(), sibling];
            if order {
                rows.reverse();
            }
            for r in &rows {
                ledger.record(r).unwrap();
            }
            let standing = ledger.latest_for_wire_kind("m--e", "x-approval").unwrap();
            assert_eq!(standing.entity_hash, "h2", "order reversed: {order}");
            assert!(standing.carried_from.is_some());
        }
    }

    /// A check made at the hash a carry left, after the content came back
    /// to it, is a new act and stands by its time. A carry chain stands on
    /// its last line, and so does a carry cycle, in every ledger order.
    #[test]
    fn a_check_after_a_return_to_the_carried_from_hash_stands() {
        let tmp = TempDir::new().unwrap();
        let ledger = CheckLedger::for_workspace(tmp.path());
        let source = at("m--e", "ok", "h1", 100);
        ledger.record(&source).unwrap();
        ledger
            .record(&CheckRecord {
                entity_hash: "h2".into(),
                carried_from: Some(CarriedFrom::transition("h1")),
                checked_write: None,
                ..source.clone()
            })
            .unwrap();
        ledger.record(&at("m--e", "failed", "h1", 500)).unwrap();
        let standing = ledger
            .latest_for_kind("m--e", CheckKind::Verification)
            .unwrap();
        assert_eq!((standing.verdict.as_str(), standing.ts), ("failed", 500));

        let a = at("m--e", "ok", "h1", 100);
        let carry = |hash: &str, from: &str, depth: u32| CheckRecord {
            entity_hash: hash.into(),
            carried_from: Some(CarriedFrom::transition_at(from, depth)),
            ..a.clone()
        };
        let read = |rows: &[&CheckRecord]| {
            let tmp = TempDir::new().unwrap();
            let ledger = CheckLedger::for_workspace(tmp.path());
            for r in rows {
                ledger.record(r).unwrap();
            }
            ledger
                .latest_for_kind("m--e", CheckKind::Verification)
                .unwrap()
        };
        // A chain h1 to h2 to h3 stands on its last line.
        let (mid, last) = (carry("h2", "h1", 1), carry("h3", "h2", 2));
        assert_eq!(read(&[&last, &a, &mid]).entity_hash, "h3");
        assert_eq!(read(&[&mid, &last, &a]).entity_hash, "h3");
        // A cycle h1 to h2, back to h1, on to h2 again (two gated values
        // on one field, written in one second) stands on its last carry
        // in every ledger order.
        let (b1, back, b2) = (
            carry("h2", "h1", 1),
            carry("h1", "h2", 2),
            carry("h2", "h1", 3),
        );
        for rows in [
            [&a, &b1, &back, &b2],
            [&b2, &back, &b1, &a],
            [&back, &a, &b2, &b1],
        ] {
            let standing = read(&rows);
            assert_eq!(standing.entity_hash, "h2");
            assert_eq!(standing.carried_from.as_ref().unwrap().depth, Some(3));
        }
        // Lines an earlier engine carried (no depth) keep their old reading.
        let old = |hash: &str, from: &str| CheckRecord {
            entity_hash: hash.into(),
            carried_from: Some(CarriedFrom {
                depth: None,
                ..CarriedFrom::transition(from)
            }),
            ..a.clone()
        };
        assert_eq!(
            read(&[&old("h3", "h2"), &a, &old("h2", "h1")]).entity_hash,
            "h3"
        );
    }

    /// Two workspaces holding the same rows in different ledger orders,
    /// two of them with equal times of the act, derive the same standing.
    #[test]
    fn two_ledgers_with_the_same_rows_derive_the_same_newest() {
        let mut a = at("m--e", "ok", "h1", 100);
        a.identity = Some("grader-a".into());
        let mut b = at("m--e", "failed", "h1", 100);
        b.identity = Some("grader-b".into());
        let c = at("m--e", "ok", "h1", 50);
        let rows = [a, b, c];
        let mut standings = Vec::new();
        for perm in [[0, 1, 2], [1, 0, 2], [2, 1, 0], [1, 2, 0]] {
            let tmp = TempDir::new().unwrap();
            let ledger = CheckLedger::for_workspace(tmp.path());
            for i in perm {
                ledger.record(&rows[i]).unwrap();
            }
            let s = ledger
                .latest_for_kind("m--e", CheckKind::Verification)
                .unwrap();
            standings.push(serde_json::to_string(&s).unwrap());
            assert_eq!(
                serde_json::to_string(&ledger.in_standing_order()).unwrap(),
                serde_json::to_string(&standing_order(rows.to_vec())).unwrap(),
                "the whole order is derived from the rows alone"
            );
        }
        standings.dedup();
        assert_eq!(standings.len(), 1, "{standings:?}");
    }

    /// A check this engine makes right after another on the same entity,
    /// in the same second, stands over it: the local stamp moves past the
    /// earlier act instead of tying with it. A stated `observed_at` is
    /// kept as stated.
    #[test]
    fn a_local_recheck_in_the_same_second_stands_over_the_earlier_check() {
        let tmp = TempDir::new().unwrap();
        let ledger = CheckLedger::for_workspace(tmp.path());
        // "zz" sorts after "h2": by bytes alone the old check would win.
        ledger
            .record_local(at("m--e", "ok", "zz-old", 1000))
            .unwrap();
        let fresh = ledger.record_local(at("m--e", "ok", "h2", 1000)).unwrap();
        assert_eq!(fresh.ts, 1001);
        let standing = ledger
            .latest_for_kind("m--e", CheckKind::Verification)
            .unwrap();
        assert_eq!(standing.entity_hash, "h2");
        let mut stated = at("m--e", "ok", "h3", 1000);
        stated.observed_at = Some(900);
        assert_eq!(ledger.record_local(stated).unwrap().ts, 1000);
        // Far behind the clock: nothing moves.
        assert_eq!(
            ledger.record_local(at("m--f", "ok", "h", 5000)).unwrap().ts,
            5000
        );
    }

    /// A merged row dated beyond the clock skew ahead of the receiving
    /// clock is refused as a local record with such a time is, and named;
    /// the rows beside it still land.
    #[test]
    fn a_merged_row_from_the_future_is_refused_and_named() {
        let now = 10_000;
        let tmp = TempDir::new().unwrap();
        let ledger = CheckLedger::for_workspace(tmp.path());
        let mut future = at("m--e", "ok", "h1", now + OBSERVED_AT_SKEW_SECS + 1);
        future.identity = Some("clock-wrong".into());
        let mut dated_future = at("m--e", "ok", "h1", 100);
        dated_future.observed_at = Some(now + 10 * OBSERVED_AT_SKEW_SECS);
        let inside = at("m--e", "ok", "h1", now + OBSERVED_AT_SKEW_SECS);
        let mut bytes = line(&future);
        bytes.extend(line(&dated_future));
        bytes.extend(line(&inside));
        let merged = ledger.merge_transport_lines(&bytes, now).unwrap();
        assert_eq!(merged.appended, 1);
        assert_eq!(merged.refused.len(), 2);
        assert_eq!(merged.refused[0].entity, "m--e");
        assert_eq!(merged.refused[0].identity.as_deref(), Some("clock-wrong"));
        assert_eq!(merged.refused[1].act_time, now + 10 * OBSERVED_AT_SKEW_SECS);
        assert_eq!(ledger.raw_lines().len(), 1);
    }

    #[test]
    fn state_derivation_covers_all_four_states() {
        assert_eq!(derive_state(None, "h1"), CheckState::NeverChecked);
        let ok = rec("m--e", "ok", "h1");
        assert_eq!(derive_state(Some(&ok), "h1"), CheckState::CheckedOk);
        assert_eq!(derive_state(Some(&ok), "h2"), CheckState::CheckStale);
        let failed = rec("m--e", "failed", "h1");
        assert_eq!(derive_state(Some(&failed), "h1"), CheckState::CheckFailed);
        // A failed check on changed content is stale too — the verdict
        // no longer speaks to current content either way.
        assert_eq!(derive_state(Some(&failed), "h2"), CheckState::CheckStale);
    }

    #[test]
    fn ledger_appends_and_serves_newest_per_entity() {
        let tmp = TempDir::new().unwrap();
        let ledger = CheckLedger::for_workspace(tmp.path());
        assert!(ledger.latest_for("m--a").is_none());
        ledger.record(&at("m--a", "failed", "h1", 1)).unwrap();
        ledger.record(&at("m--b", "ok", "h9", 2)).unwrap();
        ledger.record(&at("m--a", "ok", "h2", 3)).unwrap();
        let latest = ledger.latest_for("m--a").unwrap();
        assert_eq!(latest.verdict, "ok");
        assert_eq!(latest.entity_hash, "h2");
        // Supersession never erases: all three records remain.
        assert_eq!(ledger.raw_lines().len(), 3);
    }

    /// A rename carries the old id's lines under the new id, marked
    /// with their origin, and leaves the originals in place. The carried
    /// line keeps the hash the check was made against, so it derives
    /// `check_stale` against the renamed file's new hash — never a
    /// silently fresh `checked_ok`, never `never_checked`.
    /// `observed_at` is the caller's statement of when the check was
    /// made: parsed from the two ISO shapes, refused when unreadable or
    /// ahead of the clock beyond the skew allowance, kept verbatim by
    /// the rename carry (every carried field is the original act's) and
    /// by the sealed form's round trip, and absent from a line that
    /// never carried it, byte for byte.
    #[test]
    fn observed_at_parses_refuses_the_future_and_survives_the_carries() {
        let now = 1_792_503_930; // 2026-10-20T13:45:30Z
        assert_eq!(parse_observed_at("2026-10-19", now), Ok(1_792_368_000));
        assert_eq!(parse_observed_at(" 2026-10-20T13:45:30Z ", now), Ok(now));
        // Inside the skew allowance: accepted. Beyond it: refused.
        assert!(parse_observed_at("2026-10-20T13:50:00Z", now).is_ok());
        let err = parse_observed_at("2026-10-20T13:51:00Z", now).unwrap_err();
        assert!(err.contains("future"), "{err}");
        let err = parse_observed_at("20.10.2026", now).unwrap_err();
        assert!(err.contains("ISO-8601"), "{err}");

        let tmp = TempDir::new().unwrap();
        let ledger = CheckLedger::for_workspace(tmp.path());
        let mut dated = rec("m--old", "ok", "h1");
        dated.observed_at = Some(1_792_368_000);
        ledger.record(&dated).unwrap();
        ledger.record(&rec("m--old", "ok", "h2")).unwrap();
        assert_eq!(ledger.carry_rename("m--old", "m--new").unwrap(), 2);
        let carried: Vec<CheckRecord> = ledger
            .raw_lines()
            .into_iter()
            .filter(|r| r.entity == "m--new")
            .collect();
        assert_eq!(carried[0].observed_at, Some(1_792_368_000));
        assert_eq!(carried[1].observed_at, None);

        let sealed = SealedCheck::from_record(&dated);
        assert_eq!(sealed.observed_at, Some(1_792_368_000));
        assert_eq!(
            sealed.to_record("m--old", "verification").observed_at,
            Some(1_792_368_000)
        );

        let raw = std::fs::read_to_string(check_ledger_path(tmp.path())).unwrap();
        let lines: Vec<&str> = raw.lines().collect();
        assert!(
            lines[0].contains("\"observed_at\":1792368000"),
            "{}",
            lines[0]
        );
        assert!(!lines[1].contains("observed_at"), "{}", lines[1]);
    }

    #[test]
    fn carry_rename_rekeys_without_erasing() {
        let tmp = TempDir::new().unwrap();
        let ledger = CheckLedger::for_workspace(tmp.path());
        ledger.record(&rec("m--old", "ok", "h1")).unwrap();
        ledger.record(&rec("m--other", "ok", "h9")).unwrap();
        let mut conf = rec("m--old", "failed", "h1");
        conf.kind = Some("conformance".into());
        ledger.record(&conf).unwrap();

        assert_eq!(ledger.carry_rename("m--old", "m--new").unwrap(), 2);
        assert_eq!(ledger.carry_rename("m--absent", "m--new").unwrap(), 0);

        let all = ledger.raw_lines();
        assert_eq!(all.len(), 5);
        assert!(all.iter().filter(|r| r.entity == "m--old").count() == 2);
        let carried: Vec<&CheckRecord> = all.iter().filter(|r| r.entity == "m--new").collect();
        assert_eq!(carried.len(), 2);
        assert!(
            carried
                .iter()
                .all(|r| r.renamed_from.as_deref() == Some("m--old"))
        );
        let latest = ledger
            .latest_for_kind("m--new", CheckKind::Verification)
            .unwrap();
        assert_eq!(latest.verdict, "ok");
        assert_eq!(derive_state(Some(&latest), "h1"), CheckState::CheckedOk);
        assert_eq!(
            derive_state(Some(&latest), "h2-after-rename"),
            CheckState::CheckStale
        );
        assert_eq!(
            ledger
                .latest_for_kind("m--new", CheckKind::Conformance)
                .unwrap()
                .verdict,
            "failed"
        );
        // A checker's own line never carries the marker.
        assert!(
            ledger
                .latest_for("m--other")
                .unwrap()
                .renamed_from
                .is_none()
        );
    }

    /// A transition carry re-keys the licensing record to the post-write
    /// hash and marks its origin; a record that is stale at the pre-write
    /// hash, a failed one, or an unchanged hash carries nothing. The
    /// carried line keeps the checker's identity, so independence still
    /// reads it as the checker's, not the writer's.
    #[test]
    fn carry_transition_moves_only_the_fresh_confirming_record() {
        let tmp = TempDir::new().unwrap();
        let ledger = CheckLedger::for_workspace(tmp.path());
        let mut ok = rec("m--plan", "ok", "h1");
        ok.kind = Some("x-projection".into());
        ok.identity = Some("checker-c".into());
        ledger.record(&ok).unwrap();

        assert!(
            !ledger
                .carry_transition("m--plan", "x-projection", "h1", "h1")
                .unwrap()
        );
        assert!(
            !ledger
                .carry_transition("m--plan", "x-projection", "h0", "h2")
                .unwrap()
        );
        assert!(
            !ledger
                .carry_transition("m--plan", "verification", "h1", "h2")
                .unwrap()
        );
        assert_eq!(ledger.raw_lines().len(), 1, "nothing appended so far");

        assert!(
            ledger
                .carry_transition("m--plan", "x-projection", "h1", "h2")
                .unwrap()
        );
        let all = ledger.raw_lines();
        assert_eq!(all.len(), 2, "append-only: the original stays");
        let carried = ledger
            .latest_for_wire_kind("m--plan", "x-projection")
            .unwrap();
        assert_eq!(carried.entity_hash, "h2");
        assert_eq!(carried.identity.as_deref(), Some("checker-c"));
        assert_eq!(carried.verdict, "ok");
        assert_eq!(carried.carried_from, Some(CarriedFrom::transition("h1")));
        assert_eq!(derive_state(Some(&carried), "h2"), CheckState::CheckedOk);
        // A second transition carries the carried line onward, one step.
        assert!(
            ledger
                .carry_transition("m--plan", "x-projection", "h2", "h3")
                .unwrap()
        );
        let again = ledger
            .latest_for_wire_kind("m--plan", "x-projection")
            .unwrap();
        assert_eq!(again.carried_from.as_ref().unwrap().hash, "h2");

        // A failed record licenses nothing and is never carried.
        let mut failed = rec("m--other", "failed", "h1");
        failed.kind = Some("x-projection".into());
        ledger.record(&failed).unwrap();
        assert!(
            !ledger
                .carry_transition("m--other", "x-projection", "h1", "h2")
                .unwrap()
        );
        // A checker's own line never carries the marker.
        assert!(all[0].carried_from.is_none());
    }

    /// The sealed member re-keys a record fresh at the pre-rewrite hash
    /// to the archived hash and marks it; a stale record keeps its hash.
    #[test]
    fn sealed_rekey_moves_fresh_records_and_leaves_stale_ones() {
        let mut sealed = SealedChecks::new();
        let fresh = SealedCheck::from_record(&rec("m--a", "ok", "h1"));
        let mut stale = SealedCheck::from_record(&rec("m--a", "ok", "h0"));
        stale.ts = 0;
        sealed.entities.insert(
            "a".into(),
            BTreeMap::from([
                ("verification".to_string(), fresh),
                ("x-audit".to_string(), stale),
            ]),
        );
        assert_eq!(sealed.rekey_entity("a", "h1", "h1"), 0);
        assert_eq!(sealed.rekey_entity("absent", "h1", "h2"), 0);
        assert_eq!(sealed.rekey_entity("a", "h1", "h2"), 1);
        let v = sealed.latest("a", "verification").unwrap();
        assert_eq!(v.entity_hash, "h2");
        assert_eq!(v.carried_from.as_ref().unwrap().reason, CARRY_REASON_EXPORT);
        assert_eq!(v.carried_from.as_ref().unwrap().hash, "h1");
        let x = sealed.latest("a", "x-audit").unwrap();
        assert_eq!(x.entity_hash, "h0", "stale stays stale");
        assert!(x.carried_from.is_none());
        // The round trip through the ledger form keeps the marker.
        let back = v.to_record("m--a", "verification");
        assert_eq!(back.carried_from, v.carried_from);
        assert_eq!(SealedCheck::from_record(&back), *v);
        // A pre-marker member line still parses, and reads no independence.
        let legacy = r#"{"ts":1,"verdict":"ok","entity_hash":"h","actor":"cli","role":"checker"}"#;
        let parsed: SealedCheck = serde_json::from_str(legacy).unwrap();
        assert!(parsed.carried_from.is_none());
        assert!(parsed.independence.is_none());
        assert!(parsed.sealed_independence().is_none());
    }

    /// The sealed trust class of a row's prose parses only from the two
    /// origin tokens and fails the validator outside them. The bytes come
    /// from a publisher's archive, so the vocabulary is closed here exactly
    /// as the independence reading's is: a member claiming `first-party` in
    /// a spelling no reader recognises must be refused with a typed error,
    /// not parsed into something a reader treats as a class.
    #[test]
    fn sealed_row_origin_parses_only_from_the_closed_vocabulary() {
        let mut sealed = SealedChecks::new();
        let mut row = SealedCheck::from_record(&rec("m--a", "ok", "h1"));
        row.origin = Some("third-party".to_string());
        sealed.entities.insert(
            "a".into(),
            BTreeMap::from([("verification".to_string(), row)]),
        );
        assert_eq!(
            sealed.latest("a", "verification").unwrap().sealed_origin(),
            Some(crate::render::OriginClass::ThirdParty)
        );
        let carried: std::collections::BTreeSet<String> = ["a".to_string()].into();
        assert!(sealed.validate(&carried).is_ok());

        // A member an older writer sealed carries none and reads none.
        let legacy = r#"{"ts":1,"verdict":"ok","entity_hash":"h","actor":"cli","role":"checker"}"#;
        let parsed: SealedCheck = serde_json::from_str(legacy).unwrap();
        assert!(parsed.origin.is_none());
        assert!(parsed.sealed_origin().is_none());

        // A token outside the vocabulary is refused, and reads as no class
        // rather than as a guess.
        sealed
            .entities
            .get_mut("a")
            .unwrap()
            .get_mut("verification")
            .unwrap()
            .origin = Some("trusted".into());
        assert!(
            sealed
                .latest("a", "verification")
                .unwrap()
                .sealed_origin()
                .is_none()
        );
        let err = sealed.validate(&carried).unwrap_err();
        assert!(err.contains("origin `trusted`"), "{err}");
    }

    /// The sealed independence reading survives the export re-key, is
    /// dropped from the ledger form (the ledger derives, never stores
    /// it), parses only from the vocabulary, and fails the validator
    /// outside it.
    #[test]
    fn sealed_independence_is_kept_by_rekey_and_closed_in_vocabulary() {
        use crate::engine::independence::Independence;
        let mut sealed = SealedChecks::new();
        let mut fresh = SealedCheck::from_record(&rec("m--a", "ok", "h1"));
        fresh.independence = Some(Independence::ConfirmedIndependent.as_str().to_string());
        sealed.entities.insert(
            "a".into(),
            BTreeMap::from([("verification".to_string(), fresh)]),
        );
        assert_eq!(sealed.rekey_entity("a", "h1", "h2"), 1);
        let v = sealed.latest("a", "verification").unwrap();
        assert_eq!(
            v.sealed_independence(),
            Some(Independence::ConfirmedIndependent)
        );
        let bytes = sealed.to_archive_bytes().unwrap();
        let back = SealedChecks::from_archive_bytes(&bytes).unwrap();
        assert_eq!(back, sealed);
        assert!(v.to_record("m--a", "verification").carried_from.is_some());
        let carried: std::collections::BTreeSet<String> = ["a".to_string()].into();
        assert!(back.validate(&carried).is_ok());

        let mut foreign = sealed.clone();
        foreign
            .entities
            .get_mut("a")
            .unwrap()
            .get_mut("verification")
            .unwrap()
            .independence = Some("trusted".into());
        assert!(
            foreign
                .latest("a", "verification")
                .unwrap()
                .sealed_independence()
                .is_none()
        );
        let err = foreign.validate(&carried).unwrap_err();
        assert!(err.contains("independence `trusted`"), "{err}");
    }

    #[test]
    fn verdict_vocabulary_is_closed() {
        assert!(Verdict::from_wire("ok").is_some());
        assert!(Verdict::from_wire("failed").is_some());
        assert!(Verdict::from_wire("passed").is_none());
        assert!(Verdict::from_wire("OK").is_none());
    }

    fn conf(entity: &str, verdict: &str, hash: &str, pin: &str) -> CheckRecord {
        CheckRecord {
            kind: Some("conformance".to_string()),
            schema_ref: Some(pin.to_string()),
            ..rec(entity, verdict, hash)
        }
    }

    #[test]
    fn kind_vocabulary_is_closed() {
        assert!(CheckKind::from_wire("verification").is_some());
        assert!(CheckKind::from_wire("conformance").is_some());
        assert!(CheckKind::from_wire("semantic").is_none());
        assert!(CheckKind::from_wire("Conformance").is_none());
    }

    /// A pre-kind ledger line (no `kind` field) parses
    /// and derives as a `verification` record, byte-for-byte the old
    /// shape on the write side too.
    #[test]
    fn legacy_lines_read_as_verification() {
        let legacy = r#"{"ts":1,"entity":"m--e","verdict":"ok","entity_hash":"h1","actor":"cli","role":"checker"}"#;
        let parsed: CheckRecord = serde_json::from_str(legacy).unwrap();
        assert_eq!(parsed.resolved_kind(), Some(CheckKind::Verification));
        // A freshly built verification record serialises with no kind
        // and no schema_ref key at all.
        let fresh = rec("m--e", "ok", "h1");
        let line = serde_json::to_string(&fresh).unwrap();
        assert!(!line.contains("kind"));
        assert!(!line.contains("schema_ref"));
        // An identity-less record carries no identity key either —
        // pre-identity lines and identity-less callers stay
        // byte-identical.
        assert!(!line.contains("identity"));
    }

    /// State derives per (entity, kind) — a later check
    /// of the other kind does not supersede.
    #[test]
    fn latest_is_per_kind() {
        let tmp = TempDir::new().unwrap();
        let ledger = CheckLedger::for_workspace(tmp.path());
        ledger.record(&rec("m--a", "ok", "h1")).unwrap();
        ledger
            .record(&conf("m--a", "failed", "h1", "planning@1.0.0"))
            .unwrap();
        let v = ledger
            .latest_for_kind("m--a", CheckKind::Verification)
            .unwrap();
        assert_eq!(v.verdict, "ok");
        let c = ledger
            .latest_for_kind("m--a", CheckKind::Conformance)
            .unwrap();
        assert_eq!(c.verdict, "failed");
        assert_eq!(c.schema_ref.as_deref(), Some("planning@1.0.0"));
    }

    /// A conformance verdict is stale on a content move
    /// AND on a pin move; a verification verdict ignores pin moves.
    #[test]
    fn conformance_stales_on_pin_move_verification_does_not() {
        let c = conf("m--e", "ok", "h1", "planning@1.0.0");
        assert_eq!(
            derive_state_pinned(Some(&c), "h1", Some("planning@1.0.0")),
            CheckState::CheckedOk
        );
        assert_eq!(
            derive_state_pinned(Some(&c), "h2", Some("planning@1.0.0")),
            CheckState::CheckStale
        );
        assert_eq!(
            derive_state_pinned(Some(&c), "h1", Some("planning@2.0.0")),
            CheckState::CheckStale
        );
        // The mem losing its pin stales the verdict too.
        assert_eq!(
            derive_state_pinned(Some(&c), "h1", None),
            CheckState::CheckStale
        );
        // Verification: unaffected by any pin argument.
        let v = rec("m--e", "ok", "h1");
        assert_eq!(
            derive_state_pinned(Some(&v), "h1", Some("planning@9.0.0")),
            CheckState::CheckedOk
        );
        assert_eq!(derive_state(Some(&v), "h1"), CheckState::CheckedOk);
    }

    // --- findings and open kinds ---

    #[test]
    fn finding_shape_is_fixed_and_validated_whole() {
        let ok = CheckFinding::from_json(serde_json::json!({
            "code": "hidden-premise", "message": "The step assumes X.", "section": "step"
        }))
        .unwrap();
        assert_eq!(ok.code, "hidden-premise");
        assert_eq!(ok.section.as_deref(), Some("step"));
        for bad in [
            serde_json::json!({ "message": "no code" }),
            serde_json::json!({ "code": "x" }),
            serde_json::json!({ "code": "", "message": "empty code" }),
            serde_json::json!({ "code": "x", "message": "   " }),
            serde_json::json!({ "code": "x", "message": "m", "severity": "high" }),
            serde_json::json!({ "code": "x", "message": "m", "section": "" }),
        ] {
            let err = CheckFinding::from_json(bad.clone())
                .unwrap_err()
                .to_string();
            assert!(err.contains("shape"), "{bad}: {err}");
        }
    }

    #[test]
    fn open_kinds_parse_only_with_the_prefix_and_never_resolve_to_an_engine_kind() {
        assert_eq!(
            RecordKind::from_wire("verification"),
            Some(RecordKind::Engine(CheckKind::Verification))
        );
        assert_eq!(
            RecordKind::from_wire("x-step-walk"),
            Some(RecordKind::Foreign("x-step-walk".to_string()))
        );
        for bad in ["step-walk", "x-", "x-Step", "x--a", "x-a-", "X-a"] {
            assert!(RecordKind::from_wire(bad).is_none(), "{bad}");
        }
        assert!(RecordKind::vocabulary_hint().contains("x-<name>"));
        let mut r = rec("m--e", "ok", "h");
        r.kind = Some("x-step-walk".to_string());
        assert_eq!(r.resolved_kind(), None);
        assert_eq!(r.foreign_kind(), Some("x-step-walk"));
        r.kind = None;
        assert_eq!(r.resolved_kind(), Some(CheckKind::Verification));
        r.kind = Some("conformance".to_string());
        assert_eq!(r.resolved_kind(), Some(CheckKind::Conformance));
        // A pre-`x-` unrecognised kind keeps its legacy reading.
        r.kind = Some("mystery".to_string());
        assert_eq!(r.resolved_kind(), Some(CheckKind::Verification));
    }

    #[test]
    fn pre_finding_ledger_lines_parse_and_derive_unchanged_and_findings_round_trip() {
        let tmp = TempDir::new().unwrap();
        let ledger = CheckLedger::for_workspace(tmp.path());
        let dir = check_ledger_path(tmp.path());
        std::fs::create_dir_all(dir.parent().unwrap()).unwrap();
        // A line written before findings existed: no `finding`, no `kind`.
        std::fs::write(
            &dir,
            "{\"ts\":1,\"entity\":\"m--e\",\"verdict\":\"failed\",\"entity_hash\":\"h\",\"actor\":\"cli\",\"role\":\"unspecified\"}\n",
        )
        .unwrap();
        let old = ledger
            .latest_for_kind("m--e", CheckKind::Verification)
            .unwrap();
        assert!(old.finding.is_none());
        assert_eq!(derive_state(Some(&old), "h"), CheckState::CheckFailed);

        let mut with = rec("m--e", "failed", "h");
        with.ts = 2;
        with.finding = Some(CheckFinding {
            code: "hidden-premise".into(),
            section: Some("step".into()),
            message: "The step assumes X.".into(),
            evidence: None,
        });
        ledger.record(&with).unwrap();
        // A foreign-kind line beside it moves no verification state.
        let mut foreign = rec("m--e", "ok", "h");
        foreign.ts = 3;
        foreign.kind = Some("x-step-walk".into());
        ledger.record(&foreign).unwrap();
        let latest = ledger
            .latest_for_kind("m--e", CheckKind::Verification)
            .unwrap();
        assert_eq!(
            latest.ts, 2,
            "the foreign record is not the latest verification record"
        );
        assert_eq!(latest.finding.as_ref().unwrap().code, "hidden-premise");
        assert_eq!(derive_state(Some(&latest), "h"), CheckState::CheckFailed);
        let text = std::fs::read_to_string(&dir).unwrap();
        assert!(text.contains("\"finding\":{\"code\":\"hidden-premise\",\"section\":\"step\",\"message\":\"The step assumes X.\"}"), "{text}");
        assert!(text.contains("\"kind\":\"x-step-walk\""));
        assert_eq!(text.lines().count(), 3, "append-only");
    }
}