memstead-base 0.24.0

Engine internals for Memstead — store, parser, validators, mem lifecycle, workspace policy. Published as a dependency of the memstead-cli and memstead-mcp products, not as a supported library — pre-1.0, no API stability promise.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
//! 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 plan-13 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 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, String> {
        let finding: CheckFinding = serde_json::from_value(value)
            .map_err(|e| format!("finding does not match the shape {} ({e})", Self::SHAPE))?;
        finding.validate()?;
        Ok(finding)
    }
}

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,
}

impl CarriedFrom {
    pub fn transition(hash: &str) -> Self {
        Self {
            hash: hash.to_string(),
            reason: CARRY_REASON_TRANSITION.to_string(),
        }
    }

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

/// 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. Informational: a reader
    /// ordering checks by time takes `observed_at` where present and `ts`
    /// otherwise; the engine's own state derivation ("the newest record
    /// of a kind") reads ledger order and ignores both. 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 (plan-13 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 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 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.
pub 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())
    }

    /// 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
            .all()
            .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 carried = CheckRecord {
            entity_hash: post_hash.to_string(),
            carried_from: Some(CarriedFrom::transition(pre_hash)),
            ..latest
        };
        self.record(&carried)?;
        Ok(true)
    }

    /// The records of one mem's entities, oldest first: every record
    /// whose entity id is qualified by `mem`.
    pub fn records_for_mem(&self, mem: &str) -> Vec<CheckRecord> {
        let prefix = format!("{mem}--");
        self.all()
            .into_iter()
            .filter(|r| r.entity.starts_with(&prefix))
            .collect()
    }

    /// 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, in
    /// the order the lines carry; a record already present (the same
    /// bytes) is skipped, so a round trip adds nothing. Unparseable
    /// lines are skipped. Returns the number of records appended.
    /// Rows keep every field they arrived with: identity, role, hash,
    /// timestamp; nothing is rewritten on import.
    pub fn merge_transport_lines(&self, lines: &[u8]) -> std::io::Result<usize> {
        let present: std::collections::HashSet<String> = self
            .all()
            .iter()
            .filter_map(|r| serde_json::to_string(r).ok())
            .collect();
        let mut appended = 0;
        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;
            }
            self.record(&rec)?;
            appended += 1;
        }
        Ok(appended)
    }

    /// All records, oldest first. A missing ledger is an empty one;
    /// unparseable lines are skipped (a torn tail must not poison the
    /// readable history).
    pub fn all(&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()
    }

    /// The newest record for one entity, of any kind. 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.all().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.all()
            .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
                .all()
                .into_iter()
                .rev()
                .find(|r| r.entity == entity && r.kind.as_deref() == Some(kind)),
        }
    }
}

// ---------------------------------------------------------------------------
// 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(),
        }
    }
}

/// 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,
        }
    }

    #[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(&rec("m--a", "failed", "h1")).unwrap();
        ledger.record(&rec("m--b", "ok", "h9")).unwrap();
        ledger.record(&rec("m--a", "ok", "h2")).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.all().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
            .all()
            .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.all();
        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.all().len(), 1, "nothing appended so far");

        assert!(
            ledger
                .carry_transition("m--plan", "x-projection", "h1", "h2")
                .unwrap()
        );
        let all = ledger.all();
        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 {
                hash: "h1".into(),
                reason: CARRY_REASON_TRANSITION.into()
            })
        );
        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());
    }

    /// Criterion 5: 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-plan-15 lines and identity-less callers stay
        // byte-identical.
        assert!(!line.contains("identity"));
    }

    /// Criterion 3: 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"));
    }

    /// Criterion 4: 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();
            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");
    }
}