Skip to main content

nenjo_tools/
memory.rs

1use async_trait::async_trait;
2use serde::{Deserialize, Serialize};
3
4// ── Layer types (from layers.rs) ──────────────────────────────────
5
6/// Which layer of the memory hierarchy a piece of data belongs to.
7#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8pub enum MemoryLayer {
9    /// Raw immutable conversation/event logs.
10    Resource,
11    /// Extracted atomic facts with embeddings.
12    Item,
13    /// Evolving category summaries.
14    Summary,
15}
16
17/// Lifecycle status of a memory item.
18#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
19#[serde(rename_all = "lowercase")]
20#[derive(Default)]
21pub enum MemoryItemStatus {
22    /// Live, searchable fact.
23    #[default]
24    Active,
25    /// Replaced by a newer, more accurate fact.
26    Superseded,
27    /// Preserved but excluded from search results.
28    Archived,
29    /// Extracted but not yet validated.
30    Unverified,
31}
32
33impl MemoryItemStatus {
34    pub fn as_str(&self) -> &'static str {
35        match self {
36            Self::Active => "active",
37            Self::Superseded => "superseded",
38            Self::Archived => "archived",
39            Self::Unverified => "unverified",
40        }
41    }
42
43    #[allow(clippy::should_implement_trait)]
44    pub fn from_str(s: &str) -> Self {
45        match s {
46            "active" => Self::Active,
47            "superseded" => Self::Superseded,
48            "archived" => Self::Archived,
49            "unverified" => Self::Unverified,
50            _ => Self::Active,
51        }
52    }
53}
54
55/// Filters for the `search_items_filtered` method.
56#[derive(Debug, Clone, Default)]
57pub struct SearchFilters {
58    pub category: Option<String>,
59    pub min_confidence: Option<f32>,
60    pub max_age_days: Option<u32>,
61    pub status: Option<String>,
62}
63
64/// An edge between two memory items.
65#[derive(Debug, Clone, Serialize, Deserialize)]
66pub struct MemoryRelation {
67    pub id: String,
68    pub source_id: String,
69    pub target_id: String,
70    pub relation: String, // "supersedes", "depends_on", "related_to", "contradicts"
71    pub created_at: String,
72}
73
74/// Layer 1: Raw immutable conversation log / event record.
75#[derive(Debug, Clone, Serialize, Deserialize)]
76pub struct MemoryResource {
77    pub id: String,
78    pub namespace: String,
79    pub resource_type: String,
80    pub content: String,
81    pub metadata: serde_json::Value,
82    pub created_at: String,
83}
84
85/// Layer 2: Extracted atomic fact with optional embedding.
86#[derive(Debug, Clone, Serialize, Deserialize)]
87pub struct MemoryItem {
88    pub id: String,
89    pub namespace: String,
90    pub fact: String,
91    pub category: String,
92    pub confidence: f32,
93    #[serde(default)]
94    pub status: MemoryItemStatus,
95    pub source_resource_id: Option<String>,
96    pub access_count: u32,
97    pub last_accessed_at: String,
98    pub created_at: String,
99    pub updated_at: String,
100    /// Set during search — hybrid relevance score (FTS5 BM25 + vector cosine).
101    #[serde(skip_serializing_if = "Option::is_none")]
102    pub score: Option<f64>,
103}
104
105/// Layer 3: Evolving category summary, rebuilt as items change.
106#[derive(Debug, Clone, Serialize, Deserialize)]
107pub struct MemorySummary {
108    pub id: String,
109    pub namespace: String,
110    pub category: String,
111    pub summary_text: String,
112    pub item_count: u32,
113    pub version: u32,
114    pub created_at: String,
115    pub updated_at: String,
116}
117
118// ── AgentMemory trait (from traits.rs) ────────────────────────────
119
120/// Namespace-aware, three-layer memory backend.
121///
122/// All operations are scoped by namespace (`ns` parameter) to isolate
123/// per-role and per-project memory. The three layers are:
124///
125/// - **Resource** (Layer 1): Raw immutable conversation/event logs.
126/// - **Item** (Layer 2): Extracted atomic facts with embeddings.
127/// - **Summary** (Layer 3): Evolving category summaries.
128#[async_trait]
129pub trait AgentMemory: Send + Sync {
130    /// Backend name (e.g. "sqlite", "none").
131    fn name(&self) -> &str;
132
133    // ── Resource layer (raw immutable logs) ─────────────────────
134
135    /// Store a raw resource (conversation log, event record).
136    /// Returns the generated resource ID.
137    async fn store_resource(
138        &self,
139        ns: &str,
140        resource_type: &str,
141        content: &str,
142        metadata: serde_json::Value,
143    ) -> anyhow::Result<String>;
144
145    /// List resources in a namespace, optionally filtered by type.
146    async fn list_resources(
147        &self,
148        ns: &str,
149        resource_type: Option<&str>,
150        limit: usize,
151    ) -> anyhow::Result<Vec<MemoryResource>>;
152
153    // ── Item layer (extracted atomic facts) ─────────────────────
154
155    /// Store an extracted fact. Returns the generated item ID.
156    async fn store_item(
157        &self,
158        ns: &str,
159        fact: &str,
160        category: &str,
161        confidence: f32,
162        source_resource_id: Option<&str>,
163    ) -> anyhow::Result<String>;
164
165    /// Hybrid search items (FTS5 BM25 + vector cosine) scoped to namespace.
166    async fn search_items(
167        &self,
168        ns: &str,
169        query: &str,
170        limit: usize,
171    ) -> anyhow::Result<Vec<MemoryItem>>;
172
173    /// List all items in a category within a namespace.
174    async fn list_items_by_category(
175        &self,
176        ns: &str,
177        category: &str,
178    ) -> anyhow::Result<Vec<MemoryItem>>;
179
180    /// Bump access_count and last_accessed_at for an item.
181    async fn touch_item(&self, id: &str) -> anyhow::Result<()>;
182
183    /// Delete an item by ID. Returns true if found and deleted.
184    async fn delete_item(&self, id: &str) -> anyhow::Result<bool>;
185
186    /// Delete items older than `older_than_days` with access_count < `min_access`.
187    /// Returns the number of items deleted.
188    async fn delete_stale_items(
189        &self,
190        ns: &str,
191        older_than_days: u32,
192        min_access: u32,
193    ) -> anyhow::Result<u64>;
194
195    // ── Status lifecycle ─────────────────────────────────────────
196
197    /// Update the status of a memory item (active, superseded, archived, unverified).
198    async fn update_item_status(&self, _id: &str, _status: &str) -> anyhow::Result<bool> {
199        Ok(false)
200    }
201
202    /// Update the confidence score of a memory item (used for dedup merge + decay).
203    async fn update_item_confidence(&self, _id: &str, _confidence: f32) -> anyhow::Result<bool> {
204        Ok(false)
205    }
206
207    // ── Dedup ────────────────────────────────────────────────────
208
209    /// Find items similar to a given fact text using vector similarity.
210    /// Returns items with cosine similarity above `threshold`.
211    async fn find_similar_items(
212        &self,
213        _ns: &str,
214        _fact: &str,
215        _threshold: f32,
216        _limit: usize,
217    ) -> anyhow::Result<Vec<MemoryItem>> {
218        Ok(vec![])
219    }
220
221    // ── Decay ────────────────────────────────────────────────────
222
223    /// Decay confidence of items not accessed in `older_than_hours` by `factor`.
224    /// Returns the number of items decayed.
225    async fn decay_confidence(
226        &self,
227        _ns: &str,
228        _older_than_hours: u32,
229        _factor: f32,
230    ) -> anyhow::Result<u64> {
231        Ok(0)
232    }
233
234    // ── Filtered search ──────────────────────────────────────────
235
236    /// Search items with additional filters (category, confidence, age, status).
237    async fn search_items_filtered(
238        &self,
239        ns: &str,
240        query: &str,
241        limit: usize,
242        _filters: &SearchFilters,
243    ) -> anyhow::Result<Vec<MemoryItem>> {
244        self.search_items(ns, query, limit).await
245    }
246
247    // ── Relations ────────────────────────────────────────────────
248
249    /// Create a relation between two memory items. Returns the relation ID.
250    async fn add_relation(
251        &self,
252        _source_id: &str,
253        _target_id: &str,
254        _relation: &str,
255    ) -> anyhow::Result<String> {
256        Ok(String::new())
257    }
258
259    /// Get all relations for a memory item (as source or target).
260    async fn get_relations(&self, _item_id: &str) -> anyhow::Result<Vec<MemoryRelation>> {
261        Ok(vec![])
262    }
263
264    /// Get items related to a given item, traversing through relations.
265    async fn get_related_items(
266        &self,
267        _item_id: &str,
268        _limit: usize,
269    ) -> anyhow::Result<Vec<MemoryItem>> {
270        Ok(vec![])
271    }
272
273    // ── Summary layer (evolving category summaries) ─────────────
274
275    /// Get the current summary for a category in a namespace.
276    async fn get_summary(&self, ns: &str, category: &str) -> anyhow::Result<Option<MemorySummary>>;
277
278    /// Delete a category summary. Returns true if found and deleted.
279    async fn delete_summary(&self, _ns: &str, _category: &str) -> anyhow::Result<bool> {
280        Ok(false)
281    }
282
283    /// Insert or update a category summary.
284    async fn upsert_summary(
285        &self,
286        ns: &str,
287        category: &str,
288        text: &str,
289        item_count: u32,
290    ) -> anyhow::Result<()>;
291
292    /// List all summaries in a namespace.
293    async fn list_summaries(&self, ns: &str) -> anyhow::Result<Vec<MemorySummary>>;
294
295    // ── Maintenance ─────────────────────────────────────────────
296
297    /// List all distinct namespaces that have data.
298    async fn list_all_namespaces(&self) -> anyhow::Result<Vec<String>>;
299
300    /// Count total items in a namespace.
301    async fn count_items(&self, ns: &str) -> anyhow::Result<usize>;
302
303    /// Count items grouped by category in a namespace.
304    async fn count_items_by_category(&self, _ns: &str) -> anyhow::Result<Vec<(String, usize)>> {
305        Ok(vec![])
306    }
307
308    /// Quick health check (e.g. `SELECT 1`).
309    async fn health_check(&self) -> bool;
310}
311
312#[cfg(test)]
313mod tests {
314    use super::*;
315
316    /// Verify the trait is object-safe (can be used as `dyn AgentMemory`).
317    #[allow(dead_code)]
318    fn assert_object_safe(_: &dyn AgentMemory) {}
319
320    #[test]
321    fn memory_item_status_roundtrip() {
322        for status in [
323            MemoryItemStatus::Active,
324            MemoryItemStatus::Superseded,
325            MemoryItemStatus::Archived,
326            MemoryItemStatus::Unverified,
327        ] {
328            let json = serde_json::to_string(&status).unwrap();
329            let parsed: MemoryItemStatus = serde_json::from_str(&json).unwrap();
330            assert_eq!(parsed, status);
331        }
332    }
333
334    #[test]
335    fn memory_item_status_from_str() {
336        assert_eq!(
337            MemoryItemStatus::from_str("active"),
338            MemoryItemStatus::Active
339        );
340        assert_eq!(
341            MemoryItemStatus::from_str("superseded"),
342            MemoryItemStatus::Superseded
343        );
344        assert_eq!(
345            MemoryItemStatus::from_str("unknown"),
346            MemoryItemStatus::Active
347        );
348    }
349
350    #[test]
351    fn memory_item_status_default() {
352        assert_eq!(MemoryItemStatus::default(), MemoryItemStatus::Active);
353    }
354}