reef-core 0.4.0

Provider-neutral primitives for building LLM agents: run lifecycle, transcript, tools, hooks
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
//! In-memory transcript truth source with capability-narrowed handles.
//!
//! Mutation semantics are stated as version arithmetic: batch
//! append advances by its length, replacement advances by one, compare-and-swap
//! checks and commits share one write critical section, and restore continues a
//! saved version epoch.

use std::error;
use std::fmt;
use std::sync::{Arc, RwLock};
#[cfg(test)]
use std::sync::{Barrier, Mutex, TryLockError};

use super::item::Item;
use crate::redact::Locked;

/// A monotonic transcript revision within one store epoch.
///
/// `Version` never wraps. A write which cannot be represented returns
/// [`Error::VersionOverflow`] without changing the store.
///
/// ```
/// use reef_core::transcript::store;
/// assert!(store::Version::from_u64(2) > store::Version::from_u64(1));
/// assert_eq!(store::Version::ZERO.as_u64(), 0);
/// ```
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct Version(u64);

impl Version {
    /// The first version in a fresh epoch.
    pub const ZERO: Self = Self(0);

    /// The greatest representable transcript version.
    pub const MAX: Self = Self(u64::MAX);

    /// Creates a version from its persisted integer representation.
    #[must_use]
    pub const fn from_u64(value: u64) -> Self {
        Self(value)
    }

    /// Returns the persisted integer representation.
    #[must_use]
    pub const fn as_u64(self) -> u64 {
        self.0
    }

    fn checked_add(self, delta: u64) -> Option<Self> {
        self.0.checked_add(delta).map(Self)
    }
}

impl fmt::Display for Version {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(formatter)
    }
}

/// One atomic, immutable transcript state.
///
/// Cloning a snapshot is O(1): unchanged readers share the same immutable item
/// backing. [`Store::restore`] adopts that backing and continues exactly at its
/// saved version; [`Store::from_items`] instead starts a new version-zero epoch.
#[derive(Clone, Debug)]
pub struct Snapshot {
    version: Version,
    items: Arc<Vec<Item>>,
}

impl Snapshot {
    /// Creates a versioned snapshot by adopting an owned item history.
    #[must_use]
    pub fn new(version: Version, items: Vec<Item>) -> Self {
        Self::from_shared(version, Arc::new(items))
    }

    const fn from_shared(version: Version, items: Arc<Vec<Item>>) -> Self {
        Self { version, items }
    }

    pub(crate) fn with_version(self, version: Version) -> Self {
        Self {
            version,
            items: self.items,
        }
    }

    /// Returns the atomically captured version.
    #[must_use]
    pub const fn version(&self) -> Version {
        self.version
    }

    /// Returns the captured ordered items.
    #[must_use]
    pub fn items(&self) -> &[Item] {
        self.items.as_slice()
    }

    /// Transfers ownership of the version and ordered items.
    ///
    /// If another snapshot or store still shares the item backing, this method
    /// clones the items to produce the requested unique vector.
    #[must_use]
    pub fn into_parts(self) -> (Version, Vec<Item>) {
        let items = Arc::try_unwrap(self.items).unwrap_or_else(|items| items.as_ref().clone());
        (self.version, items)
    }

    #[cfg(test)]
    pub(crate) fn shares_items_with(&self, other: &Self) -> bool {
        Arc::ptr_eq(&self.items, &other.items)
    }

    #[cfg(test)]
    pub(crate) fn items_backing_ptr(&self) -> *const Vec<Item> {
        Arc::as_ptr(&self.items)
    }
}

/// A typed transcript store failure.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum Error {
    /// The store changed after the caller observed `expected`.
    #[non_exhaustive]
    VersionConflict {
        /// The stale version supplied by the caller.
        expected: Version,
        /// The version observed while holding the commit lock.
        actual: Version,
    },
    /// A successful mutation would exceed [`Version::MAX`].
    #[non_exhaustive]
    VersionOverflow {
        /// The current version.
        current: Version,
        /// The requested increment.
        delta: u64,
    },
    /// A panic occurred while a writer held the lock.
    ///
    /// Reef fails closed rather than exposing potentially inconsistent state.
    Poisoned,
}

impl fmt::Display for Error {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::VersionConflict { expected, actual } => write!(
                formatter,
                "transcript version conflict: expected {expected}, actual {actual}"
            ),
            Self::VersionOverflow { current, delta } => write!(
                formatter,
                "transcript version overflow: current {current}, increment {delta}"
            ),
            Self::Poisoned => formatter.write_str("transcript store lock poisoned"),
        }
    }
}

impl error::Error for Error {}

struct State {
    version: Version,
    items: Arc<Vec<Item>>,
    staged_tail: Option<Vec<Item>>,
}

impl State {
    fn has_staged_items(&self) -> bool {
        self.staged_tail
            .as_ref()
            .is_some_and(|tail| !tail.is_empty())
    }

    fn materialize_staged_items(&mut self) {
        let Some(mut tail) = self.staged_tail.take() else {
            return;
        };
        if tail.is_empty() {
            self.staged_tail = Some(tail);
            return;
        }
        Arc::make_mut(&mut self.items).append(&mut tail);
        self.staged_tail = Some(Vec::new());
    }

    fn snapshot(&self) -> Snapshot {
        debug_assert!(!self.has_staged_items());
        Snapshot::from_shared(self.version, Arc::clone(&self.items))
    }

    fn into_snapshot(mut self) -> Snapshot {
        self.materialize_staged_items();
        Snapshot::from_shared(self.version, self.items)
    }

    fn into_snapshot_with_suffix(mut self, mut suffix: Vec<Item>) -> Snapshot {
        if let Some(tail) = &mut self.staged_tail {
            tail.append(&mut suffix);
        } else {
            Arc::make_mut(&mut self.items).append(&mut suffix);
        }
        self.into_snapshot()
    }
}

struct Core {
    state: RwLock<State>,
    #[cfg(test)]
    commit_overlap: Mutex<Option<Arc<CommitOverlap>>>,
}

#[cfg(test)]
struct CommitOverlap {
    writer_ready: Barrier,
    reader_contending: Barrier,
    commit_release: Barrier,
}

#[cfg(test)]
impl CommitOverlap {
    fn new() -> Self {
        Self {
            writer_ready: Barrier::new(2),
            reader_contending: Barrier::new(3),
            commit_release: Barrier::new(2),
        }
    }
}

#[cfg(test)]
pub(super) struct CommitOverlapControl {
    overlap: Arc<CommitOverlap>,
}

#[cfg(test)]
impl CommitOverlapControl {
    pub(super) fn wait_for_writer(&self) {
        self.overlap.writer_ready.wait();
    }

    pub(super) fn wait_for_reader(&self) {
        self.overlap.reader_contending.wait();
    }

    pub(super) fn release_writer(&self) {
        self.overlap.commit_release.wait();
    }
}

impl Core {
    /// Renders one capability handle by the transcript version behind it.
    ///
    /// The five handles differ in authority, not in state, so the version is
    /// the fact worth printing and the only one they can all reach. The read is
    /// non-blocking: a handle is routinely formatted from inside code that
    /// already holds the lock, and a `Debug` that waited there would deadlock.
    fn debug_handle(&self, name: &str, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut handle = formatter.debug_struct(name);
        match self.state.try_read() {
            Ok(state) => handle.field("version", &state.version),
            Err(_contended_or_poisoned) => handle.field("version", &Locked),
        }
        .finish()
    }

    #[cfg(test)]
    fn test_before_read(&self) {
        let overlap = self
            .commit_overlap
            .lock()
            .expect("test overlap lock must be healthy")
            .clone();
        if let Some(overlap) = overlap {
            // The writer holds the production write lock before it reaches this
            // seam, so a mechanical try_read must fail fast with WouldBlock.
            // This proves the reader below genuinely contends with a live
            // writer rather than merely waiting on the test barrier.
            assert!(
                matches!(self.state.try_read(), Err(TryLockError::WouldBlock)),
                "overlap seam requires the production write lock to be held"
            );
            overlap.reader_contending.wait();
        }
    }

    #[cfg(test)]
    fn test_before_commit(&self) {
        let overlap = self
            .commit_overlap
            .lock()
            .expect("test overlap lock must be healthy")
            .clone();
        if let Some(overlap) = overlap {
            // At this point the candidate and next version are complete while
            // the production write lock is still held. Do not permit the
            // single state mutation until a reader has entered its lock path.
            overlap.writer_ready.wait();
            overlap.reader_contending.wait();
            overlap.commit_release.wait();
            *self
                .commit_overlap
                .lock()
                .expect("test overlap lock must be healthy") = None;
        }
    }

    fn items(&self) -> Result<Vec<Item>, Error> {
        self.snapshot().map(|snapshot| snapshot.into_parts().1)
    }

    fn snapshot(&self) -> Result<Snapshot, Error> {
        #[cfg(test)]
        self.test_before_read();
        {
            let state = self.state.read().map_err(|_| Error::Poisoned)?;
            if !state.has_staged_items() {
                return Ok(state.snapshot());
            }
        }

        let mut state = self.state.write().map_err(|_| Error::Poisoned)?;
        state.materialize_staged_items();
        Ok(state.snapshot())
    }

    fn version(&self) -> Result<Version, Error> {
        #[cfg(test)]
        self.test_before_read();
        let state = self.state.read().map_err(|_| Error::Poisoned)?;
        Ok(state.version)
    }

    fn append_batch(
        &self,
        mut candidate: Vec<Item>,
        expected: Option<Version>,
    ) -> Result<Version, Error> {
        // Rust's supported targets have pointer widths no greater than 64 bits,
        // so every possible Vec length is representable as u64.
        let delta = candidate.len() as u64;
        let mut state = self.state.write().map_err(|_| Error::Poisoned)?;
        if let Some(expected) = expected {
            if state.version != expected {
                return Err(Error::VersionConflict {
                    expected,
                    actual: state.version,
                });
            }
        }
        let next = state
            .version
            .checked_add(delta)
            .ok_or(Error::VersionOverflow {
                current: state.version,
                delta,
            })?;
        #[cfg(test)]
        self.test_before_commit();
        if let Some(tail) = &mut state.staged_tail {
            tail.append(&mut candidate);
        } else {
            Arc::make_mut(&mut state.items).append(&mut candidate);
        }
        state.version = next;
        Ok(next)
    }

    fn replace(&self, candidate: Vec<Item>, expected: Option<Version>) -> Result<Version, Error> {
        let mut state = self.state.write().map_err(|_| Error::Poisoned)?;
        if let Some(expected) = expected {
            if state.version != expected {
                return Err(Error::VersionConflict {
                    expected,
                    actual: state.version,
                });
            }
        }
        let next = state.version.checked_add(1).ok_or(Error::VersionOverflow {
            current: state.version,
            delta: 1,
        })?;
        #[cfg(test)]
        self.test_before_commit();
        state.items = Arc::new(candidate);
        if let Some(tail) = &mut state.staged_tail {
            tail.clear();
        }
        state.version = next;
        Ok(next)
    }

    fn replace_snapshot(&self, candidate: Snapshot, expected: Version) -> Result<Version, Error> {
        // `Snapshot::version` is supplied by crate-owned transaction assembly.
        // Make a producer bug equally loud in debug and release without poisoning
        // the store lock; `Version::MAX` remains the typed overflow path below.
        if let Some(next) = expected.checked_add(1) {
            assert_eq!(
                candidate.version(),
                next,
                "snapshot installed at a live boundary must carry that boundary's successor version"
            );
        }
        let mut state = self.state.write().map_err(|_| Error::Poisoned)?;
        if state.version != expected {
            return Err(Error::VersionConflict {
                expected,
                actual: state.version,
            });
        }
        let next = state.version.checked_add(1).ok_or(Error::VersionOverflow {
            current: state.version,
            delta: 1,
        })?;
        #[cfg(test)]
        self.test_before_commit();
        state.items = candidate.items;
        if let Some(tail) = &mut state.staged_tail {
            tail.clear();
        }
        state.version = next;
        Ok(next)
    }
}

/// Owns one transcript and issues independent minimal-permission capabilities.
///
/// `Store` itself has no read or mutation methods. Give consumers only the
/// handle they require; none of the handles can recover or mint another facet.
///
/// ```
/// use reef_core::transcript::store;
/// let store = store::Store::new();
/// let reader = store.reader();
/// assert!(reader.items().unwrap().is_empty());
/// ```
#[derive(Clone)]
pub struct Store {
    core: Arc<Core>,
}

impl fmt::Debug for Store {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.core.debug_handle("Store", formatter)
    }
}

impl Store {
    /// Creates an empty version-zero transcript.
    #[must_use]
    pub fn new() -> Self {
        Self::from_items(Vec::new())
    }

    /// Creates a new version-zero epoch owning `items`.
    #[must_use]
    pub fn from_items(items: Vec<Item>) -> Self {
        Self::from_state(Version::ZERO, items)
    }

    /// Restores an owned snapshot and continues its exact saved version.
    ///
    /// The closed [`Item`] enum makes every `Snapshot` structurally valid, so
    /// restore is infallible. Subsequent conflicting or overflowing writes use
    /// [`Error`] rather than resetting or wrapping the saved version.
    #[must_use]
    pub fn restore(snapshot: Snapshot) -> Self {
        let Snapshot { version, items } = snapshot;
        Self::from_shared_state(version, items, None)
    }

    pub(crate) fn fork(&self) -> Result<Self, Error> {
        let snapshot = self.core.snapshot()?;
        Ok(Self::from_shared_state(
            snapshot.version,
            snapshot.items,
            Some(Vec::new()),
        ))
    }

    pub(crate) fn version(&self) -> Result<Version, Error> {
        self.core.version()
    }

    pub(crate) fn into_snapshot(self) -> Result<Snapshot, Error> {
        match Arc::try_unwrap(self.core) {
            Ok(core) => core
                .state
                .into_inner()
                .map(State::into_snapshot)
                .map_err(|_| Error::Poisoned),
            Err(core) => core.snapshot(),
        }
    }

    pub(crate) fn into_snapshot_with_suffix(self, suffix: Vec<Item>) -> Result<Snapshot, Error> {
        match Arc::try_unwrap(self.core) {
            Ok(core) => core
                .state
                .into_inner()
                .map(|state| state.into_snapshot_with_suffix(suffix))
                .map_err(|_| Error::Poisoned),
            Err(core) => {
                let mut snapshot = core.snapshot()?;
                Arc::make_mut(&mut snapshot.items).extend(suffix);
                Ok(snapshot)
            }
        }
    }

    #[cfg(test)]
    pub(crate) fn into_items(self) -> Result<Vec<Item>, Error> {
        self.into_snapshot().map(|snapshot| snapshot.into_parts().1)
    }

    fn from_state(version: Version, items: Vec<Item>) -> Self {
        Self::from_shared_state(version, Arc::new(items), None)
    }

    fn from_shared_state(
        version: Version,
        items: Arc<Vec<Item>>,
        staged_tail: Option<Vec<Item>>,
    ) -> Self {
        Self {
            core: Arc::new(Core {
                state: RwLock::new(State {
                    version,
                    items,
                    staged_tail,
                }),
                #[cfg(test)]
                commit_overlap: Mutex::new(None),
            }),
        }
    }

    /// Issues an owned-items read capability.
    #[must_use]
    pub fn reader(&self) -> Reader {
        Reader {
            core: Arc::clone(&self.core),
        }
    }

    /// Issues an atomic versioned-snapshot capability.
    #[must_use]
    pub fn snapshot_reader(&self) -> SnapshotReader {
        SnapshotReader {
            core: Arc::clone(&self.core),
        }
    }

    /// Issues append-only authority.
    #[must_use]
    pub fn appender(&self) -> Appender {
        Appender {
            core: Arc::clone(&self.core),
        }
    }

    /// Issues whole-history replacement authority.
    #[must_use]
    pub fn replacer(&self) -> Replacer {
        Replacer {
            core: Arc::clone(&self.core),
        }
    }
}

impl Default for Store {
    fn default() -> Self {
        Self::new()
    }
}

/// Read-only access returning an owned item history.
///
/// This handle intentionally has no method that returns [`Store`], [`Appender`],
/// or [`Replacer`].
///
/// ```compile_fail
/// use reef_core::transcript::{item, store};
/// let reader = store::Store::new().reader();
/// reader.append(item::Item::System(item::System::new(
///     String::new(), String::new(), item::ModelVisibility::Visible,
/// )));
/// ```
#[derive(Clone)]
pub struct Reader {
    core: Arc<Core>,
}

impl fmt::Debug for Reader {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.core.debug_handle("Reader", formatter)
    }
}

impl Reader {
    /// Returns an owned copy of the complete ordered history.
    ///
    /// # Errors
    ///
    /// [`Error::Poisoned`] if a writer panicked while holding the store lock.
    /// Reading is otherwise infallible: the history is already a closed [`Item`]
    /// sequence, so there is nothing here to validate.
    pub fn items(&self) -> Result<Vec<Item>, Error> {
        self.core.items()
    }
}

/// Atomic version-and-items snapshot access without mutation authority.
///
/// ```compile_fail
/// use reef_core::transcript::store;
/// let snapshots = store::Store::new().snapshot_reader();
/// snapshots.replace(Vec::new());
/// ```
#[derive(Clone)]
pub struct SnapshotReader {
    core: Arc<Core>,
}

impl fmt::Debug for SnapshotReader {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.core.debug_handle("SnapshotReader", formatter)
    }
}

impl SnapshotReader {
    /// Atomically captures a shared immutable history and its version.
    ///
    /// # Errors
    ///
    /// [`Error::Poisoned`] if a writer panicked while holding the store lock.
    /// There is no partial capture: a snapshot either observes one version
    /// together with the items that belong to it, or reports the poison.
    pub fn snapshot(&self) -> Result<Snapshot, Error> {
        self.core.snapshot()
    }

    /// Returns the current version without cloning item history.
    ///
    /// # Errors
    ///
    /// [`Error::Poisoned`] if a writer panicked while holding the store lock.
    pub fn version(&self) -> Result<Version, Error> {
        self.core.version()
    }
}

/// Append-only transcript authority.
///
/// Every method consumes an owned candidate before taking the commit lock. No
/// user clone or callback runs while the write lock is held; after all checks,
/// the ordered batch and version become visible in one critical section.
///
/// ```compile_fail
/// use reef_core::transcript::store;
/// let append = store::Store::new().appender();
/// append.replace(Vec::new());
/// ```
#[derive(Clone)]
pub struct Appender {
    core: Arc<Core>,
}

impl fmt::Debug for Appender {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.core.debug_handle("Appender", formatter)
    }
}

impl Appender {
    /// Appends one owned item and advances the version by one.
    ///
    /// # Errors
    ///
    /// [`Error::VersionOverflow`] if the store already stands at
    /// [`Version::MAX`], and [`Error::Poisoned`] if a writer panicked while
    /// holding the store lock. Either way the history is unchanged. There is no
    /// conflict to report, because this append accepts whatever version it finds.
    pub fn append(&self, item: Item) -> Result<Version, Error> {
        self.core.append_batch(vec![item], None)
    }

    /// Atomically appends an owned ordered batch.
    ///
    /// The version advances by `items.len()`. An empty batch is a successful
    /// no-op which still reports lock poisoning.
    ///
    /// # Errors
    ///
    /// [`Error::VersionOverflow`], reporting the current version and the
    /// requested increment, if advancing by `items.len()` would pass
    /// [`Version::MAX`]; and [`Error::Poisoned`] if a writer panicked while
    /// holding the store lock. A failure appends none of the batch — this is the
    /// atomicity the whole crate's "never write half of an exchange" rule rests
    /// on, so a rejected batch leaves no partial history behind.
    pub fn append_batch(&self, items: Vec<Item>) -> Result<Version, Error> {
        self.core.append_batch(items, None)
    }

    /// Atomically appends a batch only at `expected`.
    ///
    /// Even an empty batch checks `expected`; conflicts and overflow leave both
    /// history and version unchanged.
    ///
    /// # Errors
    ///
    /// - [`Error::VersionConflict`], reporting both `expected` and the version
    ///   actually observed under the commit lock, if another writer advanced the
    ///   store after the caller read `expected`. The concurrent winner is never
    ///   overwritten; the loser is expected to re-read and decide again.
    /// - [`Error::VersionOverflow`] if the batch would advance past
    ///   [`Version::MAX`]. The conflict check runs first, so a stale caller hears
    ///   about staleness rather than about a limit it may not be near.
    /// - [`Error::Poisoned`] if a writer panicked while holding the store lock.
    pub fn append_batch_if_version(
        &self,
        items: Vec<Item>,
        expected: Version,
    ) -> Result<Version, Error> {
        self.core.append_batch(items, Some(expected))
    }
}

/// Whole-history replacement authority without append authority.
///
/// Candidates are fully owned before locking. A successful replacement swaps
/// the complete vector and advances the version once.
///
/// ```compile_fail
/// use reef_core::transcript::store;
/// let replace = store::Store::new().replacer();
/// replace.append_batch(Vec::new());
/// ```
#[derive(Clone)]
pub struct Replacer {
    core: Arc<Core>,
}

impl fmt::Debug for Replacer {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.core.debug_handle("Replacer", formatter)
    }
}

impl Replacer {
    /// Atomically replaces all items and advances the version by one.
    ///
    /// # Errors
    ///
    /// [`Error::VersionOverflow`] if the store already stands at
    /// [`Version::MAX`], and [`Error::Poisoned`] if a writer panicked while
    /// holding the store lock. A failed replacement swaps nothing: the previous
    /// history is still the whole history.
    pub fn replace(&self, items: Vec<Item>) -> Result<Version, Error> {
        self.core.replace(items, None)
    }

    /// Atomically replaces all items only when the live version is `expected`.
    ///
    /// A conflict returns the expected and actual versions without overwriting
    /// the concurrent winner.
    ///
    /// # Errors
    ///
    /// - [`Error::VersionConflict`], reporting both `expected` and the version
    ///   observed under the commit lock, if another writer advanced the store
    ///   after the caller read `expected`. This is the check that makes a
    ///   compaction safe to attempt concurrently: the candidate is discarded
    ///   rather than overwriting work the caller never saw.
    /// - [`Error::VersionOverflow`] if the store already stands at
    ///   [`Version::MAX`]. The conflict check runs first.
    /// - [`Error::Poisoned`] if a writer panicked while holding the store lock.
    pub fn replace_if_version(
        &self,
        items: Vec<Item>,
        expected: Version,
    ) -> Result<Version, Error> {
        self.core.replace(items, Some(expected))
    }

    pub(crate) fn install_snapshot_if_version(
        &self,
        snapshot: Snapshot,
        expected: Version,
    ) -> Result<Version, Error> {
        self.core.replace_snapshot(snapshot, expected)
    }
}

#[cfg(test)]
pub(super) fn install_commit_overlap(store: &Store) -> CommitOverlapControl {
    let overlap = Arc::new(CommitOverlap::new());
    *store
        .core
        .commit_overlap
        .lock()
        .expect("test overlap lock must be healthy") = Some(Arc::clone(&overlap));
    CommitOverlapControl { overlap }
}

/// Holds the production write lock so a `Debug` must observe contention.
///
/// ADR-018 forbids a formatter from waiting on a lock, and the only way to
/// prove it does not is to format one that is genuinely held.
#[cfg(test)]
pub(super) fn hold_write_lock(store: &Store, held: &Barrier, release: &Barrier) {
    let _guard = store.core.state.write().expect("test lock starts healthy");
    held.wait();
    release.wait();
}

#[cfg(test)]
pub(crate) fn poison(store: &Store) {
    let _guard = store.core.state.write().expect("test lock starts healthy");
    panic!("intentional transcript-store poison");
}

/// The serialized form of [`Version`] and [`Snapshot`] (ADR-019 D5).
///
/// A version is a bare integer — its own documentation already calls that "the
/// persisted integer representation" — and a snapshot is `version` then `items`.
///
/// `Snapshot::version` is not a schema version and core emits none. It counts the
/// history's revisions, not the encoding's; a version belongs to a document, and
/// core serializes values, so the layer that writes a file owns its envelope.
#[cfg(feature = "serde")]
mod serde_impl {
    use std::fmt::{self, Formatter};

    use serde_core::de::{
        Deserialize, Deserializer, Error as DeError, MapAccess, SeqAccess, Visitor,
    };
    use serde_core::ser::{Serialize, SerializeStruct, Serializer};

    use super::{Snapshot, Version};
    use crate::wire::{self, IdentifierSeed};

    const SNAPSHOT_FIELDS: &[&str] = &["version", "items"];

    impl Serialize for Version {
        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where
            S: Serializer,
        {
            serializer.serialize_u64(self.0)
        }
    }

    impl<'de> Deserialize<'de> for Version {
        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
        where
            D: Deserializer<'de>,
        {
            u64::deserialize(deserializer).map(Self::from_u64)
        }
    }

    impl Serialize for Snapshot {
        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where
            S: Serializer,
        {
            let mut record = serializer.serialize_struct("Snapshot", 2)?;
            record.serialize_field("version", &self.version)?;
            record.serialize_field("items", self.items())?;
            record.end()
        }
    }

    impl<'de> Deserialize<'de> for Snapshot {
        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
        where
            D: Deserializer<'de>,
        {
            deserializer.deserialize_struct("Snapshot", SNAPSHOT_FIELDS, SnapshotVisitor)
        }
    }

    struct SnapshotVisitor;

    impl<'de> Visitor<'de> for SnapshotVisitor {
        type Value = Snapshot;

        fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
            formatter.write_str("a transcript snapshot")
        }

        fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
        where
            A: SeqAccess<'de>,
        {
            let version = wire::element(&mut sequence, 0)?;
            let items = wire::element(&mut sequence, 1)?;
            wire::end(&mut sequence, 2)?;
            Ok(Snapshot::new(version, items))
        }

        fn visit_map<A>(self, mut entries: A) -> Result<Self::Value, A::Error>
        where
            A: MapAccess<'de>,
        {
            let mut version = None;
            let mut items = None;
            while let Some(field) = entries.next_key_seed(IdentifierSeed(SNAPSHOT_FIELDS))? {
                match field.0.as_str() {
                    "version" => wire::accept(&mut version, entries.next_value()?, "version")?,
                    "items" => wire::accept(&mut items, entries.next_value()?, "items")?,
                    unknown => return Err(A::Error::unknown_field(unknown, SNAPSHOT_FIELDS)),
                }
            }
            Ok(Snapshot::new(
                wire::require(version, "version")?,
                wire::require(items, "items")?,
            ))
        }
    }
}