Skip to main content

zeph_memory/store/
mod.rs

1// SPDX-FileCopyrightText: 2026 Andrei G <bug-ops>
2// SPDX-License-Identifier: MIT OR Apache-2.0
3
4//! SQLite-backed relational store for all persistent agent data.
5//!
6//! [`DbStore`] (aliased as [`SqliteStore`]) wraps a [`zeph_db::DbPool`] and provides
7//! typed sub-store modules for every data domain:
8//!
9//! | Module | Contents |
10//! |--------|----------|
11//! | `messages` | Conversation messages, role strings, metadata |
12//! | `summaries` | Compression summaries per conversation |
13//! | `persona` | Long-lived user attributes ([`PersonaFactRow`]) |
14//! | `trajectory` | Goal trajectory entries ([`TrajectoryEntryRow`]) |
15//! | `memory_tree` | Hierarchical note consolidation tree ([`MemoryTreeRow`]) |
16//! | `session_digest` | Per-session digest records |
17//! | `experiments` | A/B experiment results and session summaries |
18//! | `corrections` | User-issued corrections stored for fine-tuning |
19//! | `graph_store` | Entity/edge adjacency tables for the knowledge graph |
20//! | `overflow` | Context-overflow handling metadata |
21//! | `preferences` | User preference key-value store |
22//! | `skills` | Skill metrics, usage, and version records |
23//! | `trust` | Skill trust scores by source |
24//! | `acp_sessions` | ACP protocol session events |
25//! | `mem_scenes` | Scene segmentation records |
26//! | `compression_guidelines` | LLM compression policy guidelines |
27//! | `admission_training` | A-MAC admission training data |
28//! | `channel_preferences` | Per-channel UX preferences (e.g. last active provider) |
29
30mod acp_sessions;
31pub mod admission_training;
32pub mod channel_preferences;
33pub mod compression_guidelines;
34pub mod corrections;
35pub mod experiments;
36pub mod graph_store;
37mod history;
38mod mem_scenes;
39pub mod memory_tree;
40pub(crate) mod messages;
41pub mod overflow;
42pub mod persona;
43pub mod preferences;
44pub mod session_digest;
45mod skills;
46mod summaries;
47pub mod trajectory;
48mod trust;
49
50#[allow(unused_imports)]
51use zeph_db::sql;
52use zeph_db::{DbConfig, DbPool};
53
54use crate::error::MemoryError;
55
56pub use acp_sessions::{AcpSessionEvent, AcpSessionInfo};
57pub use memory_tree::MemoryTreeRow;
58pub use messages::role_str;
59pub use persona::PersonaFactRow;
60pub use skills::{SkillMetricsRow, SkillUsageRow, SkillVersionRow};
61pub use trajectory::{NewTrajectoryEntry, TrajectoryEntryRow};
62pub use trust::{SkillTrustRow, SourceKind};
63
64/// Backward-compatible type alias. Prefer [`DbStore`] in new code.
65pub type SqliteStore = DbStore;
66
67/// Primary relational data store backed by a [`DbPool`].
68///
69/// Opening a `DbStore` runs all pending `SQLite` migrations automatically.
70///
71/// # Examples
72///
73/// ```rust,no_run
74/// # async fn example() -> Result<(), zeph_memory::MemoryError> {
75/// use zeph_memory::store::DbStore;
76///
77/// let store = DbStore::new(":memory:").await?;
78/// let cid = store.create_conversation().await?;
79/// # Ok(())
80/// # }
81/// ```
82#[derive(Debug, Clone)]
83pub struct DbStore {
84    pool: DbPool,
85}
86
87impl DbStore {
88    /// Open (or create) the database and run migrations.
89    ///
90    /// # Errors
91    ///
92    /// Returns an error if the database cannot be opened or migrations fail.
93    pub async fn new(path: &str) -> Result<Self, MemoryError> {
94        Self::with_pool_size(path, 5).await
95    }
96
97    /// Open (or create) the database with a configurable connection pool size.
98    ///
99    /// # Errors
100    ///
101    /// Returns an error if the database cannot be opened or migrations fail.
102    pub async fn with_pool_size(path: &str, pool_size: u32) -> Result<Self, MemoryError> {
103        let pool = DbConfig {
104            url: path.to_string(),
105            max_connections: pool_size,
106            pool_size,
107        }
108        .connect()
109        .await?;
110
111        Ok(Self { pool })
112    }
113
114    /// Expose the underlying pool for shared access by other stores.
115    #[must_use]
116    pub fn pool(&self) -> &DbPool {
117        &self.pool
118    }
119
120    /// Run all migrations on the given pool.
121    ///
122    /// # Errors
123    ///
124    /// Returns an error if any migration fails.
125    pub async fn run_migrations(pool: &DbPool) -> Result<(), MemoryError> {
126        zeph_db::run_migrations(pool).await?;
127        Ok(())
128    }
129}
130
131#[cfg(test)]
132mod tests {
133    use super::*;
134    use tempfile::NamedTempFile;
135
136    // Matches `DbConfig` busy_timeout default (5 seconds in ms)
137    const DEFAULT_BUSY_TIMEOUT_MS: i64 = 5_000;
138
139    #[tokio::test]
140    async fn wal_journal_mode_enabled_on_file_db() {
141        let file = NamedTempFile::new().expect("tempfile");
142        let path = file.path().to_str().expect("valid path");
143
144        let store = DbStore::new(path).await.expect("DbStore::new");
145
146        let mode: String = zeph_db::query_scalar(sql!("PRAGMA journal_mode"))
147            .fetch_one(store.pool())
148            .await
149            .expect("PRAGMA query");
150
151        assert_eq!(mode, "wal", "expected WAL journal mode, got: {mode}");
152    }
153
154    #[tokio::test]
155    async fn busy_timeout_enabled_on_file_db() {
156        let file = NamedTempFile::new().expect("tempfile");
157        let path = file.path().to_str().expect("valid path");
158
159        let store = DbStore::new(path).await.expect("DbStore::new");
160
161        let timeout_ms: i64 = zeph_db::query_scalar(sql!("PRAGMA busy_timeout"))
162            .fetch_one(store.pool())
163            .await
164            .expect("PRAGMA query");
165
166        assert_eq!(
167            timeout_ms, DEFAULT_BUSY_TIMEOUT_MS,
168            "expected busy_timeout pragma to match configured timeout"
169        );
170    }
171
172    #[tokio::test]
173    async fn creates_parent_dirs() {
174        let dir = tempfile::tempdir().expect("tempdir");
175        let deep = dir.path().join("a/b/c/zeph.db");
176        let path = deep.to_str().expect("valid path");
177        let _store = DbStore::new(path).await.expect("DbStore::new");
178        assert!(deep.exists(), "database file should exist");
179    }
180
181    #[tokio::test]
182    async fn with_pool_size_accepts_custom_size() {
183        let store = DbStore::with_pool_size(":memory:", 2)
184            .await
185            .expect("with_pool_size");
186        // Verify the store is operational with the custom pool size.
187        let _cid = store
188            .create_conversation()
189            .await
190            .expect("create_conversation");
191    }
192}