Skip to main content

kernex_memory/
memory_store.rs

1#![cfg_attr(test, allow(clippy::unwrap_used, clippy::expect_used))]
2
3//! Public trait surface for the SQLite-backed memory store.
4//!
5//! Mirrors the inherent method surface that downstream consumers
6//! (`kernex-runtime` composition, the sister-repo binary's REPL, future
7//! CLI/HTTP/MCP) call today, plus three new soft-delete methods on the
8//! `facts` table. Hard-delete inherent methods (`delete_fact`,
9//! `delete_facts`) stay on `Store` for emergency cleanup tooling and are
10//! deliberately NOT on the trait so the default consumer path uses
11//! recoverable soft-delete.
12//!
13//! `Runtime::store_handle()` returns `Arc<dyn MemoryStore>` so a binary
14//! consumer can share the runtime's composed `Store` instance instead of
15//! opening a second SQLite connection against the same database file.
16
17use std::sync::Arc;
18use std::time::SystemTime;
19
20use async_trait::async_trait;
21
22use crate::error::MemoryError;
23use crate::observation::{Observation, ObservationType, SaveEntry};
24use crate::store::{DueTask, Store, UsageSummary};
25use crate::types::{HistoryRow, MessageRow};
26
27/// Public trait surface over [`Store`].
28///
29/// Returned from `kernex-runtime::Runtime::store_handle()` as
30/// `Arc<dyn MemoryStore>`. Consumers should prefer this trait over the
31/// concrete `Store` type so future schema changes do not ripple into call
32/// sites.
33#[async_trait]
34pub trait MemoryStore: Send + Sync {
35    // --- conversations / messages ---
36
37    /// Mark the active conversation for `(channel, sender_id, project)` as
38    /// closed. Returns `true` if a row transitioned from active to closed.
39    async fn close_current_conversation(
40        &self,
41        channel: &str,
42        sender_id: &str,
43        project: &str,
44    ) -> Result<bool, MemoryError>;
45
46    /// Aggregate counters:
47    /// `(conversation_count, message_count, observation_count, fact_count)`.
48    ///
49    /// **Breaking change (kernex-memory 0.8.0):** prior versions returned
50    /// a 3-tuple `(conversation, message, fact)`. The observation count
51    /// joins the tuple at position 2; consumers must destructure four
52    /// elements after the bump. Soft-deleted observations and facts are
53    /// excluded; conversations and messages have no soft-delete column
54    /// today and are counted whole.
55    async fn get_memory_stats(&self, sender_id: &str) -> Result<(i64, i64, i64, i64), MemoryError>;
56
57    /// On-disk byte size of the SQLite database file.
58    async fn db_size(&self) -> Result<u64, MemoryError>;
59
60    /// Aggregate token usage across all sessions.
61    async fn get_total_usage(&self) -> Result<UsageSummary, MemoryError>;
62
63    /// Recent closed-conversation summaries for a given channel + sender,
64    /// newest first, capped at `limit`.
65    async fn get_history(
66        &self,
67        channel: &str,
68        sender_id: &str,
69        limit: i64,
70    ) -> Result<Vec<HistoryRow>, MemoryError>;
71
72    /// FTS5 full-text search over user messages, excluding the live
73    /// conversation. When `since` is `Some`, only rows with
74    /// `timestamp >= since` are returned and `limit` applies after the
75    /// recency filter.
76    async fn search_messages(
77        &self,
78        query: &str,
79        exclude_conversation_id: &str,
80        sender_id: &str,
81        limit: i64,
82        since: Option<SystemTime>,
83    ) -> Result<Vec<MessageRow>, MemoryError>;
84
85    /// Fetch a single message row by its UUID. Returns `None` when the
86    /// id is missing.
87    async fn get_message_by_id(&self, id: &str) -> Result<Option<MessageRow>, MemoryError>;
88
89    // --- facts (write paths plus soft-only delete on the trait) ---
90
91    /// Upsert a fact for `(sender_id, key)`. If the row was previously
92    /// soft-deleted, this clears `deleted_at` so the value is visible
93    /// again to default-filtered reads.
94    async fn store_fact(&self, sender_id: &str, key: &str, value: &str) -> Result<(), MemoryError>;
95
96    /// Read a single active fact by `(sender_id, key)`. Returns `None` if
97    /// the row is soft-deleted, missing, or never existed.
98    async fn get_fact(&self, sender_id: &str, key: &str) -> Result<Option<String>, MemoryError>;
99
100    /// Active (not soft-deleted) facts for `sender_id`.
101    async fn get_facts(&self, sender_id: &str) -> Result<Vec<(String, String)>, MemoryError>;
102
103    /// Soft-delete a single fact by setting its `deleted_at` timestamp.
104    /// Returns `true` if a row transitioned from active to deleted; `false`
105    /// if the row was already deleted, missing, or never existed.
106    async fn soft_delete_fact(&self, sender_id: &str, key: &str) -> Result<bool, MemoryError>;
107
108    /// Soft-delete multiple facts. With `Some(key)`, soft-deletes that
109    /// specific key. With `None`, soft-deletes every active fact for the
110    /// sender. Returns the count of rows that transitioned from active to
111    /// deleted.
112    async fn soft_delete_facts(
113        &self,
114        sender_id: &str,
115        key: Option<&str>,
116    ) -> Result<u64, MemoryError>;
117
118    /// Read soft-deleted facts (debug / recovery helper). Returns
119    /// `(key, value, deleted_at)` rows for `sender_id`.
120    async fn list_soft_deleted_facts(
121        &self,
122        sender_id: &str,
123    ) -> Result<Vec<(String, String, String)>, MemoryError>;
124
125    // --- observations (typed write surface introduced in 0.8.0) ---
126
127    /// Persist a typed observation and return the saved row. Generates
128    /// a fresh UUIDv4 id; sets `created_at == updated_at == now`. The
129    /// DB enforces `length(title) > 0` and the seven-value `type` CHECK
130    /// constraint; violations surface as `MemoryError::Sqlite`.
131    async fn save_observation(&self, entry: SaveEntry) -> Result<Observation, MemoryError>;
132
133    /// Fetch an active observation by id. Returns `None` when the id is
134    /// missing OR the row is soft-deleted (CC-9 invariant). Mirrors the
135    /// `get_message_by_id` shape introduced in 0.7.0.
136    async fn get_observation_by_id(&self, id: &str) -> Result<Option<Observation>, MemoryError>;
137
138    /// FTS5 search across observation title + structured fields.
139    /// Optional `since` filters by `created_at >=`; optional `kind`
140    /// narrows to a single type. Soft-deleted rows never appear.
141    async fn search_observations(
142        &self,
143        query: &str,
144        sender_id: &str,
145        limit: i64,
146        since: Option<SystemTime>,
147        kind: Option<ObservationType>,
148    ) -> Result<Vec<Observation>, MemoryError>;
149
150    /// Soft-delete an observation by id. Returns `Ok(true)` on
151    /// transition from active to deleted; `Ok(false)` when the row was
152    /// already deleted, missing, or never existed (matches the
153    /// `soft_delete_fact` contract).
154    async fn soft_delete_observation(&self, id: &str) -> Result<bool, MemoryError>;
155
156    /// Read soft-deleted observations for a sender. Recovery helper;
157    /// surfaced on the trait so future tooling can offer an "undelete"
158    /// command without dropping back to the inherent `Store`.
159    async fn list_soft_deleted_observations(
160        &self,
161        sender_id: &str,
162    ) -> Result<Vec<Observation>, MemoryError>;
163
164    // --- scheduled tasks ---
165
166    /// Insert a new scheduled task. Returns the new task id.
167    #[allow(clippy::too_many_arguments)]
168    async fn create_task(
169        &self,
170        channel: &str,
171        sender_id: &str,
172        reply_target: &str,
173        description: &str,
174        due_at: &str,
175        repeat: Option<&str>,
176        task_type: &str,
177        project: &str,
178    ) -> Result<String, MemoryError>;
179
180    /// Pending tasks for `sender_id` as raw `(id, description, due_at,
181    /// repeat, task_type, project)` rows, ordered by `due_at` ascending.
182    async fn get_tasks_for_sender(
183        &self,
184        sender_id: &str,
185    ) -> Result<Vec<(String, String, String, Option<String>, String, String)>, MemoryError>;
186
187    /// Mark a task as completed. With `Some("daily")` / `Some("weekly")` /
188    /// etc., reschedules the next occurrence; with `None` or `Some("once")`,
189    /// the task transitions to a terminal status.
190    async fn complete_task(&self, id: &str, repeat: Option<&str>) -> Result<(), MemoryError>;
191
192    /// Record a task failure. Increments retry counter; transitions to a
193    /// terminal failed status when retries exhaust. Returns `true` if the
194    /// task transitioned to a terminal state.
195    async fn fail_task(&self, id: &str, error: &str, max_retries: u32)
196        -> Result<bool, MemoryError>;
197
198    /// Cancel a pending task whose id starts with `id_prefix`, scoped to
199    /// `sender_id`. Returns `true` if a row was cancelled.
200    async fn cancel_task(&self, id_prefix: &str, sender_id: &str) -> Result<bool, MemoryError>;
201
202    /// All pending tasks whose `due_at` is in the past.
203    async fn get_due_tasks(&self) -> Result<Vec<DueTask>, MemoryError>;
204}
205
206#[async_trait]
207impl MemoryStore for Store {
208    async fn close_current_conversation(
209        &self,
210        channel: &str,
211        sender_id: &str,
212        project: &str,
213    ) -> Result<bool, MemoryError> {
214        Store::close_current_conversation(self, channel, sender_id, project).await
215    }
216
217    async fn get_memory_stats(&self, sender_id: &str) -> Result<(i64, i64, i64, i64), MemoryError> {
218        Store::get_memory_stats(self, sender_id).await
219    }
220
221    async fn db_size(&self) -> Result<u64, MemoryError> {
222        Store::db_size(self).await
223    }
224
225    async fn get_total_usage(&self) -> Result<UsageSummary, MemoryError> {
226        Store::get_total_usage(self).await
227    }
228
229    async fn get_history(
230        &self,
231        channel: &str,
232        sender_id: &str,
233        limit: i64,
234    ) -> Result<Vec<HistoryRow>, MemoryError> {
235        Store::get_history(self, channel, sender_id, limit).await
236    }
237
238    async fn search_messages(
239        &self,
240        query: &str,
241        exclude_conversation_id: &str,
242        sender_id: &str,
243        limit: i64,
244        since: Option<SystemTime>,
245    ) -> Result<Vec<MessageRow>, MemoryError> {
246        Store::search_messages(
247            self,
248            query,
249            exclude_conversation_id,
250            sender_id,
251            limit,
252            since,
253        )
254        .await
255    }
256
257    async fn get_message_by_id(&self, id: &str) -> Result<Option<MessageRow>, MemoryError> {
258        Store::get_message_by_id(self, id).await
259    }
260
261    async fn store_fact(&self, sender_id: &str, key: &str, value: &str) -> Result<(), MemoryError> {
262        Store::store_fact(self, sender_id, key, value).await
263    }
264
265    async fn get_fact(&self, sender_id: &str, key: &str) -> Result<Option<String>, MemoryError> {
266        Store::get_fact(self, sender_id, key).await
267    }
268
269    async fn get_facts(&self, sender_id: &str) -> Result<Vec<(String, String)>, MemoryError> {
270        Store::get_facts(self, sender_id).await
271    }
272
273    async fn soft_delete_fact(&self, sender_id: &str, key: &str) -> Result<bool, MemoryError> {
274        Store::soft_delete_fact(self, sender_id, key).await
275    }
276
277    async fn soft_delete_facts(
278        &self,
279        sender_id: &str,
280        key: Option<&str>,
281    ) -> Result<u64, MemoryError> {
282        Store::soft_delete_facts(self, sender_id, key).await
283    }
284
285    async fn list_soft_deleted_facts(
286        &self,
287        sender_id: &str,
288    ) -> Result<Vec<(String, String, String)>, MemoryError> {
289        Store::list_soft_deleted_facts(self, sender_id).await
290    }
291
292    async fn save_observation(&self, entry: SaveEntry) -> Result<Observation, MemoryError> {
293        Store::save_observation(self, entry).await
294    }
295
296    async fn get_observation_by_id(&self, id: &str) -> Result<Option<Observation>, MemoryError> {
297        Store::get_observation_by_id(self, id).await
298    }
299
300    async fn search_observations(
301        &self,
302        query: &str,
303        sender_id: &str,
304        limit: i64,
305        since: Option<SystemTime>,
306        kind: Option<ObservationType>,
307    ) -> Result<Vec<Observation>, MemoryError> {
308        Store::search_observations(self, query, sender_id, limit, since, kind).await
309    }
310
311    async fn soft_delete_observation(&self, id: &str) -> Result<bool, MemoryError> {
312        Store::soft_delete_observation(self, id).await
313    }
314
315    async fn list_soft_deleted_observations(
316        &self,
317        sender_id: &str,
318    ) -> Result<Vec<Observation>, MemoryError> {
319        Store::list_soft_deleted_observations(self, sender_id).await
320    }
321
322    async fn create_task(
323        &self,
324        channel: &str,
325        sender_id: &str,
326        reply_target: &str,
327        description: &str,
328        due_at: &str,
329        repeat: Option<&str>,
330        task_type: &str,
331        project: &str,
332    ) -> Result<String, MemoryError> {
333        Store::create_task(
334            self,
335            channel,
336            sender_id,
337            reply_target,
338            description,
339            due_at,
340            repeat,
341            task_type,
342            project,
343        )
344        .await
345    }
346
347    async fn get_tasks_for_sender(
348        &self,
349        sender_id: &str,
350    ) -> Result<Vec<(String, String, String, Option<String>, String, String)>, MemoryError> {
351        Store::get_tasks_for_sender(self, sender_id).await
352    }
353
354    async fn complete_task(&self, id: &str, repeat: Option<&str>) -> Result<(), MemoryError> {
355        Store::complete_task(self, id, repeat).await
356    }
357
358    async fn fail_task(
359        &self,
360        id: &str,
361        error: &str,
362        max_retries: u32,
363    ) -> Result<bool, MemoryError> {
364        Store::fail_task(self, id, error, max_retries).await
365    }
366
367    async fn cancel_task(&self, id_prefix: &str, sender_id: &str) -> Result<bool, MemoryError> {
368        Store::cancel_task(self, id_prefix, sender_id).await
369    }
370
371    async fn get_due_tasks(&self) -> Result<Vec<DueTask>, MemoryError> {
372        Store::get_due_tasks(self).await
373    }
374}
375
376/// Expose a [`Store`] through the [`MemoryStore`] trait surface.
377///
378/// `Store` already implements `Clone` (its `SqlitePool` is internally
379/// reference-counted); cloning here shares the same connection pool.
380pub fn into_handle(store: Store) -> Arc<dyn MemoryStore> {
381    Arc::new(store)
382}