rite-runtime 0.4.2

Execution engine for Rite ceremonies (internal to the `rite` CLI; no stable API)
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
//! Transcript sink, the durable consumer of [`StepFact`]s.
//!
//! The sink is an inline observer in the executor thread. It records each
//! [`StepFact`] synchronously before the executor proceeds to its next action,
//! and the on-disk implementation `fsync`s the line to the storage device
//! before returning. This invariant, *the transcript is durable before the
//! UI sees the fact* , is what makes the on-disk record the authoritative
//! source of evidence and the live UI a tee of the same stream.
//!
//! # On-disk format (`transcript.jsonl`)
//!
//! Each line is a JSON object with three fields:
//!
//! ```jsonc
//! {"prev_hash": "sha256:…", "at": "2026-06-01T20:34:51Z", "fact": { "type": "step_started", … }}
//! ```
//!
//! `at` is the event's wall-clock time, supplied by the executor's clock when
//! it emits the fact (the sink records it rather than choosing it, so the time
//! is independent of the storage backend). It is the single uniform timestamp
//! for every event, and part of the hashed line, so it is tamper-evident like
//! the rest of the envelope.
//!
//! The chain is verified by recomputing each line's SHA-256, accumulating it
//! as the expected `prev_hash` of the next line, starting from
//! [`GENESIS_HASH`]. The final transcript fingerprint is the hash of the
//! last line; the JSONL is self-identifying and no sidecar file is written.
//!
//! # Implementations
//!
//! - [`JsonlFileSink`], writes to disk, flushes after every line.
//! - [`InMemorySink`], collects facts in a `Vec` for tests and tooling.

use std::collections::HashSet;
use std::fs::{File, OpenOptions};
use std::io::{self, BufRead, BufReader, BufWriter, Write};
use std::path::{Path, PathBuf};

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

use crate::transcript::compute_fingerprint;
use rite_model::StepFact;

/// SHA-256 fingerprint produced by a [`TranscriptSink::finalize`] call.
///
/// Encoded as `sha256:<lowercase-hex>`, matching the convention used
/// throughout the runtime for artifact and transcript fingerprints.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TranscriptFingerprint(String);

impl TranscriptFingerprint {
    /// Build a fingerprint from an already-formatted `sha256:<hex>` string.
    #[must_use]
    pub fn from_string(s: String) -> Self {
        Self(s)
    }

    /// `sha256:<hex>` representation.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

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

/// Genesis `prev_hash` value used on the very first line of every transcript.
///
/// `sha256:` followed by 64 zero hex digits.
pub const GENESIS_HASH: &str =
    "sha256:0000000000000000000000000000000000000000000000000000000000000000";

/// Synchronous, durable observer of [`StepFact`]s.
///
/// Implementations must record each fact, including syncing it to the
/// underlying storage where applicable, before returning. The executor
/// relies on this to maintain the invariant that the UI never sees a fact
/// that has not been durably persisted.
pub trait TranscriptSink: Send {
    /// Record a single fact, stamped with the caller-supplied event time `at`.
    /// Must persist before returning, the file-backed implementation calls
    /// `sync_data` so a power loss after `record` returns cannot drop the fact.
    ///
    /// `at` is supplied by the executor (the clock owner), not read here, so the
    /// recorded time is independent of the persistence implementation and the
    /// sink stays a deterministic serializer.
    ///
    /// # Errors
    ///
    /// Returns the underlying I/O error if the sink cannot persist the fact.
    fn record(&mut self, at: DateTime<Utc>, fact: &StepFact) -> io::Result<()>;

    /// Finalize the transcript and return its fingerprint.
    ///
    /// Calling `finalize` more than once is implementation-defined; the
    /// default expectation is that the second call returns the cached
    /// fingerprint.
    ///
    /// # Errors
    ///
    /// Returns the underlying I/O error if any pending state cannot be
    /// persisted.
    fn finalize(&mut self) -> io::Result<TranscriptFingerprint>;
}

/// JSONL file sink with SHA-256 chain integrity.
///
/// Writes `transcript.jsonl` to a target directory. Every `record` call
/// serializes the fact, prepends the current chain head as `prev_hash`,
/// writes one line, flushes, and advances the chain head. The transcript
/// is self-identifying: `SHA-256` of the last line *is* the cryptographic
/// fingerprint; no sidecar file is written.
#[derive(Debug)]
pub struct JsonlFileSink {
    jsonl_path: PathBuf,
    writer: BufWriter<File>,
    current_hash: String,
    finalized: Option<TranscriptFingerprint>,
}

impl JsonlFileSink {
    /// Create a new sink in `dir`. Writes `transcript.jsonl` next to it.
    ///
    /// # Errors
    ///
    /// Returns an I/O error if the JSONL file cannot be created.
    pub fn create(dir: &Path) -> io::Result<Self> {
        let jsonl_path = dir.join("transcript.jsonl");
        let file = OpenOptions::new()
            .create_new(true)
            .write(true)
            .open(&jsonl_path)?;
        Ok(Self {
            jsonl_path,
            writer: BufWriter::new(file),
            current_hash: GENESIS_HASH.to_string(),
            finalized: None,
        })
    }

    /// Path to the JSONL file this sink is writing to.
    #[must_use]
    pub fn jsonl_path(&self) -> &Path {
        &self.jsonl_path
    }
}

impl TranscriptSink for JsonlFileSink {
    fn record(&mut self, at: DateTime<Utc>, fact: &StepFact) -> io::Result<()> {
        if self.finalized.is_some() {
            return Err(io::Error::other("transcript already finalized"));
        }
        let line = ChainedFact {
            prev_hash: &self.current_hash,
            at,
            fact,
        };
        let bytes = serde_json::to_vec(&line).map_err(io::Error::other)?;
        self.current_hash = compute_fingerprint(&bytes);
        self.writer.write_all(&bytes)?;
        self.writer.write_all(b"\n")?;
        // `flush` drains the BufWriter into the File; `sync_data` then
        // forces the kernel to push the page-cache pages to the storage
        // device before we return. Without the sync, a power loss between
        // `record` and the OS's next writeback would drop already-reported
        // facts even though the executor moved on. Cost at ceremony pace
        // (one record every few seconds of human pace) is negligible.
        self.writer.flush()?;
        self.writer.get_ref().sync_data()?;
        Ok(())
    }

    fn finalize(&mut self) -> io::Result<TranscriptFingerprint> {
        if let Some(existing) = &self.finalized {
            return Ok(existing.clone());
        }
        let fingerprint = TranscriptFingerprint(self.current_hash.clone());
        self.finalized = Some(fingerprint.clone());
        Ok(fingerprint)
    }
}

/// In-memory sink that collects every recorded [`StepFact`].
///
/// Useful for tests and for tooling that wants to inspect the fact stream
/// without going through disk.
#[derive(Debug, Default)]
pub struct InMemorySink {
    facts: Vec<StepFact>,
    current_hash: String,
    finalized: Option<TranscriptFingerprint>,
}

impl InMemorySink {
    /// Create an empty sink.
    #[must_use]
    pub fn new() -> Self {
        Self {
            facts: Vec::new(),
            current_hash: GENESIS_HASH.to_string(),
            finalized: None,
        }
    }

    /// Recorded facts in the order they arrived.
    #[must_use]
    pub fn facts(&self) -> &[StepFact] {
        &self.facts
    }

    /// Number of facts recorded so far.
    #[must_use]
    pub fn len(&self) -> usize {
        self.facts.len()
    }

    /// Whether any fact has been recorded.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.facts.is_empty()
    }
}

impl TranscriptSink for InMemorySink {
    fn record(&mut self, at: DateTime<Utc>, fact: &StepFact) -> io::Result<()> {
        if self.finalized.is_some() {
            return Err(io::Error::other("transcript already finalized"));
        }
        let line = ChainedFact {
            prev_hash: &self.current_hash,
            at,
            fact,
        };
        let bytes = serde_json::to_vec(&line).map_err(io::Error::other)?;
        self.current_hash = compute_fingerprint(&bytes);
        self.facts.push(fact.clone());
        Ok(())
    }

    fn finalize(&mut self) -> io::Result<TranscriptFingerprint> {
        if let Some(existing) = &self.finalized {
            return Ok(existing.clone());
        }
        let fingerprint = TranscriptFingerprint(self.current_hash.clone());
        self.finalized = Some(fingerprint.clone());
        Ok(fingerprint)
    }
}

#[derive(Serialize)]
struct ChainedFact<'a> {
    prev_hash: &'a str,
    at: DateTime<Utc>,
    fact: &'a StepFact,
}

#[derive(Deserialize)]
struct OwnedChainedFact {
    prev_hash: String,
    at: DateTime<Utc>,
    fact: StepFact,
}

/// A recorded fact paired with its envelope timestamp: the uniform event time,
/// which lives on the chain envelope rather than on individual facts. Returned
/// by [`read_verified_transcript`] so consumers read event time uniformly.
#[derive(Debug, Clone)]
pub struct TimedFact {
    /// Wall-clock time the fact was recorded.
    pub at: DateTime<Utc>,
    /// The recorded fact.
    pub fact: StepFact,
}

/// Outcome of verifying a transcript on disk.
#[derive(Debug, Clone)]
pub struct TranscriptVerified {
    /// Number of facts read and verified.
    pub fact_count: usize,
    /// Final transcript fingerprint (hash of the last line).
    pub fingerprint: TranscriptFingerprint,
    /// `true` if the last fact is a terminal one (`CeremonyCompleted` or
    /// `CeremonyFailed`). `false` means the transcript was cut off
    /// before the executor reached its finalize step, a truncated run.
    pub terminated: bool,
}

/// Verification failure modes.
#[derive(Debug, Error)]
pub enum VerifyError {
    /// Underlying I/O error reading the transcript.
    #[error("io error: {0}")]
    Io(#[from] io::Error),
    /// A line did not parse as a [`ChainedFact`].
    #[error("line {line} is not a valid chained fact: {reason}")]
    InvalidLine {
        /// 1-indexed line number.
        line: usize,
        /// Parse error.
        reason: String,
    },
    /// The chain is broken: a line's `prev_hash` did not match the
    /// expected value computed from the previous line.
    #[error("broken chain at line {line}: expected prev_hash {expected}, got {actual}")]
    BrokenChain {
        /// 1-indexed line number where the break was detected.
        line: usize,
        /// The expected `prev_hash` (= hash of the previous line).
        expected: String,
        /// The `prev_hash` actually recorded on the line.
        actual: String,
    },
    /// The transcript file has zero lines.
    #[error("transcript is empty")]
    Empty,
    /// A value was drawn (or a contribution folded) before any
    /// `EntropySeeded` fact established the source.
    #[error("entropy source used before it was seeded")]
    SeedMissing,
    /// A second `EntropySeeded` fact appeared. The source is seeded exactly
    /// once at ceremony start; accepting a re-seed would let a crafted
    /// transcript swap the seed mid-stream and have later draws "verify"
    /// against a seed of the forger's choosing.
    #[error("entropy source seeded more than once")]
    DuplicateSeed,
    /// The seed fact declares a derivation scheme the verifier does not
    /// recognise. Never trust an unknown scheme (the JWT-`alg` lesson).
    #[error("unknown entropy derivation scheme: {0}")]
    UnknownDerivation(String),
    /// A recorded hex value (the seed `m` or a drawn value) did not decode.
    #[error("malformed entropy value: {0}")]
    MalformedEntropy(String),
    /// A drawn value does not match what re-derivation from the recorded
    /// seed and path produces: the source was tampered with.
    #[error("entropy draw at path '{path}' does not match re-derived value")]
    DrawMismatch {
        /// Derivation path of the mismatched draw.
        path: String,
    },
    /// A recorded draw is longer than `HKDF-Expand` can produce
    /// ([`MAX_DRAW_LEN`](crate::entropy::MAX_DRAW_LEN) bytes), so it cannot
    /// have come from the real source. Rejected up front: attempting the
    /// re-derivation would abort the verifier instead of failing the check.
    #[error(
        "entropy draw at path '{path}' records {len} bytes, beyond the {max}-byte HKDF-Expand limit"
    )]
    DrawTooLong {
        /// Derivation path of the oversized draw.
        path: String,
        /// Recorded value length in bytes.
        len: usize,
        /// The `HKDF-Expand` output limit.
        max: usize,
    },
    /// A draw's recorded path does not start with the
    /// `<epoch>/<step>/` prefix the verifier rebuilds from its own fold
    /// count and the step named on the fact, so the draw is attributed to
    /// the wrong epoch or step.
    #[error("entropy draw path '{path}' does not match expected '{expected_prefix}<purpose>'")]
    PathMismatch {
        /// Recorded derivation path.
        path: String,
        /// The `<epoch>/<step>/` prefix the verifier expected.
        expected_prefix: String,
    },
    /// A contribution's recorded epoch does not match its position in the
    /// fold sequence (first contribution is epoch 1, and so on).
    #[error("entropy contribution at step '{step}' records epoch {recorded}, expected {expected}")]
    EpochMismatch {
        /// Step that recorded the contribution.
        step: String,
        /// Epoch index recorded on the fact.
        recorded: u32,
        /// Epoch index implied by the fold count.
        expected: u32,
    },
    /// The same derivation path was drawn twice. The runtime never reuses a
    /// path, so a duplicate means the record was edited or replayed.
    #[error("entropy draw path '{path}' recorded more than once")]
    DuplicateDrawPath {
        /// The repeated derivation path.
        path: String,
    },
}

/// Verify a JSONL transcript file produced by [`JsonlFileSink`].
///
/// Reads the file line-by-line, recomputes each line's SHA-256, and
/// checks that `prev_hash` matches the previous line's hash.
///
/// # Errors
///
/// Returns [`VerifyError`] for any I/O failure, malformed line, or
/// chain break.
pub fn verify_transcript(jsonl_path: &Path) -> Result<TranscriptVerified, VerifyError> {
    let loaded = read_verified_transcript(jsonl_path)?;
    Ok(TranscriptVerified {
        fact_count: loaded.facts.len(),
        fingerprint: loaded.fingerprint,
        terminated: loaded.terminated,
    })
}

/// Verified transcript contents, chain-walked facts plus the final
/// fingerprint and a flag for whether the run reached a terminal fact.
#[derive(Debug, Clone)]
pub struct LoadedTranscript {
    /// Facts in the order they were recorded, each paired with the envelope
    /// timestamp the sink stamped when it wrote the line.
    pub facts: Vec<TimedFact>,
    /// Final transcript fingerprint (hash of the last line).
    pub fingerprint: TranscriptFingerprint,
    /// `true` if the last fact is `CeremonyCompleted` or `CeremonyFailed`.
    pub terminated: bool,
}

/// Verify a JSONL transcript and return its facts.
///
/// Same chain check as [`verify_transcript`], plus returns the
/// deserialized [`StepFact`] stream and whether the last line is a
/// terminal fact.
///
/// # Errors
///
/// Same as [`verify_transcript`].
pub fn read_verified_transcript(jsonl_path: &Path) -> Result<LoadedTranscript, VerifyError> {
    let file = File::open(jsonl_path)?;
    let reader = BufReader::new(file);

    let mut expected_prev = GENESIS_HASH.to_string();
    let mut last_hash = expected_prev.clone();
    let mut facts: Vec<TimedFact> = Vec::new();

    for (idx, line) in reader.lines().enumerate() {
        let line = line?;
        let line_no = idx.saturating_add(1);
        let parsed: OwnedChainedFact =
            serde_json::from_str(&line).map_err(|e| VerifyError::InvalidLine {
                line: line_no,
                reason: e.to_string(),
            })?;
        if parsed.prev_hash != expected_prev {
            return Err(VerifyError::BrokenChain {
                line: line_no,
                expected: expected_prev,
                actual: parsed.prev_hash,
            });
        }
        last_hash = compute_fingerprint(line.as_bytes());
        expected_prev.clone_from(&last_hash);
        facts.push(TimedFact {
            at: parsed.at,
            fact: parsed.fact,
        });
    }

    if facts.is_empty() {
        return Err(VerifyError::Empty);
    }

    let terminated = matches!(
        facts.last().map(|t| &t.fact),
        Some(StepFact::CeremonyCompleted { .. } | StepFact::CeremonyFailed { .. }),
    );

    Ok(LoadedTranscript {
        facts,
        fingerprint: TranscriptFingerprint(last_hash),
        terminated,
    })
}

/// Outcome of re-deriving a transcript's entropy source.
#[derive(Debug, Clone, Default)]
pub struct EntropyVerified {
    /// Derivation-scheme tag declared by the seed fact, if the ceremony used
    /// the source at all.
    pub derivation: Option<String>,
    /// Provenance of the machine seed as recorded by the seed fact (e.g.
    /// `os`, or the `dry-run` sentinel). Consumers surface this so a
    /// dry-run transcript, which re-derives just as cleanly as a real one,
    /// is never presented as real evidence.
    pub source: Option<String>,
    /// Number of human contributions folded into the ratchet.
    pub contributions: usize,
    /// Number of drawn values that re-derived to their recorded value.
    pub values_verified: usize,
}

/// Re-derive a transcript's entropy source and confirm every drawn value.
///
/// Replays the `rite-kdf/v1` ratchet over the recorded facts: it rebuilds
/// `seed_0` from the recorded machine entropy, folds each human contribution
/// in chain order, and for every [`StepFact::EntropyDrawn`] re-derives the
/// value from the recorded path and checks it against the recorded value. A
/// tampered seed, contribution, path, or value fails the check.
///
/// Beyond the value re-derivation, the replay enforces the source's own
/// invariants, so a transcript cannot record a fact stream the runtime could
/// never have produced:
///
/// - the source is seeded exactly once;
/// - each contribution's recorded `epoch` matches its position in the fold
///   sequence;
/// - each draw's recorded path carries the `<epoch>/<step>/` prefix rebuilt
///   from the verifier's own fold count and the step named on the fact;
/// - no derivation path is drawn twice;
/// - no recorded value exceeds what `HKDF-Expand` can produce
///   ([`MAX_DRAW_LEN`](crate::entropy::MAX_DRAW_LEN) bytes), which would
///   otherwise abort the verifier instead of failing the check.
///
/// The caller is expected to have chain-verified the facts first (via
/// [`read_verified_transcript`]); this function only re-derives.
///
/// # Errors
///
/// Returns a [`VerifyError`] variant describing the first inconsistency:
/// [`VerifyError::SeedMissing`], [`VerifyError::DuplicateSeed`],
/// [`VerifyError::UnknownDerivation`], [`VerifyError::MalformedEntropy`],
/// [`VerifyError::EpochMismatch`], [`VerifyError::PathMismatch`],
/// [`VerifyError::DuplicateDrawPath`], [`VerifyError::DrawTooLong`], or
/// [`VerifyError::DrawMismatch`].
pub fn verify_entropy<'a>(
    facts: impl IntoIterator<Item = &'a StepFact>,
) -> Result<EntropyVerified, VerifyError> {
    let mut seed: Option<[u8; 32]> = None;
    let mut epoch: u32 = 0;
    let mut drawn_paths: HashSet<String> = HashSet::new();
    let mut result = EntropyVerified::default();

    for fact in facts {
        match fact {
            StepFact::EntropySeeded {
                m,
                source,
                derivation,
                ..
            } => {
                if seed.is_some() {
                    return Err(VerifyError::DuplicateSeed);
                }
                if derivation != crate::entropy::DERIVATION_V1 {
                    return Err(VerifyError::UnknownDerivation(derivation.clone()));
                }
                let m_bytes = base16ct::lower::decode_vec(m)
                    .map_err(|e| VerifyError::MalformedEntropy(format!("seed m: {e}")))?;
                seed = Some(crate::entropy::initial_seed(&m_bytes));
                result.derivation = Some(derivation.clone());
                result.source = Some(source.clone());
            }
            StepFact::EntropyContributed {
                step,
                epoch: recorded_epoch,
                contribution,
                ..
            } => {
                let current = seed.as_ref().ok_or(VerifyError::SeedMissing)?;
                let expected = epoch.saturating_add(1);
                if *recorded_epoch != expected {
                    return Err(VerifyError::EpochMismatch {
                        step: step.as_str().to_string(),
                        recorded: *recorded_epoch,
                        expected,
                    });
                }
                seed = Some(crate::entropy::fold_seed(current, contribution.as_bytes()));
                epoch = expected;
                result.contributions = result.contributions.saturating_add(1);
            }
            StepFact::EntropyDrawn {
                step, path, value, ..
            } => {
                let current = seed.as_ref().ok_or(VerifyError::SeedMissing)?;
                // Rebuild the path prefix from the verifier's own fold count
                // and the step named on the fact; only the purpose segment is
                // taken from the record. A draw attributed to the wrong epoch
                // or step fails here even if its value re-derives.
                let expected_prefix = crate::entropy::build_path(epoch, step, "");
                if !path.starts_with(&expected_prefix) || path.len() == expected_prefix.len() {
                    return Err(VerifyError::PathMismatch {
                        path: path.clone(),
                        expected_prefix,
                    });
                }
                if !drawn_paths.insert(path.clone()) {
                    return Err(VerifyError::DuplicateDrawPath { path: path.clone() });
                }
                // The recorded value's own length fixes how many bytes to
                // re-derive; decoding it also rejects a malformed hex record.
                let recorded = base16ct::lower::decode_vec(value)
                    .map_err(|e| VerifyError::MalformedEntropy(format!("draw {path}: {e}")))?;
                if recorded.len() > crate::entropy::MAX_DRAW_LEN {
                    return Err(VerifyError::DrawTooLong {
                        path: path.clone(),
                        len: recorded.len(),
                        max: crate::entropy::MAX_DRAW_LEN,
                    });
                }
                let expected = crate::entropy::derive_value(current, path, recorded.len());
                if expected != recorded {
                    return Err(VerifyError::DrawMismatch { path: path.clone() });
                }
                result.values_verified = result.values_verified.saturating_add(1);
            }
            _ => {}
        }
    }

    Ok(result)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_support::fixed_test_time as test_at;

    fn sample_fact() -> StepFact {
        StepFact::CeremonyStarted {
            name: "Test".to_string(),
        }
    }

    #[test]
    fn in_memory_sink_records_and_finalizes() {
        let mut sink = InMemorySink::new();
        assert!(sink.is_empty());
        sink.record(test_at(), &sample_fact()).expect("record");
        assert_eq!(sink.len(), 1);
        let fp = sink.finalize().expect("finalize");
        assert!(fp.as_str().starts_with("sha256:"));
    }

    #[test]
    fn in_memory_sink_rejects_record_after_finalize() {
        let mut sink = InMemorySink::new();
        sink.record(test_at(), &sample_fact()).expect("record");
        sink.finalize().expect("finalize");
        let err = sink
            .record(test_at(), &sample_fact())
            .expect_err("should fail");
        assert!(err.to_string().contains("already finalized"));
    }

    #[test]
    fn in_memory_sink_chain_advances() {
        let mut sink = InMemorySink::new();
        let initial = sink.current_hash.clone();
        sink.record(test_at(), &sample_fact()).expect("record");
        assert_ne!(sink.current_hash, initial);
        let after_first = sink.current_hash.clone();
        sink.record(test_at(), &sample_fact()).expect("record");
        assert_ne!(sink.current_hash, after_first);
    }

    #[test]
    fn record_persists_the_supplied_time_and_reader_recovers_it() {
        // The sink records the `at` it is given (it does not read a clock), and
        // the reader recovers exactly that instant from the envelope.
        let tmp = tempfile::tempdir().expect("tempdir");
        let mut sink = JsonlFileSink::create(tmp.path()).expect("create");
        let at = test_at();
        sink.record(at, &sample_fact()).expect("record");
        sink.finalize().expect("finalize");

        let loaded = read_verified_transcript(sink.jsonl_path()).expect("read");
        assert_eq!(loaded.facts.first().expect("one fact").at, at);
    }

    #[test]
    fn jsonl_file_sink_writes_and_chains() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let mut sink = JsonlFileSink::create(tmp.path()).expect("create");
        sink.record(test_at(), &sample_fact()).expect("record");
        sink.record(test_at(), &sample_fact()).expect("record");
        let fp = sink.finalize().expect("finalize");

        let jsonl = std::fs::read_to_string(sink.jsonl_path()).expect("read jsonl");
        let mut lines = jsonl.lines();
        let raw_first = lines.next().expect("first line");
        let raw_second = lines.next().expect("second line");
        assert!(lines.next().is_none(), "expected exactly two lines");

        let first: serde_json::Value = serde_json::from_str(raw_first).expect("parse first");
        let second: serde_json::Value = serde_json::from_str(raw_second).expect("parse second");
        assert_eq!(
            first.get("prev_hash").and_then(serde_json::Value::as_str),
            Some(GENESIS_HASH),
        );
        let first_hash = compute_fingerprint(raw_first.as_bytes());
        assert_eq!(
            second.get("prev_hash").and_then(serde_json::Value::as_str),
            Some(first_hash.as_str()),
        );
        let second_hash = compute_fingerprint(raw_second.as_bytes());
        assert_eq!(fp.as_str(), second_hash);
    }

    #[test]
    fn jsonl_file_sink_refuses_existing_file() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let _first = JsonlFileSink::create(tmp.path()).expect("first");
        let err = JsonlFileSink::create(tmp.path()).expect_err("second should fail");
        assert_eq!(err.kind(), io::ErrorKind::AlreadyExists);
    }

    #[test]
    fn verify_round_trip_succeeds_on_well_formed_transcript() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let mut sink = JsonlFileSink::create(tmp.path()).expect("create");
        sink.record(test_at(), &sample_fact()).expect("record");
        sink.record(test_at(), &sample_fact()).expect("record");
        sink.record(test_at(), &sample_fact()).expect("record");
        let written = sink.finalize().expect("finalize");

        let verified = verify_transcript(sink.jsonl_path()).expect("verify");
        assert_eq!(verified.fact_count, 3);
        assert_eq!(verified.fingerprint, written);
        // Sample fact isn't a terminal one; the transcript is open-ended.
        assert!(!verified.terminated);
    }

    #[test]
    fn verify_detects_chain_break() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let mut sink = JsonlFileSink::create(tmp.path()).expect("create");
        sink.record(test_at(), &sample_fact()).expect("record");
        sink.record(test_at(), &sample_fact()).expect("record");
        let _ = sink.finalize().expect("finalize");

        let path = sink.jsonl_path().to_path_buf();
        let content = std::fs::read_to_string(&path).expect("read");
        let mut lines: Vec<String> = content.lines().map(String::from).collect();
        if let Some(second) = lines.get_mut(1) {
            *second = second.replace("prev_hash\":\"sha256:", "prev_hash\":\"sha256:ff");
        }
        std::fs::write(&path, lines.join("\n") + "\n").expect("write");

        let err = verify_transcript(&path).expect_err("should detect tamper");
        assert!(matches!(err, VerifyError::BrokenChain { .. }));
    }

    #[test]
    fn verify_empty_transcript_returns_empty_error() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let path = tmp.path().join("transcript.jsonl");
        std::fs::write(&path, "").expect("write empty");
        let err = verify_transcript(&path).expect_err("empty");
        assert!(matches!(err, VerifyError::Empty));
    }

    use rite_model::StepId;

    fn seeded_fact(m: &[u8]) -> StepFact {
        StepFact::EntropySeeded {
            m: base16ct::lower::encode_string(m),
            source: "os".to_string(),
            derivation: crate::entropy::DERIVATION_V1.to_string(),
        }
    }

    fn drawn_fact(seed: &[u8; 32], step: &str, path: &str, len: usize) -> StepFact {
        StepFact::EntropyDrawn {
            step: StepId::new(step),
            path: path.to_string(),
            value: base16ct::lower::encode_string(&crate::entropy::derive_value(seed, path, len)),
        }
    }

    #[test]
    fn verify_entropy_re_derives_a_clean_draw() {
        let m = b"machine entropy bytes";
        let seed = crate::entropy::initial_seed(m);
        let facts = [
            seeded_fact(m),
            drawn_fact(&seed, "issue", "0/issue/cert-serial", 9),
        ];
        let v = verify_entropy(facts.iter()).expect("verify");
        assert_eq!(v.values_verified, 1);
        assert_eq!(v.contributions, 0);
        assert_eq!(v.derivation.as_deref(), Some("rite-kdf/v1"));
    }

    #[test]
    fn verify_entropy_follows_the_ratchet_through_a_contribution() {
        let m = b"machine entropy bytes";
        let seed0 = crate::entropy::initial_seed(m);
        let seed1 = crate::entropy::fold_seed(&seed0, b"3 1 6 4 2 5");
        let facts = [
            seeded_fact(m),
            StepFact::EntropyContributed {
                step: StepId::new("roll"),
                epoch: 1,
                contribution: "3 1 6 4 2 5".to_string(),
            },
            // Drawn after the fold, so it must derive from the epoch-1 seed.
            drawn_fact(&seed1, "issue", "1/issue/cert-serial", 9),
        ];
        let v = verify_entropy(facts.iter()).expect("verify");
        assert_eq!(v.contributions, 1);
        assert_eq!(v.values_verified, 1);
    }

    #[test]
    fn verify_entropy_detects_a_tampered_value() {
        let m = b"machine entropy bytes";
        let seed = crate::entropy::initial_seed(m);
        let mut drawn = drawn_fact(&seed, "issue", "0/issue/cert-serial", 9);
        if let StepFact::EntropyDrawn { value, .. } = &mut drawn {
            *value = "deadbeefdeadbeefdead".to_string();
        }
        let facts = [seeded_fact(m), drawn];
        let err = verify_entropy(facts.iter()).expect_err("tamper");
        assert!(matches!(err, VerifyError::DrawMismatch { .. }));
    }

    #[test]
    fn verify_entropy_rejects_unknown_derivation() {
        let facts = [StepFact::EntropySeeded {
            m: "00".to_string(),
            source: "os".to_string(),
            derivation: "rite-kdf/v99".to_string(),
        }];
        let err = verify_entropy(facts.iter()).expect_err("unknown scheme");
        assert!(matches!(err, VerifyError::UnknownDerivation(_)));
    }

    #[test]
    fn verify_entropy_rejects_draw_before_seed() {
        let seed = crate::entropy::initial_seed(b"x");
        let facts = [drawn_fact(&seed, "issue", "0/issue/cert-serial", 9)];
        let err = verify_entropy(facts.iter()).expect_err("unseeded");
        assert!(matches!(err, VerifyError::SeedMissing));
    }

    #[test]
    fn verify_entropy_surfaces_the_seed_source() {
        let m = b"machine entropy bytes";
        let v = verify_entropy([seeded_fact(m)].iter()).expect("verify");
        assert_eq!(v.source.as_deref(), Some("os"));
    }

    #[test]
    fn verify_entropy_rejects_a_second_seed() {
        // A mid-stream re-seed would let a forged transcript swap the seed
        // under later draws; the replay refuses rather than resetting.
        let facts = [seeded_fact(b"first"), seeded_fact(b"second")];
        let err = verify_entropy(facts.iter()).expect_err("re-seed");
        assert!(matches!(err, VerifyError::DuplicateSeed));
    }

    #[test]
    fn verify_entropy_rejects_an_oversized_draw_without_panicking() {
        // 8161 bytes is one past the HKDF-Expand limit (255 * 32). Re-deriving
        // it would panic inside `expand`; the verifier must reject it as a
        // malformed record instead of aborting.
        let m = b"machine entropy bytes";
        let oversized = "ab".repeat(crate::entropy::MAX_DRAW_LEN.saturating_add(1));
        let facts = [
            seeded_fact(m),
            StepFact::EntropyDrawn {
                step: StepId::new("issue"),
                path: "0/issue/cert-serial".to_string(),
                value: oversized,
            },
        ];
        let err = verify_entropy(facts.iter()).expect_err("oversized draw");
        assert!(matches!(err, VerifyError::DrawTooLong { len, .. } if len == 8161));
    }

    #[test]
    fn verify_entropy_rejects_a_draw_path_with_the_wrong_epoch() {
        // No contribution was folded, so the draw must come from epoch 0; a
        // recorded epoch-1 path is a stream the runtime could not produce.
        let m = b"machine entropy bytes";
        let seed = crate::entropy::initial_seed(m);
        let facts = [
            seeded_fact(m),
            drawn_fact(&seed, "issue", "1/issue/cert-serial", 9),
        ];
        let err = verify_entropy(facts.iter()).expect_err("wrong epoch");
        assert!(matches!(err, VerifyError::PathMismatch { .. }));
    }

    #[test]
    fn verify_entropy_rejects_a_draw_path_with_the_wrong_step() {
        let m = b"machine entropy bytes";
        let seed = crate::entropy::initial_seed(m);
        let facts = [
            seeded_fact(m),
            // Path names step `other` but the fact was recorded under `issue`.
            drawn_fact(&seed, "issue", "0/other/cert-serial", 9),
        ];
        let err = verify_entropy(facts.iter()).expect_err("wrong step");
        assert!(matches!(err, VerifyError::PathMismatch { .. }));
    }

    #[test]
    fn verify_entropy_rejects_an_empty_purpose() {
        let m = b"machine entropy bytes";
        let seed = crate::entropy::initial_seed(m);
        let facts = [seeded_fact(m), drawn_fact(&seed, "issue", "0/issue/", 9)];
        let err = verify_entropy(facts.iter()).expect_err("empty purpose");
        assert!(matches!(err, VerifyError::PathMismatch { .. }));
    }

    #[test]
    fn verify_entropy_rejects_a_contribution_epoch_out_of_sequence() {
        let m = b"machine entropy bytes";
        let facts = [
            seeded_fact(m),
            StepFact::EntropyContributed {
                step: StepId::new("roll"),
                // First fold must record epoch 1.
                epoch: 2,
                contribution: "3 1 6 4 2 5".to_string(),
            },
        ];
        let err = verify_entropy(facts.iter()).expect_err("epoch skip");
        assert!(matches!(
            err,
            VerifyError::EpochMismatch {
                recorded: 2,
                expected: 1,
                ..
            }
        ));
    }

    #[test]
    fn verify_entropy_rejects_a_duplicate_draw_path() {
        // The runtime never reuses a path; a repeat means the record was
        // edited or replayed.
        let m = b"machine entropy bytes";
        let seed = crate::entropy::initial_seed(m);
        let facts = [
            seeded_fact(m),
            drawn_fact(&seed, "issue", "0/issue/cert-serial", 9),
            drawn_fact(&seed, "issue", "0/issue/cert-serial", 9),
        ];
        let err = verify_entropy(facts.iter()).expect_err("duplicate path");
        assert!(matches!(err, VerifyError::DuplicateDrawPath { .. }));
    }
}