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
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
//! Append-only JSONL event log: `JsonlLog`.
//!
//! Per BUILD_SPEC ยง7, the JSONL mirror is a peer to the SQLite store: it
//! provides **inspectability** (one event per line, grep-able) and
//! **disaster recovery** (the full ledger can be rebuilt from this file
//! alone). Append-only, fsync-per-write, and hash-chained.
//!
//! ## Append protocol
//!
//! 1. The caller hands [`JsonlLog::append`] an [`Event`].
//! 2. The log sets `prev_event_hash` to its current head (or `None` for
//!    the first event).
//! 3. The log re-seals the event via [`crate::hash::seal`], which
//!    recomputes both `payload_hash` and `event_hash` under the canonical
//!    framing.
//! 4. The log writes one JSON line + `\n`, then **fsyncs the file**.
//! 5. The new `event_hash` becomes the head.
//!
//! Re-sealing on append means callers don't need to pre-populate the
//! hashes (they're an artifact of the chain, not the event's identity).
//!
//! ## Why fsync per write
//!
//! The JSONL log is the disaster-recovery source of truth. An event that
//! is "appended" but lost on power loss leaves the SQL store ahead of the
//! mirror โ€” defeating the mirror's purpose. We pay the latency cost
//! (~1ms-10ms per write on commodity SSDs) in exchange for crash safety.
//! Higher-throughput modes (group commit, periodic fsync) are a future
//! optimization gated on a config flag and an ADR.
//!
//! ## What this module does NOT do
//!
//! - Replicate the chain to remote storage (out of scope; future ADR).
//! - Compact or rotate the log (out of scope for v0; planned for Phase 4).
//! - Index the log (the SQL store is the queryable surface).

use std::fs::{File, OpenOptions};
use std::io::{BufRead, BufReader, Read, Seek, SeekFrom, Write};
use std::path::{Path, PathBuf};

use chrono::Utc;
use cortex_core::{
    attestor::Attestor, canonical::canonical_signing_input, schema_migration_v1_to_v2_event, Event,
    EventSource, PolicyDecision, PolicyOutcome, SchemaMigrationV1ToV2Payload,
};
use thiserror::Error;

use crate::anchor_chain::{row_preimage, GENESIS_PREV_SIGNATURE};
use crate::hash::seal;
use crate::signed_row::{b64_decode, b64_encode, RowSignature, SignedRow};

/// Required contributor rule id documenting that the event source tier gate
/// composed into the policy decision for an unsigned JSONL append
/// (ADR 0019 ยง3, ADR 0026 ยง2). The ledger refuses
/// [`EventSource::User`] rows when the final outcome is
/// [`PolicyOutcome::Reject`] or [`PolicyOutcome::Quarantine`].
pub const APPEND_EVENT_SOURCE_TIER_GATE_RULE_ID: &str = "ledger.append.event_source_tier_gate";
/// Required contributor rule id documenting that attestation requirements
/// (ADR 0010 ยง1, ADR 0014 ยง3, ADR 0026 ยง4) composed into the policy
/// decision for an unsigned JSONL append. The contributor MUST vote
/// `Allow` for `EventSource::User`; the ledger refuses authority-bearing
/// rows that lack attestation.
pub const APPEND_ATTESTATION_REQUIRED_RULE_ID: &str = "ledger.append.attestation_required";
/// Required contributor rule id documenting that the runtime mode gate
/// (ADR 0037 ยง2) composed into the policy decision for an unsigned JSONL
/// append. Local-development unsigned ledgers register a `Warn`; trusted
/// modes register `Reject` to prevent unsigned rows from being passed off
/// as authority grade.
pub const APPEND_RUNTIME_MODE_RULE_ID: &str = "ledger.append.runtime_mode";
/// Required contributor rule id documenting that the signing key state at
/// event time satisfies ADR 0023 current-use revalidation for a signed
/// JSONL append. Historical-only or revoked keys vote `Reject` here.
pub const APPEND_SIGNED_KEY_STATE_CURRENT_USE_RULE_ID: &str =
    "ledger.append_signed.key_state_current_use";
/// Required contributor rule id documenting that the signing principal's
/// trust tier satisfies the ADR 0019 minimum for a signed JSONL append.
/// Principals below `Verified` vote `Reject` here.
pub const APPEND_SIGNED_TRUST_TIER_MINIMUM_RULE_ID: &str =
    "ledger.append_signed.trust_tier_minimum";
/// Required contributor rule id documenting that the proposing principal sits
/// in the `Operator` authority class (ADR 0019 ยง3) for a v1 -> v2 schema
/// migration boundary append. Non-operator principals vote `Reject` here; the
/// rule is documented as authority-class so a future ADR 0019 ยง7 scoped
/// `tier_admin` capability can satisfy the same contributor.
pub const SCHEMA_MIGRATION_AUTHORITY_CLASS_RULE_ID: &str =
    "ledger.schema_migration.authority_class";
/// Required contributor rule id documenting that a fresh operator attestation
/// (ADR 0010 ยง1-ยง2) was supplied over the proposed v1 -> v2 boundary payload.
/// Absent or invalid attestation votes `Reject`. ADR 0026 ยง4 forbids
/// `BreakGlass` substituting for this contributor at the migration authority
/// root.
pub const SCHEMA_MIGRATION_ATTESTATION_REQUIRED_RULE_ID: &str =
    "ledger.schema_migration.attestation_required";
/// Required contributor rule id documenting that the signing key supplied for
/// the operator attestation is in current use (ADR 0023 ยง2 / ยง5): the key
/// state at attestation time is `Active`, not `Retired` or `Revoked`. A
/// historical-only signing key votes `Reject` here; ADR 0026 ยง4 forbids
/// `BreakGlass` substituting for this contributor.
pub const SCHEMA_MIGRATION_CURRENT_USE_TEMPORAL_AUTHORITY_RULE_ID: &str =
    "ledger.schema_migration.current_use_temporal_authority";

/// Errors raised by [`JsonlLog`].
#[derive(Debug, Error)]
pub enum JsonlError {
    /// File-system I/O failure.
    #[error("io error on {path:?}: {source}")]
    Io {
        /// Path that was being read or written.
        path: PathBuf,
        /// Underlying I/O error.
        #[source]
        source: std::io::Error,
    },
    /// A JSON decode failed during iteration / verification.
    #[error("json decode error at line {line} in {path:?}: {source}")]
    Decode {
        /// Path being read.
        path: PathBuf,
        /// 1-based line number.
        line: usize,
        /// Underlying serde error.
        #[source]
        source: serde_json::Error,
    },
    /// A JSON encode failed during append.
    #[error("json encode error: {0}")]
    Encode(#[source] serde_json::Error),
    /// Chain verification failed (one or more rows broke the chain).
    ///
    /// Callers needing per-row diagnostics should use
    /// [`crate::audit::verify_chain`] instead.
    #[error("chain verification failed: {0}")]
    ChainBroken(String),
    /// Validation failed before append.
    #[error("validation failed: {0}")]
    Validation(String),
}

/// Append-only JSONL log handle.
///
/// Owns the file path and an in-memory copy of the current chain head.
/// The file handle is opened per write to keep the type `Send + Sync` and
/// to make file-rotation / handoff straightforward (if we ever need it).
///
/// Per Lane 3.D.6 / ADR 0010 ยง1-ยง2 the log also tracks the **previous
/// row's Ed25519 signature bytes** so the next signed append can build
/// the canonical preimage (which couples `S_n` to `S_{n-1}`).
#[derive(Debug)]
pub struct JsonlLog {
    path: PathBuf,
    /// Hex `event_hash` of the most-recently-appended event.
    head: Option<String>,
    /// Number of rows currently in the file.
    len: u64,
    /// 32-byte truncation of the most-recently-appended row's Ed25519
    /// signature (or all-zero genesis sentinel for an empty log). Used
    /// as `S_{n-1}` input to [`row_preimage`] on the next signed append.
    /// We carry only the first 32 bytes because that is what the
    /// canonical lineage hex captures (Ed25519 sigs are 64 bytes; the
    /// canonical preimage hashes the lineage hex string, so the chosen
    /// truncation is what binds rows together โ€” see ADR 0010 ยง2 Option A
    /// "prev_signature digest inside `P_n`").
    last_sig_prefix: [u8; 32],
}

/// Logical identifier (`ledger_id`) for the JSONL chain. Used as part of
/// every row's canonical preimage so signatures from one log cannot be
/// replayed into another.
///
/// Exposed `pub(crate)` so [`crate::audit::verify_signed_chain`] derives
/// the same id from the same path on the verify side.
pub(crate) fn ledger_id_for(path: &Path) -> String {
    path.file_stem()
        .and_then(|s| s.to_str())
        .unwrap_or("cortex-jsonl")
        .to_string()
}

impl JsonlLog {
    /// Open (or create) the log at `path`.
    ///
    /// On open we scan the existing file to recover the head hash and row
    /// count. An empty file (or non-existent path) is a fresh log with no
    /// head.
    pub fn open(path: impl AsRef<Path>) -> Result<Self, JsonlError> {
        let path = path.as_ref().to_path_buf();
        // Touch the file so subsequent appends succeed without a TOCTOU.
        OpenOptions::new()
            .create(true)
            .append(true)
            .open(&path)
            .map_err(|source| JsonlError::Io {
                path: path.clone(),
                source,
            })?;

        // Scan to recover head, len, and last signature prefix.
        let f = File::open(&path).map_err(|source| JsonlError::Io {
            path: path.clone(),
            source,
        })?;
        let reader = BufReader::new(f);
        let mut head: Option<String> = None;
        let mut len: u64 = 0;
        let mut last_sig_prefix: [u8; 32] = GENESIS_PREV_SIGNATURE;
        for (i, line) in reader.lines().enumerate() {
            let line = line.map_err(|source| JsonlError::Io {
                path: path.clone(),
                source,
            })?;
            if line.trim().is_empty() {
                continue;
            }
            let row: SignedRow =
                serde_json::from_str(&line).map_err(|source| JsonlError::Decode {
                    path: path.clone(),
                    line: i + 1,
                    source,
                })?;
            head = Some(row.event.event_hash.clone());
            len += 1;
            if let Some(sig) = &row.signature {
                if let Some(bytes) = b64_decode(&sig.bytes) {
                    if bytes.len() >= 32 {
                        last_sig_prefix.copy_from_slice(&bytes[..32]);
                    } else {
                        // Malformed-but-present signature on disk; leave
                        // last_sig_prefix at the genesis sentinel and let
                        // the audit verifier surface it as BadSignature.
                    }
                }
            } else {
                // Legacy unsigned row: do NOT advance last_sig_prefix.
                // The audit verifier will flag this row's MissingSignature
                // failure; subsequent signed appends will still chain off
                // whatever prior signature was last seen (or genesis).
            }
        }

        Ok(Self {
            path,
            head,
            len,
            last_sig_prefix,
        })
    }

    /// Path of the underlying file.
    #[must_use]
    pub fn path(&self) -> &Path {
        &self.path
    }

    /// Number of rows currently in the log.
    #[must_use]
    pub fn len(&self) -> u64 {
        self.len
    }

    /// Whether the log has zero rows.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.len == 0
    }

    /// Current chain head (`event_hash` of the most recent row).
    ///
    /// `None` for an empty log.
    #[must_use]
    pub fn head(&self) -> Option<&str> {
        self.head.as_deref()
    }

    /// Append one event to the log **without** an Ed25519 signature, gated
    /// through the ADR 0026 enforcement lattice.
    ///
    /// This is the legacy / pre-3.D.6 path. Rows written via this method
    /// **fail** [`crate::audit::verify_signed_chain`] with
    /// [`crate::audit::FailureReason::MissingSignature`] (per ADR 0010 ยง1
    /// "Single asymmetric trust domain": rows without a valid Ed25519
    /// signature do not verify; there is no symmetric-MAC fallback). It
    /// is retained for the local-development ledger path and for tests of
    /// non-attestation features (hash chain, payload framing);
    /// **trusted-history / authority paths MUST use
    /// [`Self::append_signed`]**.
    ///
    /// `policy` is the composed [`PolicyDecision`] for this append and
    /// MUST satisfy:
    ///
    /// 1. The composition includes contributors for
    ///    [`APPEND_EVENT_SOURCE_TIER_GATE_RULE_ID`],
    ///    [`APPEND_ATTESTATION_REQUIRED_RULE_ID`], and
    ///    [`APPEND_RUNTIME_MODE_RULE_ID`]. Callers that skipped composition
    ///    are refused.
    /// 2. When `event.source` is [`EventSource::User`], the attestation
    ///    contributor MUST vote [`PolicyOutcome::Allow`] regardless of
    ///    final outcome. ADR 0026 ยง4 forbids `BreakGlass` from substituting
    ///    for the attestation requirement at the user-event authority
    ///    boundary.
    /// 3. A final outcome of [`PolicyOutcome::Reject`] or
    ///    [`PolicyOutcome::Quarantine`] fails closed and writes nothing.
    pub fn append(
        &mut self,
        mut event: Event,
        policy: &PolicyDecision,
    ) -> Result<String, JsonlError> {
        require_append_contributors(policy)?;
        require_event_source_attestation(policy, &event.source)?;
        require_append_final_outcome(policy, "ledger.append")?;

        event.prev_event_hash = self.head.clone();
        seal(&mut event);
        let row = SignedRow::unsigned(event);
        let line = serde_json::to_string(&row).map_err(JsonlError::Encode)?;
        self.write_line(&line)?;
        self.head = Some(row.event.event_hash.clone());
        self.len += 1;
        // Unsigned append does NOT advance last_sig_prefix.
        Ok(row.event.event_hash)
    }

    /// Append one event with an Ed25519 signature over the canonical
    /// attestation preimage (T-3.D.6, ADR 0010 ยง1-ยง2), gated through the
    /// ADR 0026 enforcement lattice.
    ///
    /// The preimage couples this row's signature to `S_{n-1}` (the
    /// previous row's signature, or the genesis sentinel for the first
    /// row), the row's `event_id`, `payload_hash`, `session_id`,
    /// `ledger_id`, and the signing key's `key_id`. See
    /// [`row_preimage`] for the exact shape.
    ///
    /// `policy` is the composed [`PolicyDecision`] for this signed append
    /// and MUST satisfy:
    ///
    /// 1. The composition includes contributors for
    ///    [`APPEND_SIGNED_KEY_STATE_CURRENT_USE_RULE_ID`] (ADR 0023
    ///    current-use revalidation: historical-only or revoked signing
    ///    keys vote `Reject`) and
    ///    [`APPEND_SIGNED_TRUST_TIER_MINIMUM_RULE_ID`] (ADR 0019: the
    ///    principal MUST sit at or above `Verified`). Callers that skipped
    ///    composition are refused.
    /// 2. The key-state contributor MUST vote [`PolicyOutcome::Allow`]
    ///    regardless of final outcome. ADR 0026 ยง4 forbids `BreakGlass`
    ///    from substituting for current-use revalidation at the signed
    ///    ledger root.
    /// 3. A final outcome of [`PolicyOutcome::Reject`] or
    ///    [`PolicyOutcome::Quarantine`] fails closed and writes nothing.
    ///
    /// Returns the new head hash on success.
    pub fn append_signed(
        &mut self,
        mut event: Event,
        attestor: &dyn Attestor,
        policy: &PolicyDecision,
    ) -> Result<String, JsonlError> {
        require_append_signed_contributors(policy)?;
        require_append_signed_key_state_not_break_glassed(policy)?;
        require_append_final_outcome(policy, "ledger.append_signed")?;

        // Seal hash chain first so payload_hash is available for the
        // attestation preimage.
        event.prev_event_hash = self.head.clone();
        seal(&mut event);

        let signed_at = Utc::now();
        let key_id = attestor.key_id().to_string();
        let ledger_id = ledger_id_for(&self.path);
        let preimage = row_preimage(
            &event,
            &self.last_sig_prefix,
            &ledger_id,
            &key_id,
            signed_at,
        );
        let signing_input = canonical_signing_input(&preimage);
        let sig = attestor.sign(&signing_input);
        let sig_bytes = sig.to_bytes();

        let row = SignedRow {
            event,
            signature: Some(RowSignature {
                schema_version: cortex_core::canonical::SCHEMA_VERSION_ATTESTATION,
                key_id,
                signed_at,
                bytes: b64_encode(&sig_bytes),
            }),
        };
        let line = serde_json::to_string(&row).map_err(JsonlError::Encode)?;
        self.write_line(&line)?;

        self.head = Some(row.event.event_hash.clone());
        self.len += 1;
        // Advance the chain coupling.
        self.last_sig_prefix.copy_from_slice(&sig_bytes[..32]);
        Ok(row.event.event_hash)
    }

    /// Append the schema v1 -> v2 boundary event after the current v1 head,
    /// gated through the ADR 0026 enforcement lattice.
    ///
    /// This helper is intentionally narrow: it validates the typed payload and
    /// refuses to append unless the log's current head matches
    /// `payload.previous_v1_head_hash`. It does not run the full migration or
    /// bump `cortex_core::SCHEMA_VERSION`.
    ///
    /// `policy` is the composed [`PolicyDecision`] for the v1 -> v2 boundary
    /// append (ADR 0026 punch list #17). See
    /// [`Self::append_schema_migration_v1_to_v2_with_event`] for the
    /// preflight contract.
    pub fn append_schema_migration_v1_to_v2(
        &mut self,
        payload: SchemaMigrationV1ToV2Payload,
        policy: &PolicyDecision,
    ) -> Result<String, JsonlError> {
        let (head, _event) = self.append_schema_migration_v1_to_v2_with_event(payload, policy)?;
        Ok(head)
    }

    /// Schema v1 -> v2 boundary append variant that also returns the sealed
    /// [`Event`] written to the log, gated through the ADR 0026 enforcement
    /// lattice.
    ///
    /// Callers that mirror the boundary row into a side store (e.g. the
    /// SQLite events table during `cortex migrate v2` cutover) need the
    /// sealed event in hand. The JSONL row carries the canonical hash chain;
    /// the returned event is byte-identical to what was just persisted (its
    /// `prev_event_hash` and `event_hash` reflect the head couple).
    ///
    /// `policy` is the composed [`PolicyDecision`] for the v1 -> v2 boundary
    /// append and MUST satisfy:
    ///
    /// 1. The composition includes contributors for
    ///    [`SCHEMA_MIGRATION_AUTHORITY_CLASS_RULE_ID`] (ADR 0019 ยง3: the
    ///    proposing principal sits in the `Operator` authority class โ€” a
    ///    non-operator key cannot mint a v2 boundary),
    ///    [`SCHEMA_MIGRATION_ATTESTATION_REQUIRED_RULE_ID`] (ADR 0010 ยง1-ยง2:
    ///    a fresh operator attestation is supplied over the boundary
    ///    payload), and
    ///    [`SCHEMA_MIGRATION_CURRENT_USE_TEMPORAL_AUTHORITY_RULE_ID`]
    ///    (ADR 0023 ยง2 / ยง5: the signing key state at attestation time is
    ///    `Active`, not `Retired` or `Revoked`). Callers that skipped
    ///    composition are refused.
    /// 2. Per ADR 0026 ยง4 (hard wall), the attestation contributor and the
    ///    current-use temporal-authority contributor MUST each vote
    ///    [`PolicyOutcome::Allow`] regardless of final outcome. A
    ///    `BreakGlass` decision MUST NOT substitute for either contributor at
    ///    the migration authority root.
    /// 3. A final outcome of [`PolicyOutcome::Reject`] or
    ///    [`PolicyOutcome::Quarantine`] fails closed and writes nothing.
    pub fn append_schema_migration_v1_to_v2_with_event(
        &mut self,
        payload: SchemaMigrationV1ToV2Payload,
        policy: &PolicyDecision,
    ) -> Result<(String, Event), JsonlError> {
        require_schema_migration_contributors(policy)?;
        require_schema_migration_attestation_not_break_glassed(policy)?;
        require_schema_migration_current_use_not_break_glassed(policy)?;
        require_append_final_outcome(policy, "ledger.schema_migration")?;

        let expected_head = payload.previous_v1_head_hash.clone();
        match self.head.as_deref() {
            Some(head) if head == expected_head => {}
            observed => {
                return Err(JsonlError::Validation(format!(
                    "schema migration boundary previous_v1_head_hash mismatch: observed {observed:?}, expected {expected_head}"
                )));
            }
        }

        let now = Utc::now();
        let event = schema_migration_v1_to_v2_event(payload, now, now, None)
            .map_err(|err| JsonlError::Validation(err.to_string()))?;
        // Mirror what `append` does internally so we can hand the caller the
        // identical sealed event the JSONL row carries (the post-migrate row
        // count refusal helper needs the typed Event, not just the hash, to
        // mirror the boundary into SQLite via `mirror_single_event_into_sqlite`).
        self.append_unchecked_returning_event(event)
    }

    /// Internal: append one event without the ADR 0026 policy preflight,
    /// returning both the sealed event hash and the typed Event.
    ///
    /// Used internally by
    /// [`Self::append_schema_migration_v1_to_v2_with_event`] after its own
    /// migration-specific contributors have been verified. The caller-facing
    /// Event return shape lets the schema v2 cutover mirror the boundary
    /// row into SQLite (post-migrate row-count refusal helper) without
    /// re-iterating the JSONL log. Not exposed outside the crate so
    /// external callers cannot bypass the gate on [`Self::append`].
    fn append_unchecked_returning_event(
        &mut self,
        mut event: Event,
    ) -> Result<(String, Event), JsonlError> {
        event.prev_event_hash = self.head.clone();
        seal(&mut event);
        let row = SignedRow::unsigned(event.clone());
        let line = serde_json::to_string(&row).map_err(JsonlError::Encode)?;
        self.write_line(&line)?;
        self.head = Some(event.event_hash.clone());
        self.len += 1;
        Ok((event.event_hash.clone(), event))
    }

    /// Internal: append one already-formatted JSON line + `\n` and fsync.
    fn write_line(&self, line: &str) -> Result<(), JsonlError> {
        let mut f = OpenOptions::new()
            .create(true)
            .append(true)
            .open(&self.path)
            .map_err(|source| JsonlError::Io {
                path: self.path.clone(),
                source,
            })?;
        f.write_all(line.as_bytes())
            .map_err(|source| JsonlError::Io {
                path: self.path.clone(),
                source,
            })?;
        f.write_all(b"\n").map_err(|source| JsonlError::Io {
            path: self.path.clone(),
            source,
        })?;
        // Fsync per write โ€” see module docs.
        f.sync_all().map_err(|source| JsonlError::Io {
            path: self.path.clone(),
            source,
        })?;
        Ok(())
    }

    /// 32-byte prefix of the most recently appended row's signature, or
    /// the genesis sentinel if no signed row has been appended yet.
    /// Exposed so callers (audit verifier, tests) can reproduce the
    /// chain coupling.
    #[must_use]
    pub fn last_sig_prefix(&self) -> [u8; 32] {
        self.last_sig_prefix
    }

    /// Iterate every row in the log in append order.
    ///
    /// Each item is the parsed [`Event`] (the inner semantic event of the
    /// signed envelope). For access to the row signature use
    /// [`Self::iter_signed`]. Decode errors short-circuit the iterator
    /// and surface as `Err`.
    pub fn iter(&self) -> Result<JsonlIter, JsonlError> {
        let mut f = File::open(&self.path).map_err(|source| JsonlError::Io {
            path: self.path.clone(),
            source,
        })?;
        f.seek(SeekFrom::Start(0))
            .map_err(|source| JsonlError::Io {
                path: self.path.clone(),
                source,
            })?;
        Ok(JsonlIter {
            path: self.path.clone(),
            reader: BufReader::new(Box::new(f) as Box<dyn Read>),
            line: 0,
        })
    }

    /// Iterate every row in the log as [`SignedRow`] envelopes โ€” i.e.
    /// the [`Event`] plus its optional [`RowSignature`].
    ///
    /// Used by [`crate::audit::verify_signed_chain`] to reconstruct the
    /// per-row attestation preimage. Decode errors surface as `Err` and
    /// short-circuit.
    pub fn iter_signed(&self) -> Result<SignedJsonlIter, JsonlError> {
        let f = File::open(&self.path).map_err(|source| JsonlError::Io {
            path: self.path.clone(),
            source,
        })?;
        Ok(SignedJsonlIter {
            path: self.path.clone(),
            reader: BufReader::new(Box::new(f) as Box<dyn Read>),
            line: 0,
        })
    }

    /// Verify the chain end-to-end.
    ///
    /// Walks every row, recomputes both `payload_hash` and `event_hash`
    /// under the canonical framing, and confirms each row's
    /// `prev_event_hash` matches the previous row's `event_hash`. Returns
    /// `Ok(())` on success or [`JsonlError::ChainBroken`] with a short
    /// summary on failure. For per-row diagnostics use
    /// [`crate::audit::verify_chain`].
    pub fn verify_chain(&self) -> Result<(), JsonlError> {
        let mut prev: Option<String> = None;
        for (i, item) in self.iter()?.enumerate() {
            let e = item?;
            // Recompute payload_hash.
            let expected_payload = crate::hash::payload_hash(&e.payload);
            if e.payload_hash != expected_payload {
                return Err(JsonlError::ChainBroken(format!(
                    "row {} payload_hash mismatch",
                    i + 1
                )));
            }
            let expected_event =
                crate::hash::event_hash(e.prev_event_hash.as_deref(), &e.payload_hash);
            if e.event_hash != expected_event {
                return Err(JsonlError::ChainBroken(format!(
                    "row {} event_hash mismatch",
                    i + 1
                )));
            }
            if e.prev_event_hash != prev {
                return Err(JsonlError::ChainBroken(format!(
                    "row {} prev_event_hash does not point at previous row",
                    i + 1
                )));
            }
            prev = Some(e.event_hash.clone());
        }
        Ok(())
    }
}

fn require_append_final_outcome(policy: &PolicyDecision, surface: &str) -> Result<(), JsonlError> {
    match policy.final_outcome {
        PolicyOutcome::Allow | PolicyOutcome::Warn | PolicyOutcome::BreakGlass => Ok(()),
        PolicyOutcome::Quarantine | PolicyOutcome::Reject => Err(JsonlError::Validation(format!(
            "{surface} preflight: composed policy outcome {:?} blocks ledger append",
            policy.final_outcome,
        ))),
    }
}

fn require_contributor(policy: &PolicyDecision, rule_id: &str) -> Result<(), JsonlError> {
    let contains_rule = policy
        .contributing
        .iter()
        .chain(policy.discarded.iter())
        .any(|contribution| contribution.rule_id.as_str() == rule_id);
    if contains_rule {
        Ok(())
    } else {
        Err(JsonlError::Validation(format!(
            "policy decision missing required contributor `{rule_id}`; caller skipped ADR 0026 composition",
        )))
    }
}

fn require_append_contributors(policy: &PolicyDecision) -> Result<(), JsonlError> {
    require_contributor(policy, APPEND_EVENT_SOURCE_TIER_GATE_RULE_ID)?;
    require_contributor(policy, APPEND_ATTESTATION_REQUIRED_RULE_ID)?;
    require_contributor(policy, APPEND_RUNTIME_MODE_RULE_ID)?;
    Ok(())
}

fn require_append_signed_contributors(policy: &PolicyDecision) -> Result<(), JsonlError> {
    require_contributor(policy, APPEND_SIGNED_KEY_STATE_CURRENT_USE_RULE_ID)?;
    require_contributor(policy, APPEND_SIGNED_TRUST_TIER_MINIMUM_RULE_ID)?;
    Ok(())
}

fn require_event_source_attestation(
    policy: &PolicyDecision,
    source: &EventSource,
) -> Result<(), JsonlError> {
    // ADR 0026 ยง4: at the User-event authority boundary, the attestation
    // contributor must itself have voted `Allow`. A BreakGlass final
    // outcome MUST NOT substitute for missing attestation on a user-sourced
    // row.
    if !matches!(source, EventSource::User) {
        return Ok(());
    }
    let attestation = policy
        .contributing
        .iter()
        .chain(policy.discarded.iter())
        .find(|contribution| {
            contribution.rule_id.as_str() == APPEND_ATTESTATION_REQUIRED_RULE_ID
        })
        .ok_or_else(|| {
            JsonlError::Validation(format!(
                "ledger.append preflight: required attestation contributor `{APPEND_ATTESTATION_REQUIRED_RULE_ID}` is absent from the policy decision for EventSource::User"
            ))
        })?;
    if attestation.outcome == PolicyOutcome::Allow {
        Ok(())
    } else {
        Err(JsonlError::Validation(format!(
            "ledger.append preflight: attestation contributor `{APPEND_ATTESTATION_REQUIRED_RULE_ID}` returned {:?} for EventSource::User; ADR 0026 ยง4 forbids BreakGlass substituting for attestation",
            attestation.outcome,
        )))
    }
}

fn require_schema_migration_contributors(policy: &PolicyDecision) -> Result<(), JsonlError> {
    require_contributor(policy, SCHEMA_MIGRATION_AUTHORITY_CLASS_RULE_ID)?;
    require_contributor(policy, SCHEMA_MIGRATION_ATTESTATION_REQUIRED_RULE_ID)?;
    require_contributor(
        policy,
        SCHEMA_MIGRATION_CURRENT_USE_TEMPORAL_AUTHORITY_RULE_ID,
    )?;
    Ok(())
}

fn require_schema_migration_attestation_not_break_glassed(
    policy: &PolicyDecision,
) -> Result<(), JsonlError> {
    // ADR 0026 ยง4: at the migration authority root, the attestation
    // contributor (ADR 0010) MUST itself have voted `Allow`. A `BreakGlass`
    // final outcome MUST NOT substitute for missing operator attestation at
    // the v1 -> v2 boundary; this is the long-promised `--unattended-migrate`
    // blocker.
    let attestation = policy
        .contributing
        .iter()
        .chain(policy.discarded.iter())
        .find(|contribution| {
            contribution.rule_id.as_str() == SCHEMA_MIGRATION_ATTESTATION_REQUIRED_RULE_ID
        })
        .ok_or_else(|| {
            JsonlError::Validation(format!(
                "ledger.schema_migration preflight: required attestation contributor `{SCHEMA_MIGRATION_ATTESTATION_REQUIRED_RULE_ID}` is absent from the policy decision"
            ))
        })?;
    if attestation.outcome == PolicyOutcome::Allow {
        Ok(())
    } else {
        Err(JsonlError::Validation(format!(
            "ledger.schema_migration preflight: attestation contributor `{SCHEMA_MIGRATION_ATTESTATION_REQUIRED_RULE_ID}` returned {:?}; ADR 0026 ยง4 forbids BreakGlass substituting for operator attestation at the migration authority root",
            attestation.outcome,
        )))
    }
}

fn require_schema_migration_current_use_not_break_glassed(
    policy: &PolicyDecision,
) -> Result<(), JsonlError> {
    // ADR 0023 ยง5 + ADR 0026 ยง4: the current-use temporal-authority
    // contributor MUST itself have voted `Allow`. A historical-only or
    // revoked signing key vote of `Reject` here MUST NOT be overridden by a
    // `BreakGlass` final outcome at the migration authority root.
    let current_use = policy
        .contributing
        .iter()
        .chain(policy.discarded.iter())
        .find(|contribution| {
            contribution.rule_id.as_str()
                == SCHEMA_MIGRATION_CURRENT_USE_TEMPORAL_AUTHORITY_RULE_ID
        })
        .ok_or_else(|| {
            JsonlError::Validation(format!(
                "ledger.schema_migration preflight: required current-use contributor `{SCHEMA_MIGRATION_CURRENT_USE_TEMPORAL_AUTHORITY_RULE_ID}` is absent from the policy decision"
            ))
        })?;
    if current_use.outcome == PolicyOutcome::Allow {
        Ok(())
    } else {
        Err(JsonlError::Validation(format!(
            "ledger.schema_migration preflight: current-use contributor `{SCHEMA_MIGRATION_CURRENT_USE_TEMPORAL_AUTHORITY_RULE_ID}` returned {:?}; ADR 0023 forbids historical-only or revoked signing keys at the migration authority root",
            current_use.outcome,
        )))
    }
}

fn require_append_signed_key_state_not_break_glassed(
    policy: &PolicyDecision,
) -> Result<(), JsonlError> {
    // ADR 0023 + ADR 0026 ยง4: the current-use revalidation contributor
    // must itself have voted `Allow` for a signed append. A revoked or
    // historical-only key vote of `Reject` here MUST NOT be overridden by
    // a BreakGlass final outcome on the signed ledger root.
    let key_state = policy
        .contributing
        .iter()
        .chain(policy.discarded.iter())
        .find(|contribution| {
            contribution.rule_id.as_str() == APPEND_SIGNED_KEY_STATE_CURRENT_USE_RULE_ID
        })
        .ok_or_else(|| {
            JsonlError::Validation(format!(
                "ledger.append_signed preflight: required current-use contributor `{APPEND_SIGNED_KEY_STATE_CURRENT_USE_RULE_ID}` is absent from the policy decision"
            ))
        })?;
    if key_state.outcome == PolicyOutcome::Allow {
        Ok(())
    } else {
        Err(JsonlError::Validation(format!(
            "ledger.append_signed preflight: current-use contributor `{APPEND_SIGNED_KEY_STATE_CURRENT_USE_RULE_ID}` returned {:?}; ADR 0023 forbids historical-only or revoked signing keys at the trusted ledger root",
            key_state.outcome,
        )))
    }
}

/// Build a [`PolicyDecision`] that satisfies [`JsonlLog::append`] inputs
/// for the happy path. Intended for tests and fixtures only.
///
/// Production callers MUST compose
/// [`APPEND_EVENT_SOURCE_TIER_GATE_RULE_ID`],
/// [`APPEND_ATTESTATION_REQUIRED_RULE_ID`], and
/// [`APPEND_RUNTIME_MODE_RULE_ID`] from real trust-tier evidence, real
/// attestation evidence, and the active runtime mode. This helper is
/// exposed unconditionally because integration test crates outside
/// `cortex-ledger` need the same fixture shape; the `_test_allow` suffix
/// is the contract that documents intent.
#[must_use]
pub fn append_policy_decision_test_allow() -> PolicyDecision {
    use cortex_core::{compose_policy_outcomes, PolicyContribution};
    compose_policy_outcomes(
        vec![
            PolicyContribution::new(
                APPEND_EVENT_SOURCE_TIER_GATE_RULE_ID,
                PolicyOutcome::Allow,
                "test fixture: event source tier gate satisfied",
            )
            .expect("static test contribution is valid"),
            PolicyContribution::new(
                APPEND_ATTESTATION_REQUIRED_RULE_ID,
                PolicyOutcome::Allow,
                "test fixture: attestation requirement satisfied",
            )
            .expect("static test contribution is valid"),
            PolicyContribution::new(
                APPEND_RUNTIME_MODE_RULE_ID,
                PolicyOutcome::Allow,
                "test fixture: runtime mode permits unsigned append",
            )
            .expect("static test contribution is valid"),
        ],
        None,
    )
}

/// Build a [`PolicyDecision`] that satisfies
/// [`JsonlLog::append_schema_migration_v1_to_v2`] inputs for the happy path.
/// Intended for tests and fixtures only.
///
/// Production callers MUST compose
/// [`SCHEMA_MIGRATION_AUTHORITY_CLASS_RULE_ID`] from a real ADR 0019
/// authority-class evaluation, [`SCHEMA_MIGRATION_ATTESTATION_REQUIRED_RULE_ID`]
/// from a real ADR 0010 attestation envelope verification, and
/// [`SCHEMA_MIGRATION_CURRENT_USE_TEMPORAL_AUTHORITY_RULE_ID`] from real
/// ADR 0023 key-state-at-event-time evidence. The `_test_allow` suffix is the
/// contract that documents intent; this helper exists so integration tests
/// outside `cortex-ledger` can build a fixture decision without re-encoding
/// the rule-id list.
#[must_use]
pub fn schema_migration_v1_to_v2_policy_decision_test_allow() -> PolicyDecision {
    use cortex_core::{compose_policy_outcomes, PolicyContribution};
    compose_policy_outcomes(
        vec![
            PolicyContribution::new(
                SCHEMA_MIGRATION_AUTHORITY_CLASS_RULE_ID,
                PolicyOutcome::Allow,
                "test fixture: operator authority class satisfied",
            )
            .expect("static test contribution is valid"),
            PolicyContribution::new(
                SCHEMA_MIGRATION_ATTESTATION_REQUIRED_RULE_ID,
                PolicyOutcome::Allow,
                "test fixture: operator attestation present",
            )
            .expect("static test contribution is valid"),
            PolicyContribution::new(
                SCHEMA_MIGRATION_CURRENT_USE_TEMPORAL_AUTHORITY_RULE_ID,
                PolicyOutcome::Allow,
                "test fixture: signing key state is current-use",
            )
            .expect("static test contribution is valid"),
        ],
        None,
    )
}

/// Build a [`PolicyDecision`] that satisfies [`JsonlLog::append_signed`]
/// inputs for the happy path. Intended for tests and fixtures only; see
/// [`append_policy_decision_test_allow`] for the production-caller
/// contract.
#[must_use]
pub fn append_signed_policy_decision_test_allow() -> PolicyDecision {
    use cortex_core::{compose_policy_outcomes, PolicyContribution};
    compose_policy_outcomes(
        vec![
            PolicyContribution::new(
                APPEND_SIGNED_KEY_STATE_CURRENT_USE_RULE_ID,
                PolicyOutcome::Allow,
                "test fixture: signing key state is current-use",
            )
            .expect("static test contribution is valid"),
            PolicyContribution::new(
                APPEND_SIGNED_TRUST_TIER_MINIMUM_RULE_ID,
                PolicyOutcome::Allow,
                "test fixture: signing principal trust tier satisfies minimum",
            )
            .expect("static test contribution is valid"),
        ],
        None,
    )
}

/// Owning iterator over a [`JsonlLog`].
pub struct JsonlIter {
    path: PathBuf,
    reader: BufReader<Box<dyn Read>>,
    line: usize,
}

impl std::fmt::Debug for JsonlIter {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("JsonlIter")
            .field("path", &self.path)
            .field("line", &self.line)
            .finish()
    }
}

impl Iterator for JsonlIter {
    type Item = Result<Event, JsonlError>;

    fn next(&mut self) -> Option<Self::Item> {
        loop {
            let mut buf = String::new();
            let n = match self.reader.read_line(&mut buf) {
                Ok(n) => n,
                Err(source) => {
                    return Some(Err(JsonlError::Io {
                        path: self.path.clone(),
                        source,
                    }));
                }
            };
            if n == 0 {
                return None; // EOF
            }
            self.line += 1;
            let trimmed = buf.trim();
            if trimmed.is_empty() {
                continue;
            }
            return Some(
                serde_json::from_str::<SignedRow>(trimmed)
                    .map(|row| row.event)
                    .map_err(|source| JsonlError::Decode {
                        path: self.path.clone(),
                        line: self.line,
                        source,
                    }),
            );
        }
    }
}

/// Owning iterator over a [`JsonlLog`] yielding full [`SignedRow`]
/// envelopes (event + optional signature). Used by the Ed25519-aware
/// audit verifier in [`crate::audit::verify_signed_chain`].
pub struct SignedJsonlIter {
    path: PathBuf,
    reader: BufReader<Box<dyn Read>>,
    line: usize,
}

impl std::fmt::Debug for SignedJsonlIter {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("SignedJsonlIter")
            .field("path", &self.path)
            .field("line", &self.line)
            .finish()
    }
}

impl Iterator for SignedJsonlIter {
    type Item = Result<SignedRow, JsonlError>;

    fn next(&mut self) -> Option<Self::Item> {
        loop {
            let mut buf = String::new();
            let n = match self.reader.read_line(&mut buf) {
                Ok(n) => n,
                Err(source) => {
                    return Some(Err(JsonlError::Io {
                        path: self.path.clone(),
                        source,
                    }));
                }
            };
            if n == 0 {
                return None;
            }
            self.line += 1;
            let trimmed = buf.trim();
            if trimmed.is_empty() {
                continue;
            }
            return Some(
                serde_json::from_str::<SignedRow>(trimmed).map_err(|source| JsonlError::Decode {
                    path: self.path.clone(),
                    line: self.line,
                    source,
                }),
            );
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use chrono::TimeZone;
    use cortex_core::{
        compose_policy_outcomes, Event, EventId, EventSource, EventType, PolicyContribution,
        SchemaMigrationV1ToV2Payload, SCHEMA_MIGRATION_V1_TO_V2_EVENT_KIND,
        SCHEMA_MIGRATION_V1_TO_V2_TARGET, SCHEMA_VERSION,
    };
    use tempfile::tempdir;

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

    fn allow_policy() -> PolicyDecision {
        append_policy_decision_test_allow()
    }

    fn migration_allow_policy() -> PolicyDecision {
        schema_migration_v1_to_v2_policy_decision_test_allow()
    }

    /// T-1.B.2 acceptance: append N events, reopen, verify chain.
    #[test]
    fn append_n_reopen_and_verify() {
        let dir = tempdir().unwrap();
        let path = dir.path().join("events.jsonl");

        // Append 25 events.
        let mut log = JsonlLog::open(&path).unwrap();
        let mut heads = Vec::new();
        let policy = allow_policy();
        for i in 0..25u64 {
            let head = log.append(fixture_event(i), &policy).unwrap();
            heads.push(head);
        }
        assert_eq!(log.len(), 25);
        assert_eq!(log.head(), Some(heads.last().unwrap().as_str()));

        // Reopen and verify.
        let log2 = JsonlLog::open(&path).unwrap();
        assert_eq!(log2.len(), 25);
        assert_eq!(log2.head(), Some(heads.last().unwrap().as_str()));
        log2.verify_chain().expect("chain verifies after reopen");

        // Iterate and confirm prev->next linkage.
        let mut prev: Option<String> = None;
        let mut count = 0;
        for item in log2.iter().unwrap() {
            let e = item.unwrap();
            assert_eq!(e.prev_event_hash, prev);
            prev = Some(e.event_hash.clone());
            count += 1;
        }
        assert_eq!(count, 25);
    }

    #[test]
    fn empty_log_verifies() {
        let dir = tempdir().unwrap();
        let path = dir.path().join("empty.jsonl");
        let log = JsonlLog::open(&path).unwrap();
        assert_eq!(log.len(), 0);
        assert!(log.head().is_none());
        log.verify_chain().expect("empty chain is valid");
    }

    #[test]
    fn append_persists_after_drop() {
        let dir = tempdir().unwrap();
        let path = dir.path().join("persist.jsonl");
        {
            let mut log = JsonlLog::open(&path).unwrap();
            let policy = allow_policy();
            log.append(fixture_event(0), &policy).unwrap();
            log.append(fixture_event(1), &policy).unwrap();
            // drop log; fsync should have made the rows durable.
        }
        let log2 = JsonlLog::open(&path).unwrap();
        assert_eq!(log2.len(), 2);
    }

    #[test]
    fn corrupted_payload_fails_verify() {
        let dir = tempdir().unwrap();
        let path = dir.path().join("corrupt.jsonl");
        let mut log = JsonlLog::open(&path).unwrap();
        let policy = allow_policy();
        log.append(fixture_event(0), &policy).unwrap();
        log.append(fixture_event(1), &policy).unwrap();
        log.append(fixture_event(2), &policy).unwrap();

        // Tamper: rewrite the file with a mutated payload on row 2.
        let lines: Vec<String> = std::fs::read_to_string(&path)
            .unwrap()
            .lines()
            .map(|s| s.to_string())
            .collect();
        let mut bad: Event = serde_json::from_str(&lines[1]).unwrap();
        bad.payload = serde_json::json!({"tampered": true});
        let mut new_content = String::new();
        new_content.push_str(&lines[0]);
        new_content.push('\n');
        new_content.push_str(&serde_json::to_string(&bad).unwrap());
        new_content.push('\n');
        new_content.push_str(&lines[2]);
        new_content.push('\n');
        std::fs::write(&path, new_content).unwrap();

        let log2 = JsonlLog::open(&path).unwrap();
        let err = log2.verify_chain().unwrap_err();
        assert!(matches!(err, JsonlError::ChainBroken(_)));
    }

    #[test]
    fn append_after_reopen_continues_chain() {
        let dir = tempdir().unwrap();
        let path = dir.path().join("continue.jsonl");
        let head_before;
        {
            let mut log = JsonlLog::open(&path).unwrap();
            let policy = allow_policy();
            log.append(fixture_event(0), &policy).unwrap();
            head_before = log.append(fixture_event(1), &policy).unwrap();
        }
        let mut log2 = JsonlLog::open(&path).unwrap();
        assert_eq!(log2.head(), Some(head_before.as_str()));
        let head_after = log2.append(fixture_event(2), &allow_policy()).unwrap();
        assert_ne!(head_after, head_before);
        log2.verify_chain().expect("continued chain verifies");
    }

    #[test]
    fn schema_migration_v1_to_v2_event_emitted_after_v1_head() {
        let dir = tempdir().unwrap();
        let path = dir.path().join("schema-boundary.jsonl");
        let mut log = JsonlLog::open(&path).unwrap();
        let previous_v1_head = log.append(fixture_event(0), &allow_policy()).unwrap();
        let payload = SchemaMigrationV1ToV2Payload::new(
            previous_v1_head.clone(),
            "script-digest",
            None,
            "fixture-digest",
        );

        let boundary_head = log
            .append_schema_migration_v1_to_v2(payload, &migration_allow_policy())
            .expect("boundary event appends");

        assert_eq!(log.len(), 2);
        assert_eq!(log.head(), Some(boundary_head.as_str()));
        log.verify_chain().expect("boundary chain verifies");

        let rows = log.iter().unwrap().collect::<Result<Vec<_>, _>>().unwrap();
        let boundary = rows.last().expect("boundary row exists");
        assert_eq!(boundary.schema_version, SCHEMA_MIGRATION_V1_TO_V2_TARGET);
        assert_eq!(boundary.event_type, EventType::SystemNote);
        assert_eq!(boundary.source, EventSource::Runtime);
        assert_eq!(
            boundary.prev_event_hash.as_deref(),
            Some(previous_v1_head.as_str())
        );
        assert_eq!(
            boundary.payload["kind"],
            SCHEMA_MIGRATION_V1_TO_V2_EVENT_KIND
        );
        assert_eq!(
            boundary.payload["payload"]["previous_v1_head_hash"],
            previous_v1_head
        );
    }

    #[test]
    fn schema_migration_v1_to_v2_event_rejects_wrong_previous_head() {
        let dir = tempdir().unwrap();
        let path = dir.path().join("schema-boundary-mismatch.jsonl");
        let mut log = JsonlLog::open(&path).unwrap();
        log.append(fixture_event(0), &allow_policy()).unwrap();
        let payload =
            SchemaMigrationV1ToV2Payload::new("not-current-head", "script-digest", None, "fixture");

        let err = log
            .append_schema_migration_v1_to_v2(payload, &migration_allow_policy())
            .expect_err("wrong previous head must fail");

        assert!(matches!(err, JsonlError::Validation(_)));
        assert_eq!(log.len(), 1);
        log.verify_chain()
            .expect("rejected boundary append must not corrupt chain");
    }

    #[test]
    fn schema_migration_v1_to_v2_refuses_missing_authority_class_contributor() {
        let dir = tempdir().unwrap();
        let path = dir.path().join("schema-boundary-missing-auth.jsonl");
        let mut log = JsonlLog::open(&path).unwrap();
        let previous_v1_head = log.append(fixture_event(0), &allow_policy()).unwrap();
        let payload = SchemaMigrationV1ToV2Payload::new(
            previous_v1_head,
            "script-digest",
            None,
            "fixture-digest",
        );

        // Policy is missing the authority-class contributor.
        let policy = compose_policy_outcomes(
            vec![
                PolicyContribution::new(
                    SCHEMA_MIGRATION_ATTESTATION_REQUIRED_RULE_ID,
                    PolicyOutcome::Allow,
                    "fixture: attestation present",
                )
                .unwrap(),
                PolicyContribution::new(
                    SCHEMA_MIGRATION_CURRENT_USE_TEMPORAL_AUTHORITY_RULE_ID,
                    PolicyOutcome::Allow,
                    "fixture: current use",
                )
                .unwrap(),
            ],
            None,
        );

        let err = log
            .append_schema_migration_v1_to_v2(payload, &policy)
            .expect_err("missing authority-class contributor must fail");
        assert!(matches!(err, JsonlError::Validation(_)));
        assert_eq!(log.len(), 1);
        log.verify_chain()
            .expect("rejected boundary append must not corrupt chain");
    }

    #[test]
    fn schema_migration_v1_to_v2_refuses_reject_outcome() {
        let dir = tempdir().unwrap();
        let path = dir.path().join("schema-boundary-reject.jsonl");
        let mut log = JsonlLog::open(&path).unwrap();
        let previous_v1_head = log.append(fixture_event(0), &allow_policy()).unwrap();
        let payload = SchemaMigrationV1ToV2Payload::new(
            previous_v1_head,
            "script-digest",
            None,
            "fixture-digest",
        );

        // All three contributors present; authority-class refuses with Reject.
        let policy = compose_policy_outcomes(
            vec![
                PolicyContribution::new(
                    SCHEMA_MIGRATION_AUTHORITY_CLASS_RULE_ID,
                    PolicyOutcome::Reject,
                    "fixture: non-operator authority class",
                )
                .unwrap(),
                PolicyContribution::new(
                    SCHEMA_MIGRATION_ATTESTATION_REQUIRED_RULE_ID,
                    PolicyOutcome::Allow,
                    "fixture: attestation present",
                )
                .unwrap(),
                PolicyContribution::new(
                    SCHEMA_MIGRATION_CURRENT_USE_TEMPORAL_AUTHORITY_RULE_ID,
                    PolicyOutcome::Allow,
                    "fixture: current use",
                )
                .unwrap(),
            ],
            None,
        );
        assert_eq!(policy.final_outcome, PolicyOutcome::Reject);

        let err = log
            .append_schema_migration_v1_to_v2(payload, &policy)
            .expect_err("reject outcome must fail closed");
        assert!(matches!(err, JsonlError::Validation(_)));
        assert_eq!(log.len(), 1);
    }

    #[test]
    fn schema_migration_v1_to_v2_refuses_quarantine_outcome() {
        let dir = tempdir().unwrap();
        let path = dir.path().join("schema-boundary-quarantine.jsonl");
        let mut log = JsonlLog::open(&path).unwrap();
        let previous_v1_head = log.append(fixture_event(0), &allow_policy()).unwrap();
        let payload = SchemaMigrationV1ToV2Payload::new(
            previous_v1_head,
            "script-digest",
            None,
            "fixture-digest",
        );

        let policy = compose_policy_outcomes(
            vec![
                PolicyContribution::new(
                    SCHEMA_MIGRATION_AUTHORITY_CLASS_RULE_ID,
                    PolicyOutcome::Quarantine,
                    "fixture: under-trust authority class",
                )
                .unwrap(),
                PolicyContribution::new(
                    SCHEMA_MIGRATION_ATTESTATION_REQUIRED_RULE_ID,
                    PolicyOutcome::Allow,
                    "fixture: attestation present",
                )
                .unwrap(),
                PolicyContribution::new(
                    SCHEMA_MIGRATION_CURRENT_USE_TEMPORAL_AUTHORITY_RULE_ID,
                    PolicyOutcome::Allow,
                    "fixture: current use",
                )
                .unwrap(),
            ],
            None,
        );
        assert_eq!(policy.final_outcome, PolicyOutcome::Quarantine);

        let err = log
            .append_schema_migration_v1_to_v2(payload, &policy)
            .expect_err("quarantine outcome must fail closed");
        assert!(matches!(err, JsonlError::Validation(_)));
        assert_eq!(log.len(), 1);
    }

    #[test]
    fn schema_migration_v1_to_v2_refuses_attestation_break_glass() {
        let dir = tempdir().unwrap();
        let path = dir.path().join("schema-boundary-break-glass.jsonl");
        let mut log = JsonlLog::open(&path).unwrap();
        let previous_v1_head = log.append(fixture_event(0), &allow_policy()).unwrap();
        let payload = SchemaMigrationV1ToV2Payload::new(
            previous_v1_head,
            "script-digest",
            None,
            "fixture-digest",
        );

        // Attestation contributor voted BreakGlass; ADR 0026 ยง4 forbids
        // BreakGlass from substituting for operator attestation here.
        let policy = compose_policy_outcomes(
            vec![
                PolicyContribution::new(
                    SCHEMA_MIGRATION_AUTHORITY_CLASS_RULE_ID,
                    PolicyOutcome::Allow,
                    "fixture: operator authority class",
                )
                .unwrap(),
                PolicyContribution::new(
                    SCHEMA_MIGRATION_ATTESTATION_REQUIRED_RULE_ID,
                    PolicyOutcome::BreakGlass,
                    "fixture: operator attempted break-glass on attestation",
                )
                .unwrap(),
                PolicyContribution::new(
                    SCHEMA_MIGRATION_CURRENT_USE_TEMPORAL_AUTHORITY_RULE_ID,
                    PolicyOutcome::Allow,
                    "fixture: current use",
                )
                .unwrap(),
            ],
            None,
        );

        let err = log
            .append_schema_migration_v1_to_v2(payload, &policy)
            .expect_err("BreakGlass on attestation must fail");
        assert!(matches!(err, JsonlError::Validation(_)));
        assert_eq!(log.len(), 1);
    }

    #[test]
    fn schema_migration_v1_to_v2_refuses_historical_key_current_use() {
        let dir = tempdir().unwrap();
        let path = dir.path().join("schema-boundary-historical-key.jsonl");
        let mut log = JsonlLog::open(&path).unwrap();
        let previous_v1_head = log.append(fixture_event(0), &allow_policy()).unwrap();
        let payload = SchemaMigrationV1ToV2Payload::new(
            previous_v1_head,
            "script-digest",
            None,
            "fixture-digest",
        );

        // Current-use contributor refuses because the signing key is
        // historical-only (Retired or Revoked at attestation time).
        let policy = compose_policy_outcomes(
            vec![
                PolicyContribution::new(
                    SCHEMA_MIGRATION_AUTHORITY_CLASS_RULE_ID,
                    PolicyOutcome::Allow,
                    "fixture: operator authority class",
                )
                .unwrap(),
                PolicyContribution::new(
                    SCHEMA_MIGRATION_ATTESTATION_REQUIRED_RULE_ID,
                    PolicyOutcome::Allow,
                    "fixture: attestation present",
                )
                .unwrap(),
                PolicyContribution::new(
                    SCHEMA_MIGRATION_CURRENT_USE_TEMPORAL_AUTHORITY_RULE_ID,
                    PolicyOutcome::Reject,
                    "fixture: signing key retired before attestation time",
                )
                .unwrap(),
            ],
            None,
        );

        let err = log
            .append_schema_migration_v1_to_v2(payload, &policy)
            .expect_err("historical-only signing key must fail");
        assert!(matches!(err, JsonlError::Validation(_)));
        assert_eq!(log.len(), 1);
    }

    #[test]
    fn append_refuses_policy_decision_missing_contributors() {
        let dir = tempdir().unwrap();
        let path = dir.path().join("missing-contributor.jsonl");
        let mut log = JsonlLog::open(&path).unwrap();
        // Compose a policy with only one of the three required contributors.
        let policy = compose_policy_outcomes(
            vec![PolicyContribution::new(
                APPEND_EVENT_SOURCE_TIER_GATE_RULE_ID,
                PolicyOutcome::Allow,
                "fixture: tier gate only",
            )
            .unwrap()],
            None,
        );

        let err = log
            .append(fixture_event(0), &policy)
            .expect_err("missing contributor must fail");
        assert!(matches!(err, JsonlError::Validation(_)));
        assert_eq!(log.len(), 0);
    }

    #[test]
    fn append_refuses_reject_outcome() {
        let dir = tempdir().unwrap();
        let path = dir.path().join("reject-outcome.jsonl");
        let mut log = JsonlLog::open(&path).unwrap();
        let policy = compose_policy_outcomes(
            vec![
                PolicyContribution::new(
                    APPEND_EVENT_SOURCE_TIER_GATE_RULE_ID,
                    PolicyOutcome::Reject,
                    "fixture: tier gate refuses",
                )
                .unwrap(),
                PolicyContribution::new(
                    APPEND_ATTESTATION_REQUIRED_RULE_ID,
                    PolicyOutcome::Allow,
                    "fixture: attestation present",
                )
                .unwrap(),
                PolicyContribution::new(
                    APPEND_RUNTIME_MODE_RULE_ID,
                    PolicyOutcome::Allow,
                    "fixture: runtime mode permits unsigned",
                )
                .unwrap(),
            ],
            None,
        );
        assert_eq!(policy.final_outcome, PolicyOutcome::Reject);

        let err = log
            .append(fixture_event(0), &policy)
            .expect_err("reject outcome must fail closed");
        assert!(matches!(err, JsonlError::Validation(_)));
        assert_eq!(log.len(), 0);
    }

    #[test]
    fn append_refuses_user_event_when_attestation_contributor_not_allow() {
        let dir = tempdir().unwrap();
        let path = dir.path().join("user-attestation.jsonl");
        let mut log = JsonlLog::open(&path).unwrap();
        // Attestation says Warn, not Allow; ADR 0026 ยง4 forbids BreakGlass /
        // Warn substituting for attestation at the User authority boundary.
        let policy = compose_policy_outcomes(
            vec![
                PolicyContribution::new(
                    APPEND_EVENT_SOURCE_TIER_GATE_RULE_ID,
                    PolicyOutcome::Allow,
                    "fixture: tier gate allows",
                )
                .unwrap(),
                PolicyContribution::new(
                    APPEND_ATTESTATION_REQUIRED_RULE_ID,
                    PolicyOutcome::Warn,
                    "fixture: attestation warning",
                )
                .unwrap(),
                PolicyContribution::new(
                    APPEND_RUNTIME_MODE_RULE_ID,
                    PolicyOutcome::Allow,
                    "fixture: runtime mode permits unsigned",
                )
                .unwrap(),
            ],
            None,
        );
        // Final outcome is Warn, but EventSource::User still must fail.
        let err = log
            .append(fixture_event(0), &policy)
            .expect_err("User event without Allow attestation must fail");
        assert!(matches!(err, JsonlError::Validation(_)));
        assert_eq!(log.len(), 0);
    }

    #[test]
    fn append_allows_warn_outcome() {
        let dir = tempdir().unwrap();
        let path = dir.path().join("warn-outcome.jsonl");
        let mut log = JsonlLog::open(&path).unwrap();
        // Warn final outcome with Allow attestation must still append for
        // an EventSource::User row (the local-development ledger pattern).
        let policy = compose_policy_outcomes(
            vec![
                PolicyContribution::new(
                    APPEND_EVENT_SOURCE_TIER_GATE_RULE_ID,
                    PolicyOutcome::Allow,
                    "fixture: tier gate allows",
                )
                .unwrap(),
                PolicyContribution::new(
                    APPEND_ATTESTATION_REQUIRED_RULE_ID,
                    PolicyOutcome::Allow,
                    "fixture: attestation present",
                )
                .unwrap(),
                PolicyContribution::new(
                    APPEND_RUNTIME_MODE_RULE_ID,
                    PolicyOutcome::Warn,
                    "fixture: runtime mode is local-development",
                )
                .unwrap(),
            ],
            None,
        );
        assert_eq!(policy.final_outcome, PolicyOutcome::Warn);
        log.append(fixture_event(0), &policy)
            .expect("warn outcome must still append");
        assert_eq!(log.len(), 1);
    }
}