allen-store 0.1.0

Storage-agnostic persistence typeclass (AgentStore), InMemoryStore, and shared backend conformance suite
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
//! Defines the storage-agnostic Layer 1 persistence contract ([`AgentStore`]), a
//! reference [`InMemoryStore`], and a shared backend conformance suite for durable,
//! multi-tenant agent runtimes.
//!
//! # Architecture & Layer Role
//!
//! Within the Allen Open Agent Infrastructure Standard, `allen-store` is the abstract
//! interface of Layer 1 (Persistence). It depends only on pure Layer 0 (`allen-types`)
//! and carries zero SQL drivers or filesystem I/O. Layer 4 (`allen-runtime`) is generic
//! over [`AgentStore`], while concrete backends (`allen-store-sqlite` for single-node
//! local execution and external custom backends for multi-replica deployments)
//! implement the four sub-traits and verify behavioral parity through the shared
//! conformance suite.
//!
//! # Quick Start
//!
//! ```rust
//! use allen_store::{
//!     CommandStore, InMemoryStore, LeaseStore, OwnerId, SessionStore, StepCommit, StoreError,
//! };
//! use allen_types::ids::{EntryId, SessionId, SessionRevision, TenantId};
//! use allen_types::session::{ContentBlock, SessionEntry, SessionEntryPayload};
//! use std::time::Duration;
//!
//! # tokio::runtime::Runtime::new().unwrap().block_on(async {
//! let store = InMemoryStore::new();
//! let tenant = TenantId::try_new("org:demo").unwrap();
//! let session = SessionId::try_new("sess:1").unwrap();
//! let owner = OwnerId::try_new("worker-1").unwrap();
//!
//! // 1. Create a session and acquire an exclusive fenced lease.
//! store.create_session(&tenant, &session, None).await.unwrap();
//! let lease = store
//!     .acquire_session_lease(&tenant, &session, &owner, Duration::from_secs(30))
//!     .await
//!     .unwrap();
//!
//! // 2. Commit a session entry atomically under optimistic revision CAS.
//! let mut commit = StepCommit::empty(SessionRevision::INITIAL);
//! commit.entries.push(SessionEntry {
//!     tenant_id: tenant.clone(),
//!     session_id: session.clone(),
//!     entry_id: EntryId::try_new("entry:1").unwrap(),
//!     parent_entry_id: None,
//!     run_id: Some(lease.run_id().clone()),
//!     created_at_ms: 1_000,
//!     payload: SessionEntryPayload::UserMessage {
//!         blocks: vec![ContentBlock::text("hello")],
//!         origin: None,
//!         delivery: None,
//!     },
//! });
//! let committed = store.commit_step(&lease, commit).await.unwrap();
//! assert_eq!(committed.new_revision, SessionRevision::from_u64(1));
//!
//! // 3. Reusing the stale expected_revision fails closed with RevisionConflict.
//! let conflict = store
//!     .commit_step(&lease, StepCommit::empty(SessionRevision::INITIAL))
//!     .await
//!     .unwrap_err();
//! assert!(matches!(conflict, StoreError::RevisionConflict { .. }));
//!
//! // 4. Load the committed branch from root to active leaf.
//! let branch = store.load_branch(&tenant, &session, None).await.unwrap();
//! assert_eq!(branch.entries.len(), 1);
//! # });
//! ```
//!
//! # Feature Flags
//!
//! - `conformance`: Exposes the `conformance` module (`conformance::run_all` and
//!   `conformance::run_concurrency`) outside this crate's unit tests so backend crates
//!   can test their [`AgentStore`] implementations against the standard invariant suite.
//!   Disabled by default.
//!
//! # Module Guide
//!
//! - Root module:
//!   - Traits: [`LeaseStore`], [`CommandStore`], [`SessionStore`], [`SpendStore`], and
//!     their blanket supertrait [`AgentStore`].
//!   - Identifiers & tokens: [`OwnerId`], [`PoolName`], [`LeaseToken`], and
//!     [`TerminalRunStatus`].
//!   - Atomic checkpoint payloads: [`StepCommit`], [`StepCommitResult`], [`NewEffect`],
//!     [`EffectTransition`], [`NewSpendEntry`], [`PendingCommandReceipt`],
//!     [`CommandReceipt`], and [`LoadedBranch`].
//!   - Error surface: [`StoreError`].
//! - [`prelude`]: Re-exports the core persistence traits, checkpoint payloads, [`StoreError`],
//!   and [`InMemoryStore`] for a single `use allen_store::prelude::*;` import.
//! - [`memory`]: Reference [`InMemoryStore`] implementation for ephemeral runs and tests.
//! - `conformance` (requires feature `conformance`): Shared functional and concurrent
//!   contention verification suite.
//!
//! # Safety & Durability Invariants
//!
//! - Enforces `#![forbid(unsafe_code)]`, zero SQL drivers, and zero filesystem I/O.
//! - Requires a backend-issued [`LeaseToken`] on every mutating run or step operation
//!   and checks its monotonic [`OwnerFence`] atomically so superseded workers fail
//!   closed with [`StoreError::StaleFence`].
//! - Commits session entries, active leaf updates, scope epoch bumps, effect journal
//!   mutations, checked integer [`MicroUsd`] spend rows, and command deduplication
//!   receipts in one atomic [`CommandStore::commit_step`] transaction fenced by
//!   optimistic [`SessionRevision`] compare-and-swap.
//! - Transitions in-flight `Claimed` effects to `Unknown` atomically whenever a lease
//!   is recovered or superseded so side-effecting actions are reconciled before retry.
//! - Enforces tenant isolation on every read and write, failing closed with
//!   [`StoreError::TenantMismatch`] or [`StoreError::NotFound`].

#![forbid(unsafe_code)]
#![warn(missing_docs)]
#![cfg_attr(docsrs, feature(doc_cfg))]
#![cfg_attr(not(test), deny(clippy::unwrap_used, clippy::expect_used))]

#[cfg(any(test, feature = "conformance"))]
#[cfg_attr(docsrs, doc(cfg(feature = "conformance")))]
pub mod conformance;
pub mod memory;

/// Re-exports the core Layer 1 persistence traits, checkpoint payloads, [`StoreError`], and
/// [`InMemoryStore`] for concise imports (`use allen_store::prelude::*;`).
///
/// # Examples
///
/// ```rust
/// use allen_store::prelude::*;
/// use allen_types::ids::{SessionId, SessionRevision, TenantId};
///
/// # tokio::runtime::Runtime::new().unwrap().block_on(async {
/// let store = InMemoryStore::new();
/// let tenant = TenantId::try_new("org:demo").unwrap();
/// let session = SessionId::try_new("sess:prelude").unwrap();
/// let created = store.create_session(&tenant, &session, None).await.unwrap();
/// assert_eq!(created.new_revision, SessionRevision::INITIAL);
/// # });
/// ```
pub mod prelude {
    pub use crate::{
        AgentStore, CommandReceipt, CommandStore, EffectTransition, InMemoryStore, LeaseStore,
        LeaseToken, LoadedBranch, NewEffect, NewSpendEntry, OwnerId, PendingCommandReceipt,
        PoolName, SessionStore, SpendStore, StepCommit, StepCommitResult, StoreError,
        TerminalRunStatus,
    };
}

use allen_types::ids::{
    CommandId, EffectId, EntryId, InvalidIdError, OwnerFence, RunId, ScopeEpochs, SessionId,
    SessionRevision, TenantId,
};
use allen_types::journal::{EffectEvent, EffectRecord, IllegalEffectTransition};
use allen_types::lifecycle::CommandSettlement;
use allen_types::money::{BillingClass, CostBasis, MicroUsd, SpendCategory};
use allen_types::session::{RunStatus, SessionEntry};
use futures_util::future::BoxFuture;
use serde::{Deserialize, Serialize};
use std::fmt;
use std::str::FromStr;
use std::time::Duration;

pub use memory::InMemoryStore;

macro_rules! store_string_id {
    ($(#[$meta:meta])* $name:ident) => {
        $(#[$meta])*
        #[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
        #[serde(try_from = "String", into = "String")]
        pub struct $name(String);

        impl $name {
            /// Validates and constructs a non-empty identifier containing no NUL bytes.
            ///
            /// # Errors
            ///
            /// Returns [`InvalidIdError::Empty`] if `value` is empty or whitespace-only,
            /// or [`InvalidIdError::ContainsNul`] if `value` contains `'\0'`.
            pub fn try_new(value: impl Into<String>) -> Result<Self, InvalidIdError> {
                let value = value.into();
                if value.trim().is_empty() {
                    return Err(InvalidIdError::Empty);
                }
                if value.contains('\0') {
                    return Err(InvalidIdError::ContainsNul);
                }
                Ok(Self(value))
            }

            /// Borrows the underlying validated string slice.
            #[must_use]
            pub fn as_str(&self) -> &str {
                &self.0
            }

            /// Consumes the identifier and returns the owned inner `String`.
            #[must_use]
            pub fn into_inner(self) -> String {
                self.0
            }
        }

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

        impl AsRef<str> for $name {
            fn as_ref(&self) -> &str {
                &self.0
            }
        }

        impl TryFrom<String> for $name {
            type Error = InvalidIdError;

            fn try_from(value: String) -> Result<Self, Self::Error> {
                Self::try_new(value)
            }
        }

        impl TryFrom<&str> for $name {
            type Error = InvalidIdError;

            fn try_from(value: &str) -> Result<Self, Self::Error> {
                Self::try_new(value)
            }
        }

        impl FromStr for $name {
            type Err = InvalidIdError;

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

        impl From<$name> for String {
            fn from(value: $name) -> Self {
                value.0
            }
        }
    };
}

store_string_id!(
    /// Identifier of a worker process or host holding an exclusive run or session lease.
    OwnerId
);

store_string_id!(
    /// Named worker pool from which background workers claim queued or expired runs.
    PoolName
);

/// Terminal run statuses accepted by [`LeaseStore::finish_run`].
///
/// Restricting the parameter type to this enum excludes non-terminal states
/// (`Queued`, `Running`, `WaitingApproval`) at compile time.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TerminalRunStatus {
    /// The run reached its intended completion state without unrecovered errors.
    Completed,
    /// The run terminated due to an unrecoverable error or policy failure.
    Failed,
    /// The run was explicitly cancelled before natural completion.
    Cancelled,
    /// The run paused in a durable terminal-until-resumed state (such as awaiting external intervention).
    Parked,
}

impl TerminalRunStatus {
    /// Converts this terminal status into its corresponding [`RunStatus`] variant.
    #[must_use]
    pub const fn as_run_status(self) -> RunStatus {
        match self {
            Self::Completed => RunStatus::Completed,
            Self::Failed => RunStatus::Failed,
            Self::Cancelled => RunStatus::Cancelled,
            Self::Parked => RunStatus::Parked,
        }
    }

    /// Returns the canonical `snake_case` wire and database representation of this status.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        self.as_run_status().as_str()
    }
}

impl From<TerminalRunStatus> for RunStatus {
    fn from(status: TerminalRunStatus) -> Self {
        status.as_run_status()
    }
}

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

/// Exclusive ownership capability for one active run or interactive session.
///
/// Every mutating store operation takes a `&LeaseToken` and verifies its monotonic
/// [`OwnerFence`] atomically against persisted run state. Fields are private so runtime
/// callers cannot mutate a token's fence or tenant scope after issuance.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct LeaseToken {
    tenant_id: TenantId,
    session_id: SessionId,
    run_id: RunId,
    owner_id: OwnerId,
    fence: OwnerFence,
    expires_at_ms: i64,
}

impl LeaseToken {
    /// Constructs a lease token from persisted backend state.
    ///
    /// Intended for [`LeaseStore`] backend implementations. Runtime callers should obtain
    /// tokens from [`LeaseStore`] methods rather than constructing them directly.
    #[must_use]
    pub fn from_backend(
        tenant_id: TenantId,
        session_id: SessionId,
        run_id: RunId,
        owner_id: OwnerId,
        fence: OwnerFence,
        expires_at_ms: i64,
    ) -> Self {
        Self {
            tenant_id,
            session_id,
            run_id,
            owner_id,
            fence,
            expires_at_ms,
        }
    }

    /// Returns the tenant that owns the leased session and run.
    #[must_use]
    pub fn tenant_id(&self) -> &TenantId {
        &self.tenant_id
    }

    /// Returns the session bound to this lease.
    #[must_use]
    pub fn session_id(&self) -> &SessionId {
        &self.session_id
    }

    /// Returns the run owned by this lease.
    #[must_use]
    pub fn run_id(&self) -> &RunId {
        &self.run_id
    }

    /// Returns the worker or host identifier that currently owns this lease.
    #[must_use]
    pub fn owner_id(&self) -> &OwnerId {
        &self.owner_id
    }

    /// Returns the monotonic [`OwnerFence`] verified on every fenced mutation.
    #[must_use]
    pub const fn fence(&self) -> OwnerFence {
        self.fence
    }

    /// Returns the Unix epoch timestamp in milliseconds when this lease expires unless renewed.
    #[must_use]
    pub const fn expires_at_ms(&self) -> i64 {
        self.expires_at_ms
    }
}

/// Persisted command deduplication receipt returned by [`CommandStore::lookup_receipt`].
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct CommandReceipt {
    /// Tenant owning the session on which the command settled.
    pub tenant_id: TenantId,
    /// Session on which the command settled.
    pub session_id: SessionId,
    /// Caller-supplied idempotency identifier of the settled command.
    pub command_id: CommandId,
    /// Terminal disposition recorded when the command settled.
    pub settlement: CommandSettlement,
    /// Session revision produced by the [`CommandStore::commit_step`] that persisted this receipt.
    pub resulting_revision: SessionRevision,
    /// Session branch and activity epochs immediately after the commit.
    pub epochs: ScopeEpochs,
    /// Structured JSON outcome payload returned to retrying callers.
    pub payload_json: serde_json::Value,
}

/// Command deduplication receipt staged for atomic persistence inside [`StepCommit`].
///
/// The backend derives `tenant_id`, `session_id`, `resulting_revision`, and `epochs` from
/// the active [`LeaseToken`] and post-commit session state.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct PendingCommandReceipt {
    /// Unique idempotency identifier for the command within `(tenant_id, session_id)`.
    pub command_id: CommandId,
    /// Terminal disposition to record for the command.
    pub settlement: CommandSettlement,
    /// Structured JSON outcome payload persisted alongside the receipt.
    pub payload_json: serde_json::Value,
}

/// New external side-effect record prepared atomically inside [`StepCommit`].
///
/// Backends insert each prepared effect in `EffectState::Prepared` scoped to the active
/// [`LeaseToken`]'s tenant, run, and [`OwnerFence`].
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct NewEffect {
    /// Unique identifier for the prepared effect record.
    pub effect_id: EffectId,
    /// Tenant-unique idempotency key preventing duplicate execution of the same external action.
    pub idempotency_key: String,
    /// SHA-256 hex digest describing the canonical action payload to be executed.
    pub action_sha256: String,
}

/// State-machine transition applied to an existing or newly prepared effect inside [`StepCommit`].
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct EffectTransition {
    /// Identifier of the effect record to transition.
    pub effect_id: EffectId,
    /// Journal event validated against the effect's current state by `allen_types::journal::transition_effect`.
    pub event: EffectEvent,
    /// Optional SHA-256 or opaque digest of the observed external result to record on the effect.
    pub result_digest: Option<String>,
}

/// Checked integer spend ledger row staged for atomic persistence inside [`StepCommit`].
///
/// Backends derive `tenant_id`, `session_id`, and `run_id` from the active [`LeaseToken`].
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct NewSpendEntry {
    /// Whether this charge is billable to the tenant or internal/non-billable overhead.
    pub billing_class: BillingClass,
    /// Structured spend category (inference tokens, sandbox compute, or external tool usage).
    pub category: SpendCategory,
    /// Non-negative cost amount in micro-USD (`10^-6` USD).
    pub cost: MicroUsd,
    /// Provenance of `cost` (for example, provider-reported vs. catalog-estimated).
    pub basis: CostBasis,
    /// Unix epoch timestamp in milliseconds when the spend was recorded.
    pub recorded_at_ms: i64,
}

/// Atomic durable checkpoint committed by [`CommandStore::commit_step`].
///
/// Backends execute the entire checkpoint inside one transaction (for example, SQLite
/// `BEGIN IMMEDIATE` or a single PostgreSQL transaction), verifying the lease's
/// [`OwnerFence`] and the session's `expected_revision` before applying any change.
/// If any check or constraint fails, all entries, leaf changes, effects, spend rows, and
/// receipts in the commit roll back together.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct StepCommit {
    /// Expected current [`SessionRevision`] checked by optimistic compare-and-swap.
    pub expected_revision: SessionRevision,
    /// Session tree entries to append in order; each must match the lease's tenant and session.
    pub entries: Vec<SessionEntry>,
    /// Explicit active leaf to select after appending `entries`; when `None`, the last entry
    /// in `entries` (if any) becomes the active leaf.
    pub new_leaf: Option<EntryId>,
    /// When `true`, increments the session's branch epoch (used on branch switch or fork).
    pub bump_branch_epoch: bool,
    /// When `true`, increments the session's activity epoch (used when observable turn state advances).
    pub bump_activity_epoch: bool,
    /// New effects to insert in `EffectState::Prepared` before applying `effect_transitions`.
    pub prepare_effects: Vec<NewEffect>,
    /// Effect state transitions validated and applied in order after `prepare_effects`.
    pub effect_transitions: Vec<EffectTransition>,
    /// Spend ledger entries appended atomically with this step.
    pub spend: Vec<NewSpendEntry>,
    /// Optional command deduplication receipt recorded atomically with this step.
    pub receipt: Option<PendingCommandReceipt>,
}

impl StepCommit {
    /// Creates an empty [`StepCommit`] expecting `expected_revision` with no entries,
    /// epoch bumps, effects, spend rows, or command receipt.
    ///
    /// Committing an empty step still validates the lease fence and advances the session
    /// revision by one.
    #[must_use]
    pub fn empty(expected_revision: SessionRevision) -> Self {
        Self {
            expected_revision,
            entries: Vec::new(),
            new_leaf: None,
            bump_branch_epoch: false,
            bump_activity_epoch: false,
            prepare_effects: Vec::new(),
            effect_transitions: Vec::new(),
            spend: Vec::new(),
            receipt: None,
        }
    }
}

/// Post-commit session metadata returned by [`SessionStore::create_session`] and
/// [`CommandStore::commit_step`].
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct StepCommitResult {
    /// Session revision persisted after the operation succeeded.
    pub new_revision: SessionRevision,
    /// Branch and activity epochs persisted after the operation succeeded.
    pub epochs: ScopeEpochs,
}

/// Root-to-leaf session branch snapshot returned by [`SessionStore::load_branch`].
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct LoadedBranch {
    /// Current persisted [`SessionRevision`] of the session at read time.
    pub revision: SessionRevision,
    /// Current persisted [`ScopeEpochs`] of the session at read time.
    pub epochs: ScopeEpochs,
    /// Ordered entries from the root entry to the requested (or active) leaf.
    pub entries: Vec<SessionEntry>,
}

/// Failure returned by [`AgentStore`] operations across all backends.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum StoreError {
    /// A referenced session, run, entry, or effect does not exist.
    NotFound(String),
    /// A caller supplied a tenant or session scope that does not match the target record.
    TenantMismatch,
    /// The supplied [`LeaseToken`] carries an older [`OwnerFence`] than the persisted run.
    StaleFence {
        /// Fence carried by the caller's stale [`LeaseToken`].
        expected: OwnerFence,
        /// Current authoritative fence stored on the run.
        actual: OwnerFence,
    },
    /// Optimistic compare-and-swap in [`CommandStore::commit_step`] observed a newer revision.
    RevisionConflict {
        /// Revision expected by the caller's [`StepCommit`].
        expected: SessionRevision,
        /// Current authoritative revision stored on the session.
        actual: SessionRevision,
    },
    /// Another owner holds an unexpired lease on the target session or run.
    LeaseHeldByOther {
        /// Unix epoch timestamp in milliseconds when the competing lease expires.
        expires_at_ms: i64,
    },
    /// An [`EffectTransition`] violated the Layer 0 effect state machine.
    IllegalTransition(IllegalEffectTransition),
    /// A unique session ID, run ID, command receipt, effect ID, or effect idempotency key already exists.
    DuplicateIdempotencyKey(String),
    /// Startup migration verification detected a checksum or name mismatch against an applied SQL migration.
    SchemaDrift(String),
    /// Backend-specific storage, serialization, invariant, or lifecycle error.
    Backend(String),
}

impl From<IllegalEffectTransition> for StoreError {
    fn from(err: IllegalEffectTransition) -> Self {
        Self::IllegalTransition(err)
    }
}

impl fmt::Display for StoreError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::NotFound(msg)
            | Self::DuplicateIdempotencyKey(msg)
            | Self::SchemaDrift(msg)
            | Self::Backend(msg) => f.write_str(msg),
            Self::IllegalTransition(err) => err.fmt(f),
            Self::TenantMismatch => f.write_str("tenant mismatch"),
            Self::StaleFence { expected, actual } => {
                write!(f, "stale owner fence: expected {expected}, actual {actual}")
            }
            Self::RevisionConflict { expected, actual } => write!(
                f,
                "session revision conflict: expected {expected}, actual {actual}"
            ),
            Self::LeaseHeldByOther { expires_at_ms } => {
                write!(f, "lease held by another owner until {expires_at_ms}")
            }
        }
    }
}

impl std::error::Error for StoreError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::IllegalTransition(err) => Some(err),
            _ => None,
        }
    }
}

/// Sub-trait 1: Exclusive run and session leasing for interactive sessions and pull-queue workers.
pub trait LeaseStore: Send + Sync {
    /// Enqueues a new background run in `Queued` status for workers polling `pool_name`.
    ///
    /// # Errors
    ///
    /// Returns [`StoreError::NotFound`] if `session_id` does not exist,
    /// [`StoreError::TenantMismatch`] if `session_id` belongs to another tenant,
    /// [`StoreError::DuplicateIdempotencyKey`] if `run_id` already exists, or
    /// [`StoreError::Backend`] on storage failure.
    fn enqueue_run<'a>(
        &'a self,
        tenant_id: &'a TenantId,
        session_id: &'a SessionId,
        run_id: &'a RunId,
        pool_name: &'a PoolName,
    ) -> BoxFuture<'a, Result<(), StoreError>>;

    /// Acquires or supersedes an exclusive lease on an interactive session for `owner_id`.
    ///
    /// Creates a new interactive run when none is running on `session_id`, or supersedes an
    /// existing running lease held by `owner_id` (or an expired lease held by another owner)
    /// by advancing [`OwnerFence`] and transitioning any `Claimed` effects on that run to
    /// `Unknown` atomically.
    ///
    /// # Errors
    ///
    /// Returns [`StoreError::NotFound`] if `session_id` does not exist,
    /// [`StoreError::TenantMismatch`] if `session_id` belongs to another tenant,
    /// [`StoreError::LeaseHeldByOther`] if a different owner holds an unexpired lease on
    /// `session_id`, or [`StoreError::Backend`] on storage failure.
    fn acquire_session_lease<'a>(
        &'a self,
        tenant_id: &'a TenantId,
        session_id: &'a SessionId,
        owner_id: &'a OwnerId,
        ttl: Duration,
    ) -> BoxFuture<'a, Result<LeaseToken, StoreError>>;

    /// Atomically claims at most one `Queued` run from `pool_name` for `owner_id` with lease
    /// lifetime `ttl`.
    ///
    /// Multi-replica backends use non-blocking row locking (such as `FOR UPDATE SKIP LOCKED`
    /// in PostgreSQL) so concurrent workers never claim the same run twice. Returns `Ok(None)`
    /// when no queued run is available in `pool_name`.
    ///
    /// # Errors
    ///
    /// Returns [`StoreError::Backend`] on storage or fence overflow failures.
    fn claim_queued_run<'a>(
        &'a self,
        owner_id: &'a OwnerId,
        pool_name: &'a PoolName,
        ttl: Duration,
    ) -> BoxFuture<'a, Result<Option<LeaseToken>, StoreError>>;

    /// Atomically claims one expired running lease in `pool_name`
    /// (`status = 'running' AND expires_at_ms <= now_ms`), advances [`OwnerFence`], updates
    /// ownership and expiry to `owner_id` / `ttl`, and transitions all `Claimed` effects on
    /// that run to `Unknown`.
    ///
    /// Live leases with `expires_at_ms > now_ms` are never touched. Returns `Ok(None)` when
    /// no expired running lease exists in `pool_name`.
    ///
    /// # Errors
    ///
    /// Returns [`StoreError::IllegalTransition`] or [`StoreError::Backend`] on invariant or
    /// storage failures.
    fn reclaim_expired_run<'a>(
        &'a self,
        owner_id: &'a OwnerId,
        pool_name: &'a PoolName,
        ttl: Duration,
    ) -> BoxFuture<'a, Result<Option<LeaseToken>, StoreError>>;

    /// Extends the expiration timestamp of an active `lease` by `ttl` without changing its
    /// [`OwnerFence`].
    ///
    /// # Errors
    ///
    /// Returns [`StoreError::NotFound`] if the run does not exist,
    /// [`StoreError::TenantMismatch`] if the token's tenant or session does not match,
    /// [`StoreError::StaleFence`] if another owner or [`Self::finish_run`] advanced the fence,
    /// or [`StoreError::Backend`] if the run is not in `Running` status or storage fails.
    fn renew_lease<'a>(
        &'a self,
        lease: &'a LeaseToken,
        ttl: Duration,
    ) -> BoxFuture<'a, Result<LeaseToken, StoreError>>;

    /// Marks the leased run with a terminal [`TerminalRunStatus`] and optional `summary_code`,
    /// advancing [`OwnerFence`] so subsequent calls using `lease` fail closed with
    /// [`StoreError::StaleFence`].
    ///
    /// # Errors
    ///
    /// Returns [`StoreError::NotFound`], [`StoreError::TenantMismatch`],
    /// [`StoreError::StaleFence`], or [`StoreError::Backend`] when the run is missing,
    /// fenced out, or not in `Running` status.
    fn finish_run<'a>(
        &'a self,
        lease: &'a LeaseToken,
        status: TerminalRunStatus,
        summary_code: Option<&'a str>,
    ) -> BoxFuture<'a, Result<(), StoreError>>;

    /// Reclaims a specific expired running lease (`status = 'running' AND expires_at_ms <= now_ms`)
    /// for `new_owner_id`, returning the new [`LeaseToken`] and all `Claimed` effects that
    /// transitioned atomically to `Unknown`.
    ///
    /// Refuses live unexpired leases with [`StoreError::LeaseHeldByOther`] and refuses
    /// queued or terminal runs with [`StoreError::Backend`].
    ///
    /// # Errors
    ///
    /// Returns [`StoreError::NotFound`], [`StoreError::TenantMismatch`],
    /// [`StoreError::LeaseHeldByOther`], [`StoreError::IllegalTransition`], or
    /// [`StoreError::Backend`].
    fn recover_expired_run<'a>(
        &'a self,
        tenant_id: &'a TenantId,
        run_id: &'a RunId,
        new_owner_id: &'a OwnerId,
        ttl: Duration,
    ) -> BoxFuture<'a, Result<(LeaseToken, Vec<EffectRecord>), StoreError>>;

    /// Forces operator or conformance takeover of a non-terminal (`Running` or
    /// `WaitingApproval`) run regardless of whether its lease has expired.
    ///
    /// Advances [`OwnerFence`] and transitions all `Claimed` effects on `run_id` to
    /// `Unknown` in one atomic transaction. Refuses `Queued` and terminal runs
    /// (`Completed`, `Failed`, `Cancelled`, `Parked`).
    ///
    /// # Errors
    ///
    /// Returns [`StoreError::NotFound`], [`StoreError::TenantMismatch`],
    /// [`StoreError::IllegalTransition`], or [`StoreError::Backend`].
    fn force_recover_run<'a>(
        &'a self,
        tenant_id: &'a TenantId,
        run_id: &'a RunId,
        new_owner_id: &'a OwnerId,
        ttl: Duration,
    ) -> BoxFuture<'a, Result<LeaseToken, StoreError>>;
}

/// Sub-trait 2: Atomic step checkpoints, command deduplication receipts, and effect inspection.
pub trait CommandStore: Send + Sync {
    /// Looks up a previously committed [`CommandReceipt`] for `(tenant_id, session_id, command_id)`.
    ///
    /// Returns `Ok(None)` if `command_id` has not been committed for that session.
    ///
    /// # Errors
    ///
    /// Returns [`StoreError::TenantMismatch`] if `session_id` belongs to another tenant,
    /// or [`StoreError::Backend`] on storage or deserialization failure.
    fn lookup_receipt<'a>(
        &'a self,
        tenant_id: &'a TenantId,
        session_id: &'a SessionId,
        command_id: &'a CommandId,
    ) -> BoxFuture<'a, Result<Option<CommandReceipt>, StoreError>>;

    /// Atomically verifies `lease` and `commit.expected_revision`, then persists all entries,
    /// leaf pointer updates, epoch bumps, effect journal mutations, spend entries, and the
    /// optional command receipt in a single transaction.
    ///
    /// On any error, backends roll back the entire checkpoint so no partial entries, effects,
    /// spend rows, or receipts become visible.
    ///
    /// # Errors
    ///
    /// Returns:
    /// - [`StoreError::NotFound`] if the run, session, target `new_leaf`, or transitioned
    ///   effect does not exist.
    /// - [`StoreError::TenantMismatch`] if any entry, effect, run, or session crosses tenant
    ///   or session boundaries.
    /// - [`StoreError::StaleFence`] if `lease` no longer holds the authoritative [`OwnerFence`].
    /// - [`StoreError::RevisionConflict`] if the session's revision differs from
    ///   `commit.expected_revision`.
    /// - [`StoreError::IllegalTransition`] if an [`EffectTransition`] violates the Layer 0
    ///   effect state machine.
    /// - [`StoreError::DuplicateIdempotencyKey`] if an entry ID, effect ID, effect
    ///   idempotency key, or command receipt ID collides with an existing record.
    /// - [`StoreError::Backend`] on storage or serialization failure.
    fn commit_step<'a>(
        &'a self,
        lease: &'a LeaseToken,
        commit: StepCommit,
    ) -> BoxFuture<'a, Result<StepCommitResult, StoreError>>;

    /// Lists every effect in `EffectState::Unknown` belonging to `(tenant_id, run_id)`.
    ///
    /// Runtimes query this method after crash recovery to reconcile ambiguous external
    /// side effects before scheduling new actions.
    ///
    /// # Errors
    ///
    /// Returns [`StoreError::TenantMismatch`] if `run_id` belongs to another tenant, or
    /// [`StoreError::Backend`] on storage or deserialization failure.
    fn list_unknown_effects<'a>(
        &'a self,
        tenant_id: &'a TenantId,
        run_id: &'a RunId,
    ) -> BoxFuture<'a, Result<Vec<EffectRecord>, StoreError>>;

    /// Lists every effect currently in `EffectState::Claimed` belonging to `(tenant_id, run_id)`.
    ///
    /// # Errors
    ///
    /// Returns [`StoreError::TenantMismatch`] if `run_id` belongs to another tenant, or
    /// [`StoreError::Backend`] on storage or deserialization failure.
    fn list_claimed_effects<'a>(
        &'a self,
        tenant_id: &'a TenantId,
        run_id: &'a RunId,
    ) -> BoxFuture<'a, Result<Vec<EffectRecord>, StoreError>>;
}

/// Sub-trait 3: Durable session tree creation and root-to-leaf branch loading.
pub trait SessionStore: Send + Sync {
    /// Creates a new empty session at [`SessionRevision::INITIAL`] with default [`ScopeEpochs`].
    ///
    /// Optional `parent_session_id` records lineage when spawning child or forked sessions.
    ///
    /// # Errors
    ///
    /// Returns [`StoreError::DuplicateIdempotencyKey`] if `session_id` already exists, or
    /// [`StoreError::Backend`] on storage failure.
    fn create_session<'a>(
        &'a self,
        tenant_id: &'a TenantId,
        session_id: &'a SessionId,
        parent_session_id: Option<&'a SessionId>,
    ) -> BoxFuture<'a, Result<StepCommitResult, StoreError>>;

    /// Loads the ordered root-to-leaf [`SessionEntry`] chain for `session_id`.
    ///
    /// When `leaf` is `None`, loads the session's current active leaf (returning an empty
    /// `entries` vector for a brand-new session). Detects parent-pointer cycles and rejects
    /// cross-tenant reads.
    ///
    /// # Errors
    ///
    /// Returns [`StoreError::NotFound`] if the session or a referenced entry does not exist,
    /// [`StoreError::TenantMismatch`] if `session_id` belongs to another tenant, or
    /// [`StoreError::Backend`] on cycle detection or storage/deserialization failure.
    fn load_branch<'a>(
        &'a self,
        tenant_id: &'a TenantId,
        session_id: &'a SessionId,
        leaf: Option<&'a EntryId>,
    ) -> BoxFuture<'a, Result<LoadedBranch, StoreError>>;
}

/// Sub-trait 4: Checked integer [`MicroUsd`] spend ledger queries.
///
/// Writes enter the spend ledger exclusively through atomic [`CommandStore::commit_step`]
/// checkpoints so spend accounting rolls back alongside failed steps.
pub trait SpendStore: Send + Sync {
    /// Sums all spend rows recorded for `tenant_id` with `recorded_at_ms >= since_ms`,
    /// optionally restricted to a single [`BillingClass`].
    ///
    /// Uses saturating [`MicroUsd`] addition so sums never wrap.
    ///
    /// # Errors
    ///
    /// Returns [`StoreError::Backend`] on storage or corrupt-row failures.
    fn sum_spend_since<'a>(
        &'a self,
        tenant_id: &'a TenantId,
        since_ms: i64,
        billing_class: Option<BillingClass>,
    ) -> BoxFuture<'a, Result<MicroUsd, StoreError>>;

    /// Sums all spend rows recorded for `(tenant_id, run_id)` across all billing classes.
    ///
    /// # Errors
    ///
    /// Returns [`StoreError::Backend`] on storage or corrupt-row failures.
    fn sum_run_spend<'a>(
        &'a self,
        tenant_id: &'a TenantId,
        run_id: &'a RunId,
    ) -> BoxFuture<'a, Result<MicroUsd, StoreError>>;
}

/// Unified Layer 1 persistence supertrait combining [`LeaseStore`], [`CommandStore`],
/// [`SessionStore`], and [`SpendStore`].
///
/// Any type implementing all four sub-traits (including [`InMemoryStore`],
/// `SqliteAgentStore`, external custom backends, and `Arc<T>`) implements `AgentStore`
/// automatically via the blanket implementation.
pub trait AgentStore: LeaseStore + CommandStore + SessionStore + SpendStore {}
impl<T: LeaseStore + CommandStore + SessionStore + SpendStore> AgentStore for T {}

impl<T: LeaseStore + ?Sized> LeaseStore for std::sync::Arc<T> {
    fn enqueue_run<'a>(
        &'a self,
        tenant_id: &'a TenantId,
        session_id: &'a SessionId,
        run_id: &'a RunId,
        pool_name: &'a PoolName,
    ) -> BoxFuture<'a, Result<(), StoreError>> {
        (**self).enqueue_run(tenant_id, session_id, run_id, pool_name)
    }
    fn acquire_session_lease<'a>(
        &'a self,
        tenant_id: &'a TenantId,
        session_id: &'a SessionId,
        owner_id: &'a OwnerId,
        ttl: Duration,
    ) -> BoxFuture<'a, Result<LeaseToken, StoreError>> {
        (**self).acquire_session_lease(tenant_id, session_id, owner_id, ttl)
    }
    fn claim_queued_run<'a>(
        &'a self,
        owner_id: &'a OwnerId,
        pool_name: &'a PoolName,
        ttl: Duration,
    ) -> BoxFuture<'a, Result<Option<LeaseToken>, StoreError>> {
        (**self).claim_queued_run(owner_id, pool_name, ttl)
    }
    fn reclaim_expired_run<'a>(
        &'a self,
        owner_id: &'a OwnerId,
        pool_name: &'a PoolName,
        ttl: Duration,
    ) -> BoxFuture<'a, Result<Option<LeaseToken>, StoreError>> {
        (**self).reclaim_expired_run(owner_id, pool_name, ttl)
    }
    fn renew_lease<'a>(
        &'a self,
        lease: &'a LeaseToken,
        ttl: Duration,
    ) -> BoxFuture<'a, Result<LeaseToken, StoreError>> {
        (**self).renew_lease(lease, ttl)
    }
    fn finish_run<'a>(
        &'a self,
        lease: &'a LeaseToken,
        status: TerminalRunStatus,
        summary_code: Option<&'a str>,
    ) -> BoxFuture<'a, Result<(), StoreError>> {
        (**self).finish_run(lease, status, summary_code)
    }
    fn recover_expired_run<'a>(
        &'a self,
        tenant_id: &'a TenantId,
        run_id: &'a RunId,
        new_owner_id: &'a OwnerId,
        ttl: Duration,
    ) -> BoxFuture<'a, Result<(LeaseToken, Vec<EffectRecord>), StoreError>> {
        (**self).recover_expired_run(tenant_id, run_id, new_owner_id, ttl)
    }
    fn force_recover_run<'a>(
        &'a self,
        tenant_id: &'a TenantId,
        run_id: &'a RunId,
        new_owner_id: &'a OwnerId,
        ttl: Duration,
    ) -> BoxFuture<'a, Result<LeaseToken, StoreError>> {
        (**self).force_recover_run(tenant_id, run_id, new_owner_id, ttl)
    }
}

impl<T: CommandStore + ?Sized> CommandStore for std::sync::Arc<T> {
    fn lookup_receipt<'a>(
        &'a self,
        tenant_id: &'a TenantId,
        session_id: &'a SessionId,
        command_id: &'a CommandId,
    ) -> BoxFuture<'a, Result<Option<CommandReceipt>, StoreError>> {
        (**self).lookup_receipt(tenant_id, session_id, command_id)
    }
    fn commit_step<'a>(
        &'a self,
        lease: &'a LeaseToken,
        commit: StepCommit,
    ) -> BoxFuture<'a, Result<StepCommitResult, StoreError>> {
        (**self).commit_step(lease, commit)
    }
    fn list_unknown_effects<'a>(
        &'a self,
        tenant_id: &'a TenantId,
        run_id: &'a RunId,
    ) -> BoxFuture<'a, Result<Vec<EffectRecord>, StoreError>> {
        (**self).list_unknown_effects(tenant_id, run_id)
    }

    fn list_claimed_effects<'a>(
        &'a self,
        tenant_id: &'a TenantId,
        run_id: &'a RunId,
    ) -> BoxFuture<'a, Result<Vec<EffectRecord>, StoreError>> {
        (**self).list_claimed_effects(tenant_id, run_id)
    }
}

impl<T: SessionStore + ?Sized> SessionStore for std::sync::Arc<T> {
    fn create_session<'a>(
        &'a self,
        tenant_id: &'a TenantId,
        session_id: &'a SessionId,
        parent_session_id: Option<&'a SessionId>,
    ) -> BoxFuture<'a, Result<StepCommitResult, StoreError>> {
        (**self).create_session(tenant_id, session_id, parent_session_id)
    }
    fn load_branch<'a>(
        &'a self,
        tenant_id: &'a TenantId,
        session_id: &'a SessionId,
        leaf: Option<&'a EntryId>,
    ) -> BoxFuture<'a, Result<LoadedBranch, StoreError>> {
        (**self).load_branch(tenant_id, session_id, leaf)
    }
}

impl<T: SpendStore + ?Sized> SpendStore for std::sync::Arc<T> {
    fn sum_spend_since<'a>(
        &'a self,
        tenant_id: &'a TenantId,
        since_ms: i64,
        billing_class: Option<BillingClass>,
    ) -> BoxFuture<'a, Result<MicroUsd, StoreError>> {
        (**self).sum_spend_since(tenant_id, since_ms, billing_class)
    }
    fn sum_run_spend<'a>(
        &'a self,
        tenant_id: &'a TenantId,
        run_id: &'a RunId,
    ) -> BoxFuture<'a, Result<MicroUsd, StoreError>> {
        (**self).sum_run_spend(tenant_id, run_id)
    }
}

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

    #[test]
    fn owner_id_and_pool_name_reject_empty_whitespace_and_nul() {
        assert_eq!(OwnerId::try_new(""), Err(InvalidIdError::Empty));
        assert_eq!(OwnerId::try_new(" \t\n "), Err(InvalidIdError::Empty));
        assert_eq!(
            OwnerId::try_new("worker\0id"),
            Err(InvalidIdError::ContainsNul)
        );
        assert_eq!(PoolName::try_new(""), Err(InvalidIdError::Empty));
        assert_eq!(
            PoolName::try_new("pool\0name"),
            Err(InvalidIdError::ContainsNul)
        );

        let owner = OwnerId::try_new("worker-1").unwrap();
        assert_eq!(owner.as_str(), "worker-1");
        let pool = PoolName::try_new("scanner-pool").unwrap();
        assert_eq!(pool.as_str(), "scanner-pool");

        assert!(serde_json::from_str::<OwnerId>("\"\"").is_err());
        assert!(serde_json::from_str::<PoolName>("\"   \"").is_err());
    }

    #[test]
    fn terminal_run_status_maps_only_terminal_statuses() {
        assert_eq!(
            TerminalRunStatus::Completed.as_run_status(),
            RunStatus::Completed
        );
        assert_eq!(TerminalRunStatus::Failed.as_run_status(), RunStatus::Failed);
        assert_eq!(
            TerminalRunStatus::Cancelled.as_run_status(),
            RunStatus::Cancelled
        );
        assert_eq!(TerminalRunStatus::Parked.as_run_status(), RunStatus::Parked);
    }
}