crtx-ledger 0.1.0

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
//! Position-bound external anchor primitive (ADR 0013).
//!
//! A ledger anchor binds a human-correlation timestamp to both the logical
//! chain position and the event hash at that exact position:
//! `(timestamp, event_count, chain_head_hash)`.
//!
//! The text format is deliberately small and fail-closed:
//!
//! ```text
//! # cortex-ledger-anchor-format: 1
//! <timestamp_rfc3339> <event_count> <chain_head_hash>
//! ```
//!
//! Unknown format headers, malformed fields, or extra structure are parse
//! errors. Verification recomputes the hash chain from the JSONL rows and
//! compares the stored hash at `event_count`; it does not trust only the
//! current tip hash.

use std::fmt;
use std::fs::File;
use std::io::{BufRead, BufReader, Read};
use std::path::{Path, PathBuf};
use std::str::FromStr;

use chrono::{DateTime, SecondsFormat, Utc};
use thiserror::Error;

use crate::hash::{event_hash, payload_hash, HEX_HASH_LEN};
use crate::jsonl::JsonlError;
use crate::signed_row::SignedRow;

/// Header required at the top of every v1 ledger anchor text.
pub const ANCHOR_FORMAT_HEADER_V1: &str = "# cortex-ledger-anchor-format: 1";

/// Position-bound ledger anchor payload.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LedgerAnchor {
    /// Operator-local or wall-clock timestamp for human correlation.
    pub timestamp: DateTime<Utc>,
    /// Total event count at anchor time. Position `n` means row `n` in
    /// append order, so `chain_head_hash` must equal the event hash on
    /// that row.
    pub event_count: u64,
    /// Lowercase hex event hash at exactly [`Self::event_count`].
    pub chain_head_hash: String,
}

impl LedgerAnchor {
    /// Build an anchor, validating fields exactly as the text parser does.
    pub fn new(
        timestamp: DateTime<Utc>,
        event_count: u64,
        chain_head_hash: impl Into<String>,
    ) -> Result<Self, AnchorParseError> {
        let chain_head_hash = chain_head_hash.into();
        validate_chain_head_hash(&chain_head_hash)?;
        Ok(Self {
            timestamp,
            event_count,
            chain_head_hash,
        })
    }

    /// Render this anchor in the canonical ADR 0013 v1 text format.
    #[must_use]
    pub fn to_anchor_text(&self) -> String {
        format!(
            "{ANCHOR_FORMAT_HEADER_V1}\n{} {} {}\n",
            self.timestamp.to_rfc3339_opts(SecondsFormat::Secs, true),
            self.event_count,
            self.chain_head_hash
        )
    }
}

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

impl FromStr for LedgerAnchor {
    type Err = AnchorParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        parse_anchor(s)
    }
}

/// Parse a v1 ledger anchor from text.
pub fn parse_anchor(input: &str) -> Result<LedgerAnchor, AnchorParseError> {
    let mut lines = input.lines();
    let Some(header) = lines.next() else {
        return Err(AnchorParseError::MissingHeader);
    };
    if header != ANCHOR_FORMAT_HEADER_V1 {
        return Err(AnchorParseError::UnknownFormatHeader {
            observed: header.to_string(),
        });
    }

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

    let parts: Vec<&str> = body.split(' ').collect();
    if parts.len() != 3 || parts.iter().any(|part| part.is_empty()) {
        return Err(AnchorParseError::MalformedBody {
            reason: "expected exactly: <timestamp> <event_count> <chain_head_hash>".to_string(),
        });
    }

    let timestamp = DateTime::parse_from_rfc3339(parts[0])
        .map_err(|source| AnchorParseError::InvalidTimestamp {
            value: parts[0].to_string(),
            message: source.to_string(),
        })?
        .with_timezone(&Utc);
    let event_count =
        parts[1]
            .parse::<u64>()
            .map_err(|source| AnchorParseError::InvalidEventCount {
                value: parts[1].to_string(),
                message: source.to_string(),
            })?;
    let chain_head_hash = parts[2].to_string();
    validate_chain_head_hash(&chain_head_hash)?;

    Ok(LedgerAnchor {
        timestamp,
        event_count,
        chain_head_hash,
    })
}

/// Parse a v1 ledger anchor history from repeated canonical anchor records.
///
/// The history format is deliberately just the existing fail-closed v1 anchor
/// record repeated back-to-back:
///
/// ```text
/// # cortex-ledger-anchor-format: 1
/// <timestamp_rfc3339> <event_count> <chain_head_hash>
/// # cortex-ledger-anchor-format: 1
/// <timestamp_rfc3339> <event_count> <chain_head_hash>
/// ```
///
/// Blank separators, unknown headers, incomplete records, or extra structure
/// are parse errors. Monotonicity is checked by [`verify_anchor_history`].
pub fn parse_anchor_history(input: &str) -> Result<Vec<LedgerAnchor>, AnchorParseError> {
    let mut lines = input.lines();
    let mut anchors = Vec::new();

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

    if anchors.is_empty() {
        return Err(AnchorParseError::MissingHeader);
    }
    Ok(anchors)
}

/// Verify one anchor against a JSONL ledger file.
///
/// This is ADR 0013 weak-mode primitive verification: the current chain must
/// contain at least `anchor.event_count` rows and the recomputed event hash at
/// that exact position must match `anchor.chain_head_hash`.
pub fn verify_anchor(
    path: impl AsRef<Path>,
    anchor: &LedgerAnchor,
) -> Result<AnchorVerification, AnchorVerifyError> {
    let path = path.as_ref().to_path_buf();
    let file = File::open(&path).map_err(|source| JsonlError::Io {
        path: path.clone(),
        source,
    })?;
    let mut prev_event_hash: Option<String> = None;
    let mut db_count = 0u64;
    let mut hash_at_anchor_position: Option<String> = None;

    for (i, line_result) in BufReader::new(file).lines().enumerate() {
        let line = i + 1;
        let line_text = line_result.map_err(|source| JsonlError::Io {
            path: path.clone(),
            source,
        })?;
        let trimmed = line_text.trim();
        if trimmed.is_empty() {
            continue;
        }
        let row: SignedRow =
            serde_json::from_str(trimmed).map_err(|source| JsonlError::Decode {
                path: path.clone(),
                line,
                source,
            })?;
        let event = row.event;
        db_count += 1;

        let expected_payload_hash = payload_hash(&event.payload);
        if event.payload_hash != expected_payload_hash {
            return Err(AnchorVerifyError::ChainBroken {
                path,
                line,
                reason: format!(
                    "payload_hash mismatch: observed {}, expected {expected_payload_hash}",
                    event.payload_hash
                ),
            });
        }

        let expected_event_hash = event_hash(event.prev_event_hash.as_deref(), &event.payload_hash);
        if event.event_hash != expected_event_hash {
            return Err(AnchorVerifyError::ChainBroken {
                path,
                line,
                reason: format!(
                    "event_hash mismatch: observed {}, expected {expected_event_hash}",
                    event.event_hash
                ),
            });
        }

        if event.prev_event_hash != prev_event_hash {
            return Err(AnchorVerifyError::ChainBroken {
                path,
                line,
                reason: format!(
                    "prev_event_hash mismatch: observed {:?}, expected {:?}",
                    event.prev_event_hash, prev_event_hash
                ),
            });
        }

        if db_count == anchor.event_count {
            hash_at_anchor_position = Some(event.event_hash.clone());
        }
        prev_event_hash = Some(event.event_hash);
    }

    if db_count < anchor.event_count {
        return Err(AnchorVerifyError::Truncated {
            path,
            db_count,
            anchor_event_count: anchor.event_count,
        });
    }

    let observed = hash_at_anchor_position.ok_or_else(|| AnchorVerifyError::MissingPosition {
        path: path.clone(),
        anchor_event_count: anchor.event_count,
    })?;
    if observed != anchor.chain_head_hash {
        return Err(AnchorVerifyError::PositionHashMismatch {
            path,
            event_count: anchor.event_count,
            observed,
            expected: anchor.chain_head_hash.clone(),
        });
    }

    Ok(AnchorVerification {
        path,
        db_count,
        db_head_hash: prev_event_hash,
        anchor: anchor.clone(),
    })
}

/// Build a current position-bound anchor after verifying the JSONL ledger chain.
///
/// Empty ledgers cannot be anchored because ADR 0013 anchors bind to an event
/// position and event hash, not to the absence of rows.
pub fn current_anchor(
    path: impl AsRef<Path>,
    timestamp: DateTime<Utc>,
) -> Result<LedgerAnchor, AnchorVerifyError> {
    let path = path.as_ref().to_path_buf();
    let file = File::open(&path).map_err(|source| JsonlError::Io {
        path: path.clone(),
        source,
    })?;
    let mut prev_event_hash: Option<String> = None;
    let mut db_count = 0u64;

    for (i, line_result) in BufReader::new(file).lines().enumerate() {
        let line = i + 1;
        let line_text = line_result.map_err(|source| JsonlError::Io {
            path: path.clone(),
            source,
        })?;
        let trimmed = line_text.trim();
        if trimmed.is_empty() {
            continue;
        }
        let row: SignedRow =
            serde_json::from_str(trimmed).map_err(|source| JsonlError::Decode {
                path: path.clone(),
                line,
                source,
            })?;
        let event = row.event;
        db_count += 1;

        let expected_payload_hash = payload_hash(&event.payload);
        if event.payload_hash != expected_payload_hash {
            return Err(AnchorVerifyError::ChainBroken {
                path,
                line,
                reason: format!(
                    "payload_hash mismatch: observed {}, expected {expected_payload_hash}",
                    event.payload_hash
                ),
            });
        }

        let expected_event_hash = event_hash(event.prev_event_hash.as_deref(), &event.payload_hash);
        if event.event_hash != expected_event_hash {
            return Err(AnchorVerifyError::ChainBroken {
                path,
                line,
                reason: format!(
                    "event_hash mismatch: observed {}, expected {expected_event_hash}",
                    event.event_hash
                ),
            });
        }

        if event.prev_event_hash != prev_event_hash {
            return Err(AnchorVerifyError::ChainBroken {
                path,
                line,
                reason: format!(
                    "prev_event_hash mismatch: observed {:?}, expected {:?}",
                    event.prev_event_hash, prev_event_hash
                ),
            });
        }

        prev_event_hash = Some(event.event_hash);
    }

    let Some(chain_head_hash) = prev_event_hash else {
        return Err(AnchorVerifyError::EmptyLedger { path });
    };
    LedgerAnchor::new(timestamp, db_count, chain_head_hash)
        .map_err(|source| AnchorVerifyError::InternalAnchorBuild { path, source })
}

/// Verify a monotonic multi-anchor history against a JSONL ledger file.
///
/// This is the local strong-mode primitive for ADR 0013: every anchor in the
/// supplied history must individually verify against the ledger, and the
/// published anchor stream must never move backwards in `event_count`.
pub fn verify_anchor_history(
    ledger_path: impl AsRef<Path>,
    history_path: impl AsRef<Path>,
) -> Result<AnchorHistoryVerification, AnchorHistoryVerifyError> {
    let history_path = history_path.as_ref().to_path_buf();
    let mut text = String::new();
    File::open(&history_path)
        .map_err(|source| AnchorHistoryVerifyError::ReadHistory {
            path: history_path.clone(),
            source,
        })?
        .read_to_string(&mut text)
        .map_err(|source| AnchorHistoryVerifyError::ReadHistory {
            path: history_path.clone(),
            source,
        })?;

    let anchors =
        parse_anchor_history(&text).map_err(|source| AnchorHistoryVerifyError::Parse {
            path: history_path.clone(),
            source,
        })?;

    let mut previous_event_count = None;
    for (index, anchor) in anchors.iter().enumerate() {
        if let Some(previous_event_count) = previous_event_count {
            if anchor.event_count < previous_event_count {
                return Err(AnchorHistoryVerifyError::NonMonotonic {
                    path: history_path,
                    anchor_index: index + 1,
                    previous_event_count,
                    event_count: anchor.event_count,
                });
            }
        }
        previous_event_count = Some(anchor.event_count);
    }

    let mut latest_verification = None;
    for (index, anchor) in anchors.iter().enumerate() {
        let verification = verify_anchor(&ledger_path, anchor).map_err(|source| {
            AnchorHistoryVerifyError::Anchor {
                path: history_path.clone(),
                anchor_index: index + 1,
                source: Box::new(source),
            }
        })?;
        latest_verification = Some(verification);
    }

    let latest_verification = latest_verification.expect("non-empty anchor history was parsed");
    Ok(AnchorHistoryVerification {
        path: latest_verification.path,
        history_path,
        db_count: latest_verification.db_count,
        db_head_hash: latest_verification.db_head_hash,
        anchors_verified: anchors.len(),
        latest_anchor: latest_verification.anchor,
    })
}

/// Successful anchor verification summary.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AnchorVerification {
    /// Ledger path that was verified.
    pub path: PathBuf,
    /// Number of rows observed in the current ledger.
    pub db_count: u64,
    /// Current tip hash after scanning the ledger, or `None` for an empty
    /// ledger.
    pub db_head_hash: Option<String>,
    /// Anchor that was verified.
    pub anchor: LedgerAnchor,
}

/// Successful multi-anchor history verification summary.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AnchorHistoryVerification {
    /// Ledger path that was verified.
    pub path: PathBuf,
    /// Anchor history path that was verified.
    pub history_path: PathBuf,
    /// Number of rows observed in the current ledger.
    pub db_count: u64,
    /// Current tip hash after scanning the ledger, or `None` for an empty
    /// ledger.
    pub db_head_hash: Option<String>,
    /// Number of anchor records verified.
    pub anchors_verified: usize,
    /// Latest anchor in the monotonic history.
    pub latest_anchor: LedgerAnchor,
}

/// Parse errors for the v1 ledger anchor text format.
#[derive(Debug, Clone, PartialEq, Eq, Error)]
pub enum AnchorParseError {
    /// No first line was present.
    #[error("missing ledger anchor format header")]
    MissingHeader,
    /// Header was present but was not the supported v1 header.
    #[error("unknown ledger anchor format header: {observed}")]
    UnknownFormatHeader {
        /// Header line found in the input.
        observed: String,
    },
    /// Header was present but the payload line was absent.
    #[error("missing ledger anchor body")]
    MissingBody,
    /// Body did not have the exact three-field structure.
    #[error("malformed ledger anchor body: {reason}")]
    MalformedBody {
        /// Human-readable parse failure.
        reason: String,
    },
    /// More non-format structure followed the body line.
    #[error("ledger anchor has trailing content")]
    TrailingContent,
    /// Timestamp was not valid RFC 3339.
    #[error("invalid ledger anchor timestamp {value}: {message}")]
    InvalidTimestamp {
        /// Timestamp field as parsed from the input.
        value: String,
        /// Parser error message.
        message: String,
    },
    /// Event count was not a valid `u64`.
    #[error("invalid ledger anchor event_count {value}: {message}")]
    InvalidEventCount {
        /// Event-count field as parsed from the input.
        value: String,
        /// Parser error message.
        message: String,
    },
    /// Chain head hash was not lowercase 64-character hex.
    #[error("invalid ledger anchor chain_head_hash: {value}")]
    InvalidChainHeadHash {
        /// Hash field as parsed from the input.
        value: String,
    },
}

/// Verification errors for an anchor history checked against a JSONL ledger.
#[derive(Debug, Error)]
pub enum AnchorHistoryVerifyError {
    /// The history file could not be opened or read.
    #[error("failed to read anchor history {path:?}: {source}")]
    ReadHistory {
        /// Anchor history path that was being read.
        path: PathBuf,
        /// I/O failure.
        source: std::io::Error,
    },
    /// The anchor history text did not parse as repeated v1 anchor records.
    #[error("invalid anchor history {path:?}: {source}")]
    Parse {
        /// Anchor history path that was being parsed.
        path: PathBuf,
        /// Parse failure.
        source: AnchorParseError,
    },
    /// A later anchor moved backwards in logical event position.
    #[error(
        "anchor history is non-monotonic at record {anchor_index}: event_count {event_count} follows {previous_event_count}"
    )]
    NonMonotonic {
        /// Anchor history path that was being verified.
        path: PathBuf,
        /// 1-based anchor record index.
        anchor_index: usize,
        /// Previous anchor event count.
        previous_event_count: u64,
        /// Current anchor event count.
        event_count: u64,
    },
    /// One record in the history failed single-anchor verification.
    #[error("anchor history record {anchor_index} failed verification in {path:?}: {source}")]
    Anchor {
        /// Anchor history path that was being verified.
        path: PathBuf,
        /// 1-based anchor record index.
        anchor_index: usize,
        /// Single-anchor verification failure.
        source: Box<AnchorVerifyError>,
    },
}

/// Verification errors for an anchor checked against a JSONL ledger.
#[derive(Debug, Error)]
pub enum AnchorVerifyError {
    /// The ledger could not be opened, decoded, or scanned.
    #[error(transparent)]
    Jsonl(#[from] JsonlError),
    /// The ledger had no event rows to bind an anchor to.
    #[error("cannot anchor empty ledger {path:?}")]
    EmptyLedger {
        /// Ledger path that was being scanned.
        path: PathBuf,
    },
    /// The verifier produced fields that did not satisfy the anchor format.
    #[error("failed to build current ledger anchor for {path:?}: {source}")]
    InternalAnchorBuild {
        /// Ledger path that was being scanned.
        path: PathBuf,
        /// Anchor validation failure.
        source: AnchorParseError,
    },
    /// The ledger hash chain itself is invalid.
    #[error("ledger chain broken at line {line} in {path:?}: {reason}")]
    ChainBroken {
        /// Ledger path that was being verified.
        path: PathBuf,
        /// 1-based JSONL line number.
        line: usize,
        /// Human-readable chain failure.
        reason: String,
    },
    /// Current ledger is shorter than the anchored position.
    #[error(
        "ledger is shorter than anchor: db_count {db_count}, anchor_event_count {anchor_event_count}"
    )]
    Truncated {
        /// Ledger path that was being verified.
        path: PathBuf,
        /// Current number of rows in the ledger.
        db_count: u64,
        /// Event count required by the anchor.
        anchor_event_count: u64,
    },
    /// The anchor names a position that has no event hash, such as zero.
    #[error("ledger anchor position {anchor_event_count} has no event hash")]
    MissingPosition {
        /// Ledger path that was being verified.
        path: PathBuf,
        /// Event count required by the anchor.
        anchor_event_count: u64,
    },
    /// Recomputed hash at the anchored position did not match the anchor.
    #[error(
        "anchor hash mismatch at event_count {event_count}: observed {observed}, expected {expected}"
    )]
    PositionHashMismatch {
        /// Ledger path that was being verified.
        path: PathBuf,
        /// Event count required by the anchor.
        event_count: u64,
        /// Recomputed hash at `event_count`.
        observed: String,
        /// Hash declared by the anchor.
        expected: String,
    },
}

fn validate_chain_head_hash(value: &str) -> Result<(), AnchorParseError> {
    if value.len() != HEX_HASH_LEN
        || !value
            .bytes()
            .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
    {
        return Err(AnchorParseError::InvalidChainHeadHash {
            value: value.to_string(),
        });
    }
    Ok(())
}

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

    use crate::{JsonlLog, SignedRow};

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

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

    fn rewrite_rows(path: &std::path::Path, rows: &[SignedRow]) {
        let text = rows
            .iter()
            .map(|row| serde_json::to_string(row).unwrap())
            .collect::<Vec<_>>()
            .join("\n");
        std::fs::write(path, format!("{text}\n")).unwrap();
    }

    fn write_history(path: &std::path::Path, anchors: &[LedgerAnchor]) {
        let mut text = String::new();
        for anchor in anchors {
            text.push_str(&anchor.to_anchor_text());
        }
        std::fs::write(path, text).unwrap();
    }

    fn read_rows(path: &std::path::Path) -> Vec<SignedRow> {
        std::fs::read_to_string(path)
            .unwrap()
            .lines()
            .map(|line| serde_json::from_str(line).unwrap())
            .collect()
    }

    #[test]
    fn anchor_format_round_trips() {
        let anchor = LedgerAnchor::new(
            Utc.with_ymd_and_hms(2026, 5, 5, 12, 30, 0).unwrap(),
            7,
            "a".repeat(HEX_HASH_LEN),
        )
        .unwrap();

        let text = anchor.to_anchor_text();
        assert_eq!(
            text,
            format!(
                "{ANCHOR_FORMAT_HEADER_V1}\n2026-05-05T12:30:00Z 7 {}\n",
                "a".repeat(HEX_HASH_LEN)
            )
        );
        assert_eq!(parse_anchor(&text).unwrap(), anchor);
    }

    #[test]
    fn anchor_unknown_format_header_fails_closed() {
        let text = format!(
            "# cortex-ledger-anchor-format: 2\n2026-05-05T12:30:00Z 7 {}\n",
            "a".repeat(HEX_HASH_LEN)
        );
        let err = parse_anchor(&text).unwrap_err();
        assert!(matches!(err, AnchorParseError::UnknownFormatHeader { .. }));
    }

    #[test]
    fn anchor_trailing_content_fails_closed() {
        let text = format!(
            "{ANCHOR_FORMAT_HEADER_V1}\n2026-05-05T12:30:00Z 7 {}\nextra\n",
            "a".repeat(HEX_HASH_LEN)
        );
        let err = parse_anchor(&text).unwrap_err();
        assert_eq!(err, AnchorParseError::TrailingContent);
    }

    #[test]
    fn anchor_history_format_round_trips() {
        let anchors = vec![
            LedgerAnchor::new(
                Utc.with_ymd_and_hms(2026, 5, 5, 12, 30, 0).unwrap(),
                1,
                "a".repeat(HEX_HASH_LEN),
            )
            .unwrap(),
            LedgerAnchor::new(
                Utc.with_ymd_and_hms(2026, 5, 5, 12, 31, 0).unwrap(),
                2,
                "b".repeat(HEX_HASH_LEN),
            )
            .unwrap(),
        ];
        let text = anchors
            .iter()
            .map(LedgerAnchor::to_anchor_text)
            .collect::<String>();

        assert_eq!(parse_anchor_history(&text).unwrap(), anchors);
    }

    #[test]
    fn anchor_history_unknown_format_header_fails_closed() {
        let text = format!(
            "# cortex-ledger-anchor-format: 2\n2026-05-05T12:30:00Z 7 {}\n",
            "a".repeat(HEX_HASH_LEN)
        );
        let err = parse_anchor_history(&text).unwrap_err();
        assert!(matches!(err, AnchorParseError::UnknownFormatHeader { .. }));
    }

    #[test]
    fn anchor_history_truncated_record_fails_closed() {
        let err = parse_anchor_history(ANCHOR_FORMAT_HEADER_V1).unwrap_err();
        assert_eq!(err, AnchorParseError::MissingBody);
    }

    #[test]
    fn anchor_correct_head_passes() {
        let (_dir, path, heads) = write_fixture_log(3);
        let anchor = LedgerAnchor::new(
            Utc.with_ymd_and_hms(2026, 5, 5, 12, 30, 0).unwrap(),
            3,
            heads[2].clone(),
        )
        .unwrap();

        let verified = verify_anchor(&path, &anchor).unwrap();
        assert_eq!(verified.db_count, 3);
        assert_eq!(verified.db_head_hash.as_deref(), Some(heads[2].as_str()));
    }

    #[test]
    fn current_anchor_scans_clean_chain_head() {
        let (_dir, path, heads) = write_fixture_log(3);
        let timestamp = Utc.with_ymd_and_hms(2026, 5, 5, 12, 45, 0).unwrap();

        let anchor = current_anchor(&path, timestamp).unwrap();

        assert_eq!(anchor.timestamp, timestamp);
        assert_eq!(anchor.event_count, 3);
        assert_eq!(anchor.chain_head_hash, heads[2]);
        verify_anchor(&path, &anchor).unwrap();
    }

    #[test]
    fn current_anchor_rejects_empty_ledger() {
        let dir = tempdir().unwrap();
        let path = dir.path().join("empty.jsonl");
        std::fs::write(&path, "").unwrap();

        let err = current_anchor(&path, Utc.with_ymd_and_hms(2026, 5, 5, 12, 45, 0).unwrap())
            .unwrap_err();

        assert!(matches!(err, AnchorVerifyError::EmptyLedger { .. }));
    }

    #[test]
    fn anchor_detects_tail_truncation() {
        let (_dir, path, heads) = write_fixture_log(3);
        let anchor = LedgerAnchor::new(
            Utc.with_ymd_and_hms(2026, 5, 5, 12, 30, 0).unwrap(),
            3,
            heads[2].clone(),
        )
        .unwrap();
        let rows = read_rows(&path);
        rewrite_rows(&path, &rows[..2]);

        let err = verify_anchor(&path, &anchor).unwrap_err();
        assert!(matches!(
            err,
            AnchorVerifyError::Truncated {
                db_count: 2,
                anchor_event_count: 3,
                ..
            }
        ));
    }

    #[test]
    fn anchor_wrong_event_count_fails() {
        let (_dir, path, heads) = write_fixture_log(3);
        let anchor = LedgerAnchor::new(
            Utc.with_ymd_and_hms(2026, 5, 5, 12, 30, 0).unwrap(),
            2,
            heads[2].clone(),
        )
        .unwrap();

        let err = verify_anchor(&path, &anchor).unwrap_err();
        assert!(matches!(
            err,
            AnchorVerifyError::PositionHashMismatch { event_count: 2, .. }
        ));
    }

    #[test]
    fn anchor_tampered_line_fails() {
        let (_dir, path, heads) = write_fixture_log(3);
        let anchor = LedgerAnchor::new(
            Utc.with_ymd_and_hms(2026, 5, 5, 12, 30, 0).unwrap(),
            3,
            heads[2].clone(),
        )
        .unwrap();
        let mut rows = read_rows(&path);
        rows[1].event.payload = serde_json::json!({"seq": 99});
        rewrite_rows(&path, &rows);

        let err = verify_anchor(&path, &anchor).unwrap_err();
        assert!(matches!(
            err,
            AnchorVerifyError::ChainBroken { line: 2, .. }
        ));
    }

    #[test]
    fn anchor_history_correct_passes() {
        let (dir, ledger_path, heads) = write_fixture_log(3);
        let history_path = dir.path().join("ANCHOR_HISTORY");
        let anchors = vec![
            LedgerAnchor::new(
                Utc.with_ymd_and_hms(2026, 5, 5, 12, 30, 0).unwrap(),
                1,
                heads[0].clone(),
            )
            .unwrap(),
            LedgerAnchor::new(
                Utc.with_ymd_and_hms(2026, 5, 5, 12, 31, 0).unwrap(),
                3,
                heads[2].clone(),
            )
            .unwrap(),
        ];
        write_history(&history_path, &anchors);

        let verified = verify_anchor_history(&ledger_path, &history_path).unwrap();
        assert_eq!(verified.anchors_verified, 2);
        assert_eq!(verified.latest_anchor.event_count, 3);
        assert_eq!(verified.db_count, 3);
    }

    #[test]
    fn anchor_history_non_monotonic_event_count_fails_closed() {
        let (dir, ledger_path, heads) = write_fixture_log(3);
        let history_path = dir.path().join("ANCHOR_HISTORY");
        let anchors = vec![
            LedgerAnchor::new(
                Utc.with_ymd_and_hms(2026, 5, 5, 12, 30, 0).unwrap(),
                3,
                heads[2].clone(),
            )
            .unwrap(),
            LedgerAnchor::new(
                Utc.with_ymd_and_hms(2026, 5, 5, 12, 31, 0).unwrap(),
                2,
                heads[1].clone(),
            )
            .unwrap(),
        ];
        write_history(&history_path, &anchors);

        let err = verify_anchor_history(&ledger_path, &history_path).unwrap_err();
        assert!(matches!(
            err,
            AnchorHistoryVerifyError::NonMonotonic {
                anchor_index: 2,
                previous_event_count: 3,
                event_count: 2,
                ..
            }
        ));
    }

    #[test]
    fn anchor_history_detects_tail_truncation() {
        let (dir, ledger_path, heads) = write_fixture_log(3);
        let history_path = dir.path().join("ANCHOR_HISTORY");
        let anchor = LedgerAnchor::new(
            Utc.with_ymd_and_hms(2026, 5, 5, 12, 30, 0).unwrap(),
            3,
            heads[2].clone(),
        )
        .unwrap();
        write_history(&history_path, &[anchor]);
        let rows = read_rows(&ledger_path);
        rewrite_rows(&ledger_path, &rows[..2]);

        let err = verify_anchor_history(&ledger_path, &history_path).unwrap_err();
        match err {
            AnchorHistoryVerifyError::Anchor { source, .. } => assert!(matches!(
                source.as_ref(),
                AnchorVerifyError::Truncated {
                    db_count: 2,
                    anchor_event_count: 3,
                    ..
                }
            )),
            other => panic!("expected truncated anchor history verification error, got {other:?}"),
        }
    }
}