crtx-ledger 0.1.1

Append-only event log, hash chain, trace assembly, and audit records.
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
//! External anchor receipt primitive (ADR 0013 Mechanism C foundation).
//!
//! This module defines the **parser-only** v1 surface for the external
//! anchor authority work: the typed [`ExternalSink`] selector, the
//! [`ExternalReceipt`] struct, the canonical header
//! [`EXTERNAL_RECEIPT_FORMAT_HEADER_V1`], and a fail-closed parser for
//! single records and append-only receipt histories.
//!
//! **Out of scope (intentional):** live submission to Rekor or
//! OpenTimestamps, Rekor `SignedEntryTimestamp` cryptographic verification,
//! and OTS `.ots` binary-proof verification. Those wait on operator
//! decisions enumerated in `docs/design/DESIGN_external_anchor_authority.md`
//! §Residual risk — specifically the Rekor public key pin, the
//! ECDSA-P-256 vs Ed25519 choice for `SignedEntryTimestamp`, and the OTS
//! binary proof format. The parser here is sufficient to round-trip
//! receipts that an operator obtained out-of-band and to refuse anything
//! that is not a fully-specified v1 sidecar.
//!
//! The text format mirrors the existing position-bound `LedgerAnchor`
//! format: a one-line `# cortex-external-anchor-receipt-format: 1` header
//! followed by exactly one JSON body line. Receipt histories are the same
//! record repeated back-to-back, with monotonicity on `anchor_event_count`
//! enforced by [`parse_external_receipt_history`].
//!
//! ```text
//! # cortex-external-anchor-receipt-format: 1
//! {"sink":"rekor", "anchor_text_sha256":"<hex>", ...}
//! # cortex-external-anchor-receipt-format: 1
//! {"sink":"opentimestamps", "anchor_text_sha256":"<hex>", ...}
//! ```

pub mod ots;
pub mod rekor;
pub mod trusted_root;

use std::fmt;
use std::path::{Path, PathBuf};
use std::time::Duration;

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use thiserror::Error;

use crate::anchor::{verify_anchor, AnchorParseError, AnchorVerifyError, LedgerAnchor};
use crate::sha256::sha256_hex;

pub use trusted_root::{
    active_trusted_root, ActiveTrustedRoot, TransparencyLogInstance, TransparencyLogPublicKey,
    TrustRootStalenessAnchor, TrustRootStalenessError, TrustedRoot, TrustedRootIoError,
    TrustedRootKeyError, TrustedRootParseError, ValidityPeriod, CACHED_ROOT_STATUS,
    DEFAULT_MAX_TRUST_ROOT_AGE, EMBEDDED_ROOT_STATUS, EMBEDDED_TRUSTED_ROOT_SNAPSHOT_DATE,
    REKOR_TRUSTED_ROOT_TLOG_LOGID_NO_MATCH_INVARIANT, TRUSTED_ROOT_CACHE_STALE_INVARIANT,
    TRUSTED_ROOT_JSON, TRUSTED_ROOT_PARSE_INVARIANT, TRUSTED_ROOT_SNAPSHOT_STALE_INVARIANT,
    TRUSTED_ROOT_STALE_INVARIANT,
};

/// Header required at the top of every v1 external anchor receipt record.
pub const EXTERNAL_RECEIPT_FORMAT_HEADER_V1: &str = "# cortex-external-anchor-receipt-format: 1";

/// SHA-256 hex digest length, in lowercase ASCII characters.
const SHA256_HEX_LEN: usize = 64;

/// BLAKE3 hex digest length used elsewhere in the ledger; reused for
/// `anchor_chain_head_hash` validation since the receipt mirrors a
/// [`crate::LedgerAnchor`] chain head.
const BLAKE3_HEX_LEN: usize = 64;

/// Typed external anchor sink selector.
///
/// `None` is the doctrine default: no external sink is configured and no
/// receipt can be emitted. The two adapter-bound variants are currently
/// parser-only — submitting and verifying with a live network adapter is
/// deferred per the design doc.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ExternalSink {
    /// No external sink configured. Fail-closed default.
    None,
    /// Sigstore Rekor public transparency log.
    Rekor,
    /// OpenTimestamps Bitcoin-rooted calendar proof.
    OpenTimestamps,
}

impl ExternalSink {
    /// Stable wire token for the `sink` field of an [`ExternalReceipt`].
    #[must_use]
    pub const fn as_wire_str(self) -> &'static str {
        match self {
            Self::None => "none",
            Self::Rekor => "rekor",
            Self::OpenTimestamps => "opentimestamps",
        }
    }

    /// Parse a wire-form sink token. Unknown tokens fail closed.
    pub fn from_wire_str(value: &str) -> Result<Self, ExternalReceiptParseError> {
        match value {
            "none" => Ok(Self::None),
            "rekor" => Ok(Self::Rekor),
            "opentimestamps" => Ok(Self::OpenTimestamps),
            other => Err(ExternalReceiptParseError::UnknownSink {
                observed: other.to_string(),
            }),
        }
    }
}

impl fmt::Display for ExternalSink {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_wire_str())
    }
}

/// v1 external anchor receipt sidecar.
///
/// Mirrors the JSON shape in `DESIGN_external_anchor_authority.md` §Receipt
/// shape. `receipt` carries the sink-specific payload and is intentionally
/// left as `serde_json::Value`: Rekor and OpenTimestamps each pin their own
/// shape inside this field, but the live adapters that consume them are
/// deferred. Unknown fields inside `receipt` are not validated here.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ExternalReceipt {
    /// Sink that produced this receipt.
    pub sink: ExternalSink,
    /// Lowercase hex SHA-256 over the canonical [`crate::LedgerAnchor`] text
    /// at the witnessed position. The verifier recomputes this against the
    /// local ledger; mismatch is `external_anchor_receipts.anchor_text_hash.mismatch`.
    pub anchor_text_sha256: String,
    /// Event count at the witnessed position.
    pub anchor_event_count: u64,
    /// Lowercase hex BLAKE3 ledger event hash at `anchor_event_count`.
    pub anchor_chain_head_hash: String,
    /// RFC 3339 submission timestamp recorded by the operator client.
    pub submitted_at: DateTime<Utc>,
    /// Sink endpoint actually contacted (e.g. `https://rekor.sigstore.dev`).
    pub sink_endpoint: String,
    /// Sink-specific payload (Rekor entry envelope or OTS proof envelope).
    pub receipt: serde_json::Value,
}

impl ExternalReceipt {
    /// Render this receipt as a canonical v1 record: header line, then the
    /// JSON body on one line, then a trailing newline.
    pub fn to_record_text(&self) -> Result<String, ExternalReceiptParseError> {
        let body = serde_json::to_string(self).map_err(|source| {
            ExternalReceiptParseError::MalformedBody {
                reason: format!("failed to serialize receipt body: {source}"),
            }
        })?;
        Ok(format!("{EXTERNAL_RECEIPT_FORMAT_HEADER_V1}\n{body}\n"))
    }
}

impl ExternalSink {
    /// Custom serde representation: emit `as_wire_str`, parse via
    /// `from_wire_str`. This keeps the wire token stable even if the enum
    /// reorders.
    fn serialize_sink<S>(sink: &Self, ser: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        ser.serialize_str(sink.as_wire_str())
    }

    fn deserialize_sink<'de, D>(de: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let raw = String::deserialize(de)?;
        Self::from_wire_str(&raw).map_err(serde::de::Error::custom)
    }
}

// The ExternalSink serde adapter has to flow through ExternalReceipt's serde
// derive without losing the wire-token contract. We achieve that by wiring
// the field via #[serde(serialize_with / deserialize_with)] below.
impl Serialize for ExternalSink {
    fn serialize<S>(&self, ser: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        Self::serialize_sink(self, ser)
    }
}

impl<'de> Deserialize<'de> for ExternalSink {
    fn deserialize<D>(de: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        Self::deserialize_sink(de)
    }
}

/// Parse a single v1 external anchor receipt record from text.
///
/// Expects exactly two structural lines: the [`EXTERNAL_RECEIPT_FORMAT_HEADER_V1`]
/// header and a one-line JSON body. Trailing content, missing header, or
/// missing body all fail closed.
pub fn parse_external_receipt(input: &str) -> Result<ExternalReceipt, ExternalReceiptParseError> {
    let mut lines = input.lines();
    let Some(header) = lines.next() else {
        return Err(ExternalReceiptParseError::MissingHeader);
    };
    if header != EXTERNAL_RECEIPT_FORMAT_HEADER_V1 {
        return Err(ExternalReceiptParseError::UnknownFormatHeader {
            observed: header.to_string(),
        });
    }

    let Some(body) = lines.next() else {
        return Err(ExternalReceiptParseError::MissingBody);
    };
    if body.trim() != body {
        return Err(ExternalReceiptParseError::MalformedBody {
            reason: "body line must not have leading or trailing whitespace".to_string(),
        });
    }
    if body.is_empty() {
        return Err(ExternalReceiptParseError::MalformedBody {
            reason: "body line must not be empty".to_string(),
        });
    }
    if lines.next().is_some() {
        return Err(ExternalReceiptParseError::TrailingContent);
    }

    let receipt: ExternalReceipt =
        serde_json::from_str(body).map_err(|source| ExternalReceiptParseError::MalformedBody {
            reason: format!("invalid receipt JSON: {source}"),
        })?;
    validate_external_receipt_fields(&receipt)?;
    Ok(receipt)
}

/// Parse a v1 external anchor receipt history from repeated canonical records.
///
/// Mirrors [`crate::anchor::parse_anchor_history`]: receipts are the
/// `header\nbody\n` record repeated back-to-back. Monotonicity on
/// `anchor_event_count` is enforced — a later record may equal but must not
/// be less than the previous record's count. An empty history is a parse
/// error.
pub fn parse_external_receipt_history(
    input: &str,
) -> Result<Vec<ExternalReceipt>, ExternalReceiptParseError> {
    let mut lines = input.lines();
    let mut receipts = Vec::new();

    loop {
        let Some(header) = lines.next() else {
            break;
        };
        let Some(body) = lines.next() else {
            return Err(ExternalReceiptParseError::MissingBody);
        };
        receipts.push(parse_external_receipt(&format!("{header}\n{body}\n"))?);
    }

    if receipts.is_empty() {
        return Err(ExternalReceiptParseError::MissingHeader);
    }

    let mut previous_event_count: Option<u64> = None;
    for (index, receipt) in receipts.iter().enumerate() {
        if let Some(previous) = previous_event_count {
            if receipt.anchor_event_count < previous {
                return Err(ExternalReceiptParseError::NonMonotonic {
                    receipt_index: index + 1,
                    previous_event_count: previous,
                    event_count: receipt.anchor_event_count,
                });
            }
        }
        previous_event_count = Some(receipt.anchor_event_count);
    }

    Ok(receipts)
}

fn validate_external_receipt_fields(
    receipt: &ExternalReceipt,
) -> Result<(), ExternalReceiptParseError> {
    if receipt.sink == ExternalSink::None {
        return Err(ExternalReceiptParseError::UnknownSink {
            observed: ExternalSink::None.as_wire_str().to_string(),
        });
    }
    validate_lower_hex(
        &receipt.anchor_text_sha256,
        SHA256_HEX_LEN,
        "anchor_text_sha256",
    )?;
    validate_lower_hex(
        &receipt.anchor_chain_head_hash,
        BLAKE3_HEX_LEN,
        "anchor_chain_head_hash",
    )?;
    if receipt.sink_endpoint.is_empty() {
        return Err(ExternalReceiptParseError::MalformedBody {
            reason: "sink_endpoint must not be empty".to_string(),
        });
    }
    if receipt.anchor_event_count == 0 {
        return Err(ExternalReceiptParseError::MalformedBody {
            reason: "anchor_event_count must be positive".to_string(),
        });
    }
    if !receipt.receipt.is_object() {
        return Err(ExternalReceiptParseError::MalformedBody {
            reason: "receipt body field must be a JSON object".to_string(),
        });
    }
    Ok(())
}

fn validate_lower_hex(
    value: &str,
    expected_len: usize,
    field: &'static str,
) -> Result<(), ExternalReceiptParseError> {
    if value.len() != expected_len
        || !value
            .bytes()
            .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
    {
        return Err(ExternalReceiptParseError::InvalidHexField {
            field,
            value: value.to_string(),
            expected_len,
        });
    }
    Ok(())
}

/// Parse errors for the v1 external anchor receipt text format.
#[derive(Debug, Clone, PartialEq, Eq, Error)]
pub enum ExternalReceiptParseError {
    /// No first line was present.
    #[error("missing external anchor receipt format header")]
    MissingHeader,
    /// Header was present but was not the supported v1 header.
    #[error("unknown external anchor receipt format header: {observed}")]
    UnknownFormatHeader {
        /// Header line found in the input.
        observed: String,
    },
    /// Header was present but the body line was absent.
    #[error("missing external anchor receipt body")]
    MissingBody,
    /// Body did not parse as a valid v1 receipt JSON document.
    #[error("malformed external anchor receipt body: {reason}")]
    MalformedBody {
        /// Human-readable parse failure.
        reason: String,
    },
    /// Extra non-format structure followed the body line.
    #[error("external anchor receipt has trailing content")]
    TrailingContent,
    /// Receipt referenced an unknown sink token.
    #[error("unknown external anchor receipt sink: {observed}")]
    UnknownSink {
        /// Sink token as parsed from the input.
        observed: String,
    },
    /// A hex field did not have the expected length or lowercase ASCII shape.
    #[error("invalid external anchor receipt {field}: expected {expected_len} lowercase hex chars, got `{value}`")]
    InvalidHexField {
        /// Field name in the receipt envelope.
        field: &'static str,
        /// Field value as parsed from the input.
        value: String,
        /// Expected number of hex characters.
        expected_len: usize,
    },
    /// Receipt history moved backwards in logical event position.
    #[error(
        "external anchor receipt history is non-monotonic at record {receipt_index}: event_count {event_count} follows {previous_event_count}"
    )]
    NonMonotonic {
        /// 1-based receipt record index.
        receipt_index: usize,
        /// Previous receipt event count.
        previous_event_count: u64,
        /// Current receipt event count.
        event_count: u64,
    },
}

/// I/O errors when reading a receipt history file off disk.
#[derive(Debug, Error)]
pub enum ExternalReceiptHistoryIoError {
    /// The history file could not be opened or read.
    #[error("failed to read external anchor receipt history {path:?}: {source}")]
    ReadHistory {
        /// Receipt history path that was being read.
        path: PathBuf,
        /// I/O failure.
        source: std::io::Error,
    },
    /// The receipt history text did not parse as repeated v1 receipt records.
    #[error("invalid external anchor receipt history {path:?}: {source}")]
    Parse {
        /// Receipt history path that was being parsed.
        path: PathBuf,
        /// Parse failure.
        source: ExternalReceiptParseError,
    },
}

/// Read a receipt history file and return the parsed monotonic record list.
pub fn read_external_receipt_history(
    path: impl Into<PathBuf>,
) -> Result<Vec<ExternalReceipt>, ExternalReceiptHistoryIoError> {
    let path = path.into();
    let text = std::fs::read_to_string(&path).map_err(|source| {
        ExternalReceiptHistoryIoError::ReadHistory {
            path: path.clone(),
            source,
        }
    })?;
    parse_external_receipt_history(&text)
        .map_err(|source| ExternalReceiptHistoryIoError::Parse { path, source })
}

/// Stable invariant identifier emitted when the recomputed
/// `anchor_text_sha256` for an external receipt does not match the local
/// ledger. Surfaced both in CLI diagnostics and in any future export
/// artifact so wrappers can grep for the exact token.
pub const ANCHOR_TEXT_HASH_MISMATCH_INVARIANT: &str =
    "external_anchor_receipts.anchor_text_hash.mismatch";

/// Stable status emitted by [`verify_external_receipts`] today: the parser
/// has confirmed the receipt envelope is well-formed and the local
/// position-bound anchor it claims matches the ledger, but the live Rekor
/// signature / OTS proof verification adapters are deferred. Operators and
/// dashboards key off this token to distinguish "parsed only" from a
/// future "fully cryptographically verified" status.
pub const PARSED_ONLY_VERIFICATION_STATUS: &str = "parsed_only_signature_verification_pending";

/// Successful external-receipt verification summary.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ExternalReceiptVerification {
    /// Ledger path that was verified against.
    pub path: PathBuf,
    /// Receipt history path that was verified.
    pub receipts_path: PathBuf,
    /// Number of rows observed in the current ledger after scanning the
    /// last receipt position.
    pub db_count: u64,
    /// Number of receipts parsed and parser-verified.
    pub receipts_verified: usize,
    /// The latest receipt that was verified — has the largest
    /// `anchor_event_count`.
    pub latest_receipt: ExternalReceipt,
    /// Stable status string. See [`PARSED_ONLY_VERIFICATION_STATUS`].
    pub status: &'static str,
    /// Provenance token for the trusted root that was in force during
    /// verification. Either [`EMBEDDED_ROOT_STATUS`] when no operator
    /// cache was supplied or could be loaded, or [`CACHED_ROOT_STATUS`]
    /// when a refreshed cache was active.
    pub trust_root_status: &'static str,
    /// Activation timestamp of the trusted root that was in force.
    pub trust_root_signed_at: Option<DateTime<Utc>>,
}

/// Verification errors for an external receipt history checked against a
/// JSONL ledger.
#[derive(Debug, Error)]
pub enum ExternalReceiptVerifyError {
    /// The receipt history file could not be read.
    #[error("failed to read external anchor receipt history {path:?}: {source}")]
    ReadHistory {
        /// Receipt history path that was being read.
        path: PathBuf,
        /// I/O failure.
        source: std::io::Error,
    },
    /// The receipt history did not parse as repeated v1 records.
    #[error("invalid external anchor receipt history {path:?}: {source}")]
    Parse {
        /// Receipt history path that was being parsed.
        path: PathBuf,
        /// Parse failure.
        source: ExternalReceiptParseError,
    },
    /// One receipt referenced a chain-head hash that does not validate as a
    /// canonical [`LedgerAnchor`].
    #[error(
        "external anchor receipt {receipt_index} in {path:?} carries a malformed anchor: {source}"
    )]
    Anchor {
        /// Receipt history path that was being verified.
        path: PathBuf,
        /// 1-based receipt record index.
        receipt_index: usize,
        /// Anchor field validation failure.
        source: AnchorParseError,
    },
    /// The receipt's position-bound anchor failed to verify against the local ledger.
    #[error(
        "external anchor receipt {receipt_index} in {path:?} failed local anchor verification: {source}"
    )]
    AnchorVerify {
        /// Receipt history path that was being verified.
        path: PathBuf,
        /// 1-based receipt record index.
        receipt_index: usize,
        /// Local-ledger anchor verification failure.
        source: Box<AnchorVerifyError>,
    },
    /// The recomputed `anchor_text_sha256` did not match the receipt-declared value.
    #[error(
        "{invariant}: external anchor receipt {receipt_index} in {path:?} declared anchor_text_sha256 {declared} but local ledger recomputes {observed}"
    )]
    AnchorTextHashMismatch {
        /// Stable invariant token, equal to [`ANCHOR_TEXT_HASH_MISMATCH_INVARIANT`].
        invariant: &'static str,
        /// Receipt history path that was being verified.
        path: PathBuf,
        /// 1-based receipt record index.
        receipt_index: usize,
        /// Anchor-text hash declared by the receipt.
        declared: String,
        /// Anchor-text hash recomputed from the local ledger.
        observed: String,
    },
    /// The cached or embedded `trusted_root.json` is older than the
    /// operator-configured staleness window. Emits the stable
    /// [`TRUSTED_ROOT_STALE_INVARIANT`].
    #[error(
        "{invariant}: trusted_root.json (status={trust_root_status}) signed_at {signed_at:?} is stale beyond max_age {max_age:?} at now {now}"
    )]
    TrustedRootStale {
        /// Stable invariant token, equal to [`TRUSTED_ROOT_STALE_INVARIANT`].
        invariant: &'static str,
        /// Provenance token: [`EMBEDDED_ROOT_STATUS`] or [`CACHED_ROOT_STATUS`].
        trust_root_status: &'static str,
        /// Cache path that was inspected, if any.
        cache_path: Option<PathBuf>,
        /// Latest `validFor.start` observed in the active trust root.
        signed_at: Option<DateTime<Utc>>,
        /// Wall-clock used to compute staleness.
        now: DateTime<Utc>,
        /// Maximum age permitted by the operator policy.
        max_age: Duration,
    },
    /// The cached `trusted_root.json` could not be loaded — I/O or parse
    /// failure on the operator-supplied path. The embedded fallback path
    /// is selected by passing `None` for the cache; this variant only
    /// fires when a cache path was supplied AND the file existed.
    #[error("{invariant}: failed to load trusted_root.json from {path:?}: {source}")]
    TrustedRootIo {
        /// Stable invariant token, equal to [`TRUSTED_ROOT_PARSE_INVARIANT`].
        invariant: &'static str,
        /// Cache path that was being inspected.
        path: PathBuf,
        /// Underlying I/O / parse failure.
        source: Box<TrustedRootIoError>,
    },
}

/// Verify a v1 external anchor receipt history against the local JSONL
/// ledger using the **parser-only** rules, with the embedded trust root
/// and `Utc::now()` for the staleness gate.
///
/// For each receipt this enforces:
///
/// 1. The receipt envelope parses and the receipt is well-formed.
/// 2. The receipt's `(anchor_event_count, anchor_chain_head_hash)` pair
///    parses as a canonical [`LedgerAnchor`] and verifies against the
///    local ledger via [`verify_anchor`].
/// 3. SHA-256 over the canonical anchor text at that position matches
///    `anchor_text_sha256`. Mismatch returns
///    [`ExternalReceiptVerifyError::AnchorTextHashMismatch`] with the
///    stable [`ANCHOR_TEXT_HASH_MISMATCH_INVARIANT`] token.
/// 4. Monotonicity across the receipt history is enforced by
///    [`parse_external_receipt_history`] before any per-receipt check
///    runs.
/// 5. The active trusted root (embedded snapshot here, see
///    [`verify_external_receipts_with_options`] for cached refresh) is
///    not stale beyond [`DEFAULT_MAX_TRUST_ROOT_AGE`]. The staleness
///    gate fails closed with [`ExternalReceiptVerifyError::TrustedRootStale`].
///
/// **Out of scope today:** Rekor `SignedEntryTimestamp` verification and
/// OpenTimestamps `.ots` proof verification. A successful return from this
/// function carries `status = `[`PARSED_ONLY_VERIFICATION_STATUS`] to make
/// the deferred-authority surface explicit to operators.
pub fn verify_external_receipts(
    ledger_path: impl AsRef<Path>,
    receipts_path: impl Into<PathBuf>,
) -> Result<ExternalReceiptVerification, ExternalReceiptVerifyError> {
    verify_external_receipts_with_options(
        ledger_path,
        receipts_path,
        None,
        Utc::now(),
        DEFAULT_MAX_TRUST_ROOT_AGE,
    )
}

/// Same as [`verify_external_receipts`] but with the trust-root cache
/// path, wall clock, and staleness window injected by the caller.
///
/// `trust_root_cache` is `Some(path)` when the operator has refreshed
/// `trusted_root.json` via `cortex audit anchor refresh-trust`. When the
/// file is missing or unparseable, the embedded snapshot is the
/// fail-closed floor. `now` and `max_age` follow the ADR 0041 pattern of
/// caller-injected freshness inputs (no system clock buried in the trust
/// path) so test fixtures can pin both axes.
pub fn verify_external_receipts_with_options(
    ledger_path: impl AsRef<Path>,
    receipts_path: impl Into<PathBuf>,
    trust_root_cache: Option<&Path>,
    now: DateTime<Utc>,
    max_age: Duration,
) -> Result<ExternalReceiptVerification, ExternalReceiptVerifyError> {
    let receipts_path = receipts_path.into();
    let active = match active_trusted_root(trust_root_cache) {
        Ok(active) => active,
        Err(source) => {
            let path = trust_root_cache
                .map(Path::to_path_buf)
                .unwrap_or_else(|| PathBuf::from("<embedded>"));
            return Err(ExternalReceiptVerifyError::TrustedRootIo {
                invariant: TRUSTED_ROOT_PARSE_INVARIANT,
                path,
                source: Box::new(source),
            });
        }
    };
    // ADR 0013 staleness policy (council Decision #1; 2026-05-15
    // portfolio-extension fix on the 2026-05-12 footnote):
    //
    //   embedded + stale  -> warn-only, allow operation (operator may not
    //                        have refreshed yet; refusing here would brick
    //                        every first-time install)
    //   cached   + stale  -> fail closed (operator HAS refreshed once, the
    //                        refresh cadence has lapsed beyond max_age, so
    //                        external anchor authority cannot stand)
    //
    // Anchor field-choice (Bug J + portfolio extension): cached-path
    // staleness is anchored to the cache file's mtime, NOT the Sigstore
    // tlog signing-key activation date inside the JSON (the latter
    // rotates rarely so would make every release immediately stale).
    // The warn-only branch returns the active status verbatim so callers
    // still see `embedded_snapshot` and can surface the warning.
    let trust_root_status = active.status;
    let trust_root_signed_at = active.root.metadata_signed_at();
    if active.status == CACHED_ROOT_STATUS {
        let cache_path = active
            .cache_path
            .as_deref()
            .expect("CACHED_ROOT_STATUS implies a cache path was inspected");
        let anchor = TrustRootStalenessAnchor::cache_file_mtime(cache_path);
        match active.root.is_stale_at(now, max_age, anchor) {
            Ok(true) => {
                return Err(ExternalReceiptVerifyError::TrustedRootStale {
                    invariant: TRUSTED_ROOT_CACHE_STALE_INVARIANT,
                    trust_root_status,
                    cache_path: active.cache_path,
                    signed_at: trust_root_signed_at,
                    now,
                    max_age,
                });
            }
            Ok(false) => {}
            Err(TrustRootStalenessError::CacheFutureDated { .. }) => {
                // Prior F3 closure: future-dated cache mtime is a
                // dedicated bypass guard, not a parse / I/O failure.
                // Surface it as the `cache_future_dated` invariant so
                // operators and dashboards can pivot on a stable token.
                return Err(ExternalReceiptVerifyError::TrustedRootStale {
                    invariant: trusted_root::STABLE_INVARIANT_TRUSTED_ROOT_CACHE_FUTURE_DATED,
                    trust_root_status,
                    cache_path: active.cache_path,
                    signed_at: trust_root_signed_at,
                    now,
                    max_age,
                });
            }
            Err(source) => {
                return Err(ExternalReceiptVerifyError::TrustedRootIo {
                    invariant: TRUSTED_ROOT_PARSE_INVARIANT,
                    path: cache_path.to_path_buf(),
                    source: Box::new(TrustedRootIoError::Read {
                        path: cache_path.to_path_buf(),
                        source: std::io::Error::other(source.to_string()),
                    }),
                });
            }
        }
    }

    let text = std::fs::read_to_string(&receipts_path).map_err(|source| {
        ExternalReceiptVerifyError::ReadHistory {
            path: receipts_path.clone(),
            source,
        }
    })?;
    let receipts = parse_external_receipt_history(&text).map_err(|source| {
        ExternalReceiptVerifyError::Parse {
            path: receipts_path.clone(),
            source,
        }
    })?;

    // Note: `parse_external_receipt_history` already verified monotonicity
    // and that there is at least one receipt; this expect is structural.
    let mut latest_db_count = 0u64;
    let mut latest_receipt: Option<ExternalReceipt> = None;

    for (index, receipt) in receipts.iter().enumerate() {
        let record_index = index + 1;
        // Build a canonical anchor for the witnessed position. We do not
        // accept the receipt's chain head verbatim — we ask the local
        // ledger to confirm the position-hash pair, just like
        // `verify_anchor` does.
        let anchor = LedgerAnchor::new(
            receipt.submitted_at,
            receipt.anchor_event_count,
            receipt.anchor_chain_head_hash.clone(),
        )
        .map_err(|source| ExternalReceiptVerifyError::Anchor {
            path: receipts_path.clone(),
            receipt_index: record_index,
            source,
        })?;
        let verified = verify_anchor(ledger_path.as_ref(), &anchor).map_err(|source| {
            ExternalReceiptVerifyError::AnchorVerify {
                path: receipts_path.clone(),
                receipt_index: record_index,
                source: Box::new(source),
            }
        })?;
        let recomputed = sha256_hex(anchor.to_anchor_text().as_bytes());
        if recomputed != receipt.anchor_text_sha256 {
            return Err(ExternalReceiptVerifyError::AnchorTextHashMismatch {
                invariant: ANCHOR_TEXT_HASH_MISMATCH_INVARIANT,
                path: receipts_path,
                receipt_index: record_index,
                declared: receipt.anchor_text_sha256.clone(),
                observed: recomputed,
            });
        }
        latest_db_count = verified.db_count;
        latest_receipt = Some(receipt.clone());
    }

    let latest_receipt = latest_receipt.expect("parse_external_receipt_history returns non-empty");
    Ok(ExternalReceiptVerification {
        path: ledger_path.as_ref().to_path_buf(),
        receipts_path,
        db_count: latest_db_count,
        receipts_verified: receipts.len(),
        latest_receipt,
        status: PARSED_ONLY_VERIFICATION_STATUS,
        trust_root_status,
        trust_root_signed_at,
    })
}

/// Helper for callers (CLI, drill scripts, etc.) that need to construct a
/// stable, canonical `anchor_text_sha256` value for a given
/// [`LedgerAnchor`]. Equivalent to `sha256_hex(anchor.to_anchor_text())`.
#[must_use]
pub fn anchor_text_sha256(anchor: &LedgerAnchor) -> String {
    sha256_hex(anchor.to_anchor_text().as_bytes())
}

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

    fn sample_receipt(event_count: u64, sink: ExternalSink) -> ExternalReceipt {
        ExternalReceipt {
            sink,
            anchor_text_sha256: "0".repeat(SHA256_HEX_LEN),
            anchor_event_count: event_count,
            anchor_chain_head_hash: "a".repeat(BLAKE3_HEX_LEN),
            submitted_at: Utc.with_ymd_and_hms(2026, 5, 12, 18, 0, 0).unwrap(),
            sink_endpoint: "https://rekor.sigstore.dev".to_string(),
            receipt: serde_json::json!({"logIndex": 1, "uuid": "abc"}),
        }
    }

    #[test]
    fn parses_clean_record_round_trip() {
        let receipt = sample_receipt(7, ExternalSink::Rekor);
        let text = receipt.to_record_text().unwrap();
        assert!(text.starts_with(EXTERNAL_RECEIPT_FORMAT_HEADER_V1));
        let parsed = parse_external_receipt(&text).unwrap();
        assert_eq!(parsed, receipt);
    }

    #[test]
    fn rejects_unknown_sink_token() {
        let body = serde_json::json!({
            "sink": "unknown-sink",
            "anchor_text_sha256": "0".repeat(SHA256_HEX_LEN),
            "anchor_event_count": 1,
            "anchor_chain_head_hash": "a".repeat(BLAKE3_HEX_LEN),
            "submitted_at": "2026-05-12T18:00:00Z",
            "sink_endpoint": "https://example.invalid",
            "receipt": {},
        });
        let text = format!("{EXTERNAL_RECEIPT_FORMAT_HEADER_V1}\n{body}\n");
        let err = parse_external_receipt(&text).unwrap_err();
        match err {
            ExternalReceiptParseError::MalformedBody { reason } => {
                assert!(
                    reason.contains("unknown external anchor receipt sink"),
                    "{reason}"
                );
            }
            other => panic!("expected MalformedBody, got {other:?}"),
        }
    }

    #[test]
    fn rejects_missing_header() {
        let body = serde_json::to_string(&sample_receipt(1, ExternalSink::Rekor)).unwrap();
        let err = parse_external_receipt(&body).unwrap_err();
        assert!(matches!(
            err,
            ExternalReceiptParseError::UnknownFormatHeader { .. }
        ));
    }

    #[test]
    fn rejects_unknown_format_header() {
        let body = serde_json::to_string(&sample_receipt(1, ExternalSink::Rekor)).unwrap();
        let text = format!("# cortex-external-anchor-receipt-format: 2\n{body}\n");
        let err = parse_external_receipt(&text).unwrap_err();
        assert!(matches!(
            err,
            ExternalReceiptParseError::UnknownFormatHeader { .. }
        ));
    }

    #[test]
    fn rejects_missing_required_field() {
        let body = serde_json::json!({
            "sink": "rekor",
            "anchor_event_count": 1,
            "anchor_chain_head_hash": "a".repeat(BLAKE3_HEX_LEN),
            "submitted_at": "2026-05-12T18:00:00Z",
            "sink_endpoint": "https://example.invalid",
            "receipt": {},
        });
        let text = format!("{EXTERNAL_RECEIPT_FORMAT_HEADER_V1}\n{body}\n");
        let err = parse_external_receipt(&text).unwrap_err();
        match err {
            ExternalReceiptParseError::MalformedBody { reason } => {
                assert!(reason.contains("anchor_text_sha256"), "{reason}");
            }
            other => panic!("expected MalformedBody, got {other:?}"),
        }
    }

    #[test]
    fn rejects_invalid_hex_lengths() {
        let mut receipt = sample_receipt(1, ExternalSink::Rekor);
        receipt.anchor_text_sha256 = "abc".to_string();
        let body = serde_json::to_string(&receipt).unwrap();
        let text = format!("{EXTERNAL_RECEIPT_FORMAT_HEADER_V1}\n{body}\n");
        let err = parse_external_receipt(&text).unwrap_err();
        assert!(matches!(
            err,
            ExternalReceiptParseError::InvalidHexField {
                field: "anchor_text_sha256",
                ..
            }
        ));
    }

    #[test]
    fn rejects_trailing_content() {
        let body = serde_json::to_string(&sample_receipt(1, ExternalSink::Rekor)).unwrap();
        let text = format!("{EXTERNAL_RECEIPT_FORMAT_HEADER_V1}\n{body}\nextra\n");
        let err = parse_external_receipt(&text).unwrap_err();
        assert_eq!(err, ExternalReceiptParseError::TrailingContent);
    }

    #[test]
    fn rejects_none_sink_in_payload() {
        let body = serde_json::json!({
            "sink": "none",
            "anchor_text_sha256": "0".repeat(SHA256_HEX_LEN),
            "anchor_event_count": 1,
            "anchor_chain_head_hash": "a".repeat(BLAKE3_HEX_LEN),
            "submitted_at": "2026-05-12T18:00:00Z",
            "sink_endpoint": "https://example.invalid",
            "receipt": {},
        });
        let text = format!("{EXTERNAL_RECEIPT_FORMAT_HEADER_V1}\n{body}\n");
        let err = parse_external_receipt(&text).unwrap_err();
        assert!(matches!(err, ExternalReceiptParseError::UnknownSink { .. }));
    }

    #[test]
    fn parses_history_round_trip_with_monotonic_records() {
        let r1 = sample_receipt(1, ExternalSink::Rekor);
        let r2 = sample_receipt(3, ExternalSink::OpenTimestamps);
        let text = format!(
            "{}{}",
            r1.to_record_text().unwrap(),
            r2.to_record_text().unwrap()
        );
        let parsed = parse_external_receipt_history(&text).unwrap();
        assert_eq!(parsed, vec![r1, r2]);
    }

    #[test]
    fn history_rejects_non_monotonic_event_count() {
        let r1 = sample_receipt(5, ExternalSink::Rekor);
        let r2 = sample_receipt(2, ExternalSink::Rekor);
        let text = format!(
            "{}{}",
            r1.to_record_text().unwrap(),
            r2.to_record_text().unwrap()
        );
        let err = parse_external_receipt_history(&text).unwrap_err();
        assert!(matches!(
            err,
            ExternalReceiptParseError::NonMonotonic {
                receipt_index: 2,
                previous_event_count: 5,
                event_count: 2,
            }
        ));
    }

    #[test]
    fn history_rejects_truncated_record() {
        let err = parse_external_receipt_history(EXTERNAL_RECEIPT_FORMAT_HEADER_V1).unwrap_err();
        assert_eq!(err, ExternalReceiptParseError::MissingBody);
    }

    #[test]
    fn history_rejects_empty_input() {
        let err = parse_external_receipt_history("").unwrap_err();
        assert_eq!(err, ExternalReceiptParseError::MissingHeader);
    }

    #[test]
    fn sink_wire_tokens_are_stable() {
        assert_eq!(ExternalSink::None.as_wire_str(), "none");
        assert_eq!(ExternalSink::Rekor.as_wire_str(), "rekor");
        assert_eq!(ExternalSink::OpenTimestamps.as_wire_str(), "opentimestamps");
    }

    #[test]
    fn sink_from_wire_str_rejects_garbage() {
        let err = ExternalSink::from_wire_str("garbage").unwrap_err();
        assert!(matches!(err, ExternalReceiptParseError::UnknownSink { .. }));
    }

    // ---------- Slice 3: verify_external_receipts ----------

    use cortex_core::{Event, EventId, EventSource, EventType, SCHEMA_VERSION};
    use tempfile::tempdir;

    use crate::JsonlLog;

    fn ledger_event(seq: u64) -> Event {
        Event {
            id: EventId::new(),
            schema_version: SCHEMA_VERSION,
            observed_at: Utc.with_ymd_and_hms(2026, 5, 12, 18, 0, 0).unwrap(),
            recorded_at: Utc.with_ymd_and_hms(2026, 5, 12, 18, 0, 1).unwrap(),
            source: EventSource::User,
            event_type: EventType::UserMessage,
            trace_id: None,
            session_id: Some("ext-receipt".into()),
            domain_tags: vec![],
            payload: serde_json::json!({"seq": seq}),
            payload_hash: String::new(),
            prev_event_hash: None,
            event_hash: String::new(),
        }
    }

    fn build_ledger(count: u64) -> (tempfile::TempDir, std::path::PathBuf, Vec<String>) {
        let dir = tempdir().unwrap();
        let path = dir.path().join("events.jsonl");
        let mut log = JsonlLog::open(&path).unwrap();
        let mut heads = Vec::new();
        let policy = crate::append_policy_decision_test_allow();
        for seq in 0..count {
            heads.push(log.append(ledger_event(seq), &policy).unwrap());
        }
        (dir, path, heads)
    }

    fn make_canonical_receipt(
        timestamp: DateTime<Utc>,
        event_count: u64,
        chain_head: &str,
        sink: ExternalSink,
    ) -> ExternalReceipt {
        let anchor = LedgerAnchor::new(timestamp, event_count, chain_head.to_string()).unwrap();
        ExternalReceipt {
            sink,
            anchor_text_sha256: anchor_text_sha256(&anchor),
            anchor_event_count: event_count,
            anchor_chain_head_hash: chain_head.to_string(),
            submitted_at: timestamp,
            sink_endpoint: "https://rekor.sigstore.dev".to_string(),
            receipt: serde_json::json!({"logIndex": event_count, "uuid": "fixture"}),
        }
    }

    fn write_receipt_history(path: &Path, receipts: &[ExternalReceipt]) {
        let mut text = String::new();
        for receipt in receipts {
            text.push_str(&receipt.to_record_text().unwrap());
        }
        std::fs::write(path, text).unwrap();
    }

    #[test]
    fn clean_receipt_history_parses_and_verifies() {
        let (_dir, ledger, heads) = build_ledger(3);
        let receipts_path = ledger.parent().unwrap().join("EXTERNAL_ANCHOR_RECEIPTS");
        let r1 = make_canonical_receipt(
            Utc.with_ymd_and_hms(2026, 5, 12, 18, 5, 0).unwrap(),
            1,
            &heads[0],
            ExternalSink::Rekor,
        );
        let r2 = make_canonical_receipt(
            Utc.with_ymd_and_hms(2026, 5, 12, 18, 10, 0).unwrap(),
            3,
            &heads[2],
            ExternalSink::Rekor,
        );
        write_receipt_history(&receipts_path, &[r1, r2.clone()]);

        let verification = verify_external_receipts(&ledger, &receipts_path).unwrap();
        assert_eq!(verification.receipts_verified, 2);
        assert_eq!(verification.latest_receipt, r2);
        assert_eq!(verification.db_count, 3);
        assert_eq!(verification.status, PARSED_ONLY_VERIFICATION_STATUS);
    }

    #[test]
    fn tampered_anchor_text_hash_fails_closed_with_stable_invariant() {
        let (_dir, ledger, heads) = build_ledger(3);
        let receipts_path = ledger.parent().unwrap().join("EXTERNAL_ANCHOR_RECEIPTS");
        let mut r1 = make_canonical_receipt(
            Utc.with_ymd_and_hms(2026, 5, 12, 18, 5, 0).unwrap(),
            3,
            &heads[2],
            ExternalSink::Rekor,
        );
        r1.anchor_text_sha256 = "f".repeat(SHA256_HEX_LEN);
        write_receipt_history(&receipts_path, &[r1]);

        let err = verify_external_receipts(&ledger, &receipts_path).unwrap_err();
        match err {
            ExternalReceiptVerifyError::AnchorTextHashMismatch {
                invariant,
                receipt_index,
                ..
            } => {
                assert_eq!(invariant, ANCHOR_TEXT_HASH_MISMATCH_INVARIANT);
                assert_eq!(receipt_index, 1);
            }
            other => panic!("expected AnchorTextHashMismatch, got {other:?}"),
        }
    }

    #[test]
    fn tampered_anchor_chain_head_hash_fails_closed() {
        let (_dir, ledger, heads) = build_ledger(3);
        let receipts_path = ledger.parent().unwrap().join("EXTERNAL_ANCHOR_RECEIPTS");
        let mut r1 = make_canonical_receipt(
            Utc.with_ymd_and_hms(2026, 5, 12, 18, 5, 0).unwrap(),
            3,
            &heads[2],
            ExternalSink::Rekor,
        );
        // Replace with a valid-shape hash that does not match the ledger.
        r1.anchor_chain_head_hash = "0".repeat(BLAKE3_HEX_LEN);
        // Also resynth anchor_text_sha256 so the AnchorVerify branch
        // fires before the hash mismatch branch — verifies that the
        // local-anchor verification is the load-bearing check.
        let bogus_anchor = LedgerAnchor::new(
            r1.submitted_at,
            r1.anchor_event_count,
            r1.anchor_chain_head_hash.clone(),
        )
        .unwrap();
        r1.anchor_text_sha256 = anchor_text_sha256(&bogus_anchor);
        write_receipt_history(&receipts_path, &[r1]);

        let err = verify_external_receipts(&ledger, &receipts_path).unwrap_err();
        assert!(
            matches!(err, ExternalReceiptVerifyError::AnchorVerify { .. }),
            "got {err:?}"
        );
    }

    #[test]
    fn non_monotonic_receipt_history_fails_closed_before_anchor_check() {
        let (_dir, ledger, heads) = build_ledger(3);
        let receipts_path = ledger.parent().unwrap().join("EXTERNAL_ANCHOR_RECEIPTS");
        let r1 = make_canonical_receipt(
            Utc.with_ymd_and_hms(2026, 5, 12, 18, 5, 0).unwrap(),
            3,
            &heads[2],
            ExternalSink::Rekor,
        );
        let r2 = make_canonical_receipt(
            Utc.with_ymd_and_hms(2026, 5, 12, 18, 10, 0).unwrap(),
            1,
            &heads[0],
            ExternalSink::Rekor,
        );
        write_receipt_history(&receipts_path, &[r1, r2]);

        let err = verify_external_receipts(&ledger, &receipts_path).unwrap_err();
        match err {
            ExternalReceiptVerifyError::Parse { source, .. } => {
                assert!(matches!(
                    source,
                    ExternalReceiptParseError::NonMonotonic {
                        receipt_index: 2,
                        previous_event_count: 3,
                        event_count: 1,
                    }
                ));
            }
            other => panic!("expected Parse(NonMonotonic), got {other:?}"),
        }
    }

    #[test]
    fn missing_receipt_history_file_fails_closed() {
        let dir = tempdir().unwrap();
        let ledger = dir.path().join("events.jsonl");
        std::fs::write(&ledger, "").unwrap();
        let receipts_path = dir.path().join("missing-receipts");
        let err = verify_external_receipts(&ledger, &receipts_path).unwrap_err();
        assert!(matches!(
            err,
            ExternalReceiptVerifyError::ReadHistory { .. }
        ));
    }

    // ---------- Slice 4: trusted-root staleness gate ----------

    fn near_root_now() -> DateTime<Utc> {
        // Pin `now` close to the embedded trust root's latest tlog
        // activation so the staleness gate does not falsely fire when
        // the test wall clock drifts.
        let root = TrustedRoot::embedded().unwrap();
        let signed_at = root.metadata_signed_at().unwrap();
        signed_at + chrono::Duration::days(1)
    }

    fn build_receipts_fixture() -> (tempfile::TempDir, std::path::PathBuf, std::path::PathBuf) {
        let (dir, ledger, heads) = build_ledger(3);
        let receipts_path = ledger.parent().unwrap().join("EXTERNAL_ANCHOR_RECEIPTS");
        let r1 = make_canonical_receipt(
            Utc.with_ymd_and_hms(2026, 5, 12, 18, 5, 0).unwrap(),
            3,
            &heads[2],
            ExternalSink::Rekor,
        );
        write_receipt_history(&receipts_path, &[r1]);
        (dir, ledger, receipts_path)
    }

    #[test]
    fn fresh_cached_root_allows_verification() {
        let (dir, ledger, receipts_path) = build_receipts_fixture();
        let trust_root_path = dir.path().join("trusted_root.json");
        TrustedRoot::embedded()
            .unwrap()
            .write_atomic(&trust_root_path)
            .unwrap();

        let now = near_root_now();
        // Prior F3 closure (2026-05-13): pin the cache file's mtime
        // back to the injected `now`. Without this, the cache mtime
        // (real wall-clock at write time, ~2026-05-13) is ahead of
        // the injected `now` (`signed_at + 1 day` ~2025-09-24) by
        // months, and the future-dated bypass guard correctly fires.
        // We are NOT trying to exercise that guard here; we are
        // pinning the standard "fresh cache mtime, fresh now" path.
        let mtime_systemtime = std::time::SystemTime::UNIX_EPOCH
            + std::time::Duration::from_secs(now.timestamp() as u64);
        std::fs::File::options()
            .write(true)
            .open(&trust_root_path)
            .unwrap()
            .set_modified(mtime_systemtime)
            .expect("set mtime");
        let verification = verify_external_receipts_with_options(
            &ledger,
            &receipts_path,
            Some(&trust_root_path),
            now,
            DEFAULT_MAX_TRUST_ROOT_AGE,
        )
        .expect("fresh cached root verifies");
        assert_eq!(verification.trust_root_status, CACHED_ROOT_STATUS);
        assert!(verification.trust_root_signed_at.is_some());
        assert_eq!(verification.status, PARSED_ONLY_VERIFICATION_STATUS);
    }

    #[test]
    fn cached_root_older_than_31_days_fails_closed_with_cache_stale_invariant() {
        let (dir, ledger, receipts_path) = build_receipts_fixture();
        let trust_root_path = dir.path().join("trusted_root.json");
        TrustedRoot::embedded()
            .unwrap()
            .write_atomic(&trust_root_path)
            .unwrap();

        // 2026-05-15 portfolio extension of Bug J: cached-path staleness
        // is anchored to file mtime, NOT the Sigstore tlog activation
        // inside the JSON. Set the cache file's mtime 31 days in the
        // past so the gate fires on the operator-meaningful datum.
        let now = Utc::now();
        let old_mtime = now - chrono::Duration::days(31);
        let mtime_systemtime = std::time::SystemTime::UNIX_EPOCH
            + std::time::Duration::from_secs(old_mtime.timestamp() as u64);
        std::fs::File::options()
            .write(true)
            .open(&trust_root_path)
            .unwrap()
            .set_modified(mtime_systemtime)
            .expect("set mtime");

        let err = verify_external_receipts_with_options(
            &ledger,
            &receipts_path,
            Some(&trust_root_path),
            now,
            DEFAULT_MAX_TRUST_ROOT_AGE,
        )
        .unwrap_err();
        match err {
            ExternalReceiptVerifyError::TrustedRootStale {
                invariant,
                trust_root_status,
                ..
            } => {
                assert_eq!(invariant, TRUSTED_ROOT_CACHE_STALE_INVARIANT);
                assert_eq!(trust_root_status, CACHED_ROOT_STATUS);
            }
            other => panic!("expected TrustedRootStale, got {other:?}"),
        }
    }

    #[test]
    fn cached_root_with_fresh_mtime_passes_even_when_metadata_old() {
        // 2026-05-15 portfolio extension of Bug J: a freshly-written
        // cache MUST pass the staleness gate even when the embedded
        // JSON's tlog-activation date is months old. This is the
        // structural defense against the metadata_signed_at-derived
        // staleness bug.
        let (dir, ledger, receipts_path) = build_receipts_fixture();
        let trust_root_path = dir.path().join("trusted_root.json");
        TrustedRoot::embedded()
            .unwrap()
            .write_atomic(&trust_root_path)
            .unwrap();
        // Wall clock 1 year past the embedded snapshot's tlog
        // activation. Under the buggy metadata_signed_at anchor this
        // would have fired stale; under the fixed mtime anchor it does
        // not provided the cache file's mtime is also pinned forward.
        let now = TrustedRoot::embedded()
            .unwrap()
            .metadata_signed_at()
            .unwrap()
            + chrono::Duration::days(365);
        // Pin cache mtime to the simulated `now` so the staleness gate
        // sees age=0 instead of negative drift between wall-clock
        // injection and real fs mtime.
        let mtime_systemtime = std::time::SystemTime::UNIX_EPOCH
            + std::time::Duration::from_secs(now.timestamp() as u64);
        std::fs::File::options()
            .write(true)
            .open(&trust_root_path)
            .unwrap()
            .set_modified(mtime_systemtime)
            .expect("set mtime");
        let verification = verify_external_receipts_with_options(
            &ledger,
            &receipts_path,
            Some(&trust_root_path),
            now,
            DEFAULT_MAX_TRUST_ROOT_AGE,
        )
        .expect("fresh cache mtime must pass the staleness gate");
        assert_eq!(verification.trust_root_status, CACHED_ROOT_STATUS);
    }

    #[test]
    fn missing_cache_falls_back_to_embedded_and_allows_even_when_stale() {
        let (dir, ledger, receipts_path) = build_receipts_fixture();
        let missing_cache = dir.path().join("nonexistent-trusted_root.json");
        // Step the clock far past any plausible embedded activation.
        let now = Utc.with_ymd_and_hms(2099, 1, 1, 0, 0, 0).unwrap();

        let verification = verify_external_receipts_with_options(
            &ledger,
            &receipts_path,
            Some(&missing_cache),
            now,
            DEFAULT_MAX_TRUST_ROOT_AGE,
        )
        .expect("missing cache + stale embedded still allows (warn-only)");
        assert_eq!(verification.trust_root_status, EMBEDDED_ROOT_STATUS);
    }

    #[test]
    fn unparseable_cache_fails_closed_with_parse_invariant() {
        let (dir, ledger, receipts_path) = build_receipts_fixture();
        let trust_root_path = dir.path().join("trusted_root.json");
        std::fs::write(&trust_root_path, b"this is not valid json").unwrap();

        let now = near_root_now();
        let err = verify_external_receipts_with_options(
            &ledger,
            &receipts_path,
            Some(&trust_root_path),
            now,
            DEFAULT_MAX_TRUST_ROOT_AGE,
        )
        .unwrap_err();
        match err {
            ExternalReceiptVerifyError::TrustedRootIo { invariant, .. } => {
                assert_eq!(invariant, TRUSTED_ROOT_PARSE_INVARIANT);
            }
            other => panic!("expected TrustedRootIo, got {other:?}"),
        }
    }

    /// Prior F3 closure
    /// (`docs/reviews/CODE_REVIEW_2026-05-12_post_fd779d7.md`): the
    /// audit-verify path used to silently pass when the cached
    /// `trusted_root.json` had a future-dated mtime. The freshness
    /// gate now refuses with the cache-future-dated invariant.
    #[test]
    fn cached_root_with_future_dated_mtime_fails_closed_with_future_dated_invariant() {
        let (dir, ledger, receipts_path) = build_receipts_fixture();
        let trust_root_path = dir.path().join("trusted_root.json");
        TrustedRoot::embedded()
            .unwrap()
            .write_atomic(&trust_root_path)
            .unwrap();

        let now = near_root_now();
        // Touch the cache 70 years into the future — the original
        // `touch -d 2099-01-01` attack shape.
        let future = now + chrono::Duration::days(365 * 70);
        let future_systemtime = std::time::SystemTime::UNIX_EPOCH
            + std::time::Duration::from_secs(future.timestamp() as u64);
        std::fs::File::options()
            .write(true)
            .open(&trust_root_path)
            .unwrap()
            .set_modified(future_systemtime)
            .expect("set mtime");

        let err = verify_external_receipts_with_options(
            &ledger,
            &receipts_path,
            Some(&trust_root_path),
            now,
            DEFAULT_MAX_TRUST_ROOT_AGE,
        )
        .unwrap_err();
        match err {
            ExternalReceiptVerifyError::TrustedRootStale {
                invariant,
                trust_root_status,
                ..
            } => {
                assert_eq!(
                    invariant,
                    trusted_root::STABLE_INVARIANT_TRUSTED_ROOT_CACHE_FUTURE_DATED
                );
                assert_eq!(trust_root_status, CACHED_ROOT_STATUS);
            }
            other => panic!("expected TrustedRootStale with cache_future_dated, got {other:?}"),
        }
    }
}