do-memory-core 0.1.31

Core episodic learning system for AI agents with pattern extraction, reward scoring, and dual storage backend
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
//! # Storage Abstraction
//!
//! Unified trait for storage backends (Turso, redb, etc.)
//!
//! This allows the memory system to work with different storage implementations
//! transparently, supporting both durable (Turso) and cache (redb) layers.

pub mod circuit_breaker;

use crate::episode::{
    CleanupResult, Direction, EpisodeRelationship, EpisodeRetentionPolicy, PatternId,
    RelationshipType,
};
use crate::memory::attribution::{
    RecommendationFeedback, RecommendationSession, RecommendationStats,
};
use crate::{Episode, Heuristic, Pattern, Result};
use async_trait::async_trait;
use uuid::Uuid;

/// Default limit for query operations (when not specified)
pub const DEFAULT_QUERY_LIMIT: usize = 100;

/// Maximum limit for query operations (prevents OOM)
pub const MAX_QUERY_LIMIT: usize = 1000;

/// Apply limit with defaults and bounds checking.
///
/// - If `limit` is None, returns the default limit (100)
/// - If `limit` is Some, clamps it to the maximum (1000)
#[must_use]
#[inline]
pub fn apply_query_limit(limit: Option<usize>) -> usize {
    match limit {
        Some(l) => l.min(MAX_QUERY_LIMIT),
        None => DEFAULT_QUERY_LIMIT,
    }
}

/// Unified storage backend trait
///
/// Provides a common interface for different storage implementations.
/// All operations are async to support both async (Turso) and sync (redb via `spawn_blocking`).
#[async_trait]
pub trait StorageBackend: Send + Sync {
    /// Store an episode
    ///
    /// # Arguments
    ///
    /// * `episode` - Episode to store
    ///
    /// # Errors
    ///
    /// Returns error if storage operation fails
    async fn store_episode(&self, episode: &Episode) -> Result<()>;

    /// Retrieve an episode by ID
    ///
    /// # Arguments
    ///
    /// * `id` - Episode UUID
    ///
    /// # Returns
    ///
    /// `Some(Episode)` if found, `None` if not found
    ///
    /// # Errors
    ///
    /// Returns error if storage operation fails
    async fn get_episode(&self, id: Uuid) -> Result<Option<Episode>>;

    /// Delete an episode by ID
    ///
    /// # Arguments
    ///
    /// * `id` - Episode UUID
    ///
    /// # Errors
    ///
    /// Returns error if storage operation fails
    async fn delete_episode(&self, id: Uuid) -> Result<()>;

    /// Store a pattern
    ///
    /// # Arguments
    ///
    /// * `pattern` - Pattern to store
    ///
    /// # Errors
    ///
    /// Returns error if storage operation fails
    async fn store_pattern(&self, pattern: &Pattern) -> Result<()>;

    /// Retrieve a pattern by ID
    ///
    /// # Arguments
    ///
    /// * `id` - Pattern ID
    ///
    /// # Returns
    ///
    /// `Some(Pattern)` if found, `None` if not found
    ///
    /// # Errors
    ///
    /// Returns error if storage operation fails
    async fn get_pattern(&self, id: PatternId) -> Result<Option<Pattern>>;

    /// Store a heuristic
    ///
    /// # Arguments
    ///
    /// * `heuristic` - Heuristic to store
    ///
    /// # Errors
    ///
    /// Returns error if storage operation fails
    async fn store_heuristic(&self, heuristic: &Heuristic) -> Result<()>;

    /// Retrieve a heuristic by ID
    ///
    /// # Arguments
    ///
    /// * `id` - Heuristic UUID
    ///
    /// # Returns
    ///
    /// `Some(Heuristic)` if found, `None` if not found
    ///
    /// # Errors
    ///
    /// Returns error if storage operation fails
    async fn get_heuristic(&self, id: Uuid) -> Result<Option<Heuristic>>;

    /// Query episodes modified since a given timestamp
    ///
    /// Used for incremental synchronization between storage layers.
    ///
    /// # Arguments
    ///
    /// * `since` - Timestamp to query from
    /// * `limit` - Maximum number of episodes to return (default: 100, max: 1000)
    ///
    /// # Returns
    ///
    /// Vector of episodes with `start_time` >= since
    ///
    /// # Errors
    ///
    /// Returns error if storage operation fails
    async fn query_episodes_since(
        &self,
        since: chrono::DateTime<chrono::Utc>,
        limit: Option<usize>,
    ) -> Result<Vec<Episode>>;

    /// Query episodes by metadata key-value pair
    ///
    /// Used for specialized queries like monitoring data retrieval.
    ///
    /// # Arguments
    ///
    /// * `key` - Metadata key to search for
    /// * `value` - Metadata value to match
    /// * `limit` - Maximum number of episodes to return (default: 100, max: 1000)
    ///
    /// # Returns
    ///
    /// Vector of episodes matching the metadata criteria
    ///
    /// # Errors
    ///
    /// Returns error if storage operation fails
    async fn query_episodes_by_metadata(
        &self,
        key: &str,
        value: &str,
        limit: Option<usize>,
    ) -> Result<Vec<Episode>>;

    // ========== Embedding Storage Methods ==========

    /// Store embedding for an episode or pattern
    ///
    /// # Arguments
    ///
    /// * `id` - Unique identifier for the embedding (e.g., `episode_id` or `pattern_id`)
    /// * `embedding` - Vector of f32 values representing the embedding
    ///
    /// # Errors
    ///
    /// Returns error if storage operation fails
    async fn store_embedding(&self, id: &str, embedding: Vec<f32>) -> Result<()>;

    /// Retrieve embedding by ID
    ///
    /// # Arguments
    ///
    /// * `id` - Unique identifier for the embedding
    ///
    /// # Returns
    ///
    /// `Some(Vec<f32>)` if found, `None` if not found
    ///
    /// # Errors
    ///
    /// Returns error if storage operation fails
    async fn get_embedding(&self, id: &str) -> Result<Option<Vec<f32>>>;

    /// Delete embedding by ID
    ///
    /// # Arguments
    ///
    /// * `id` - Unique identifier for the embedding
    ///
    /// # Returns
    ///
    /// `true` if deleted, `false` if not found
    ///
    /// # Errors
    ///
    /// Returns error if storage operation fails
    async fn delete_embedding(&self, id: &str) -> Result<bool>;

    /// Store multiple embeddings in batch
    ///
    /// # Arguments
    ///
    /// * `embeddings` - Vector of (id, embedding) tuples
    ///
    /// # Errors
    ///
    /// Returns error if any storage operation fails
    async fn store_embeddings_batch(&self, embeddings: Vec<(String, Vec<f32>)>) -> Result<()>;

    /// Get embeddings for multiple IDs
    ///
    /// # Arguments
    ///
    /// * `ids` - Vector of embedding IDs
    ///
    /// # Returns
    ///
    /// Vector of `Option<Vec<f32>>` corresponding to each ID (None if not found)
    ///
    /// # Errors
    ///
    /// Returns error if storage operation fails
    async fn get_embeddings_batch(&self, ids: &[String]) -> Result<Vec<Option<Vec<f32>>>>;

    // ========== Relationship Storage Methods ==========

    /// Store a relationship between two episodes
    ///
    /// # Arguments
    ///
    /// * `relationship` - The relationship to store
    ///
    /// # Errors
    ///
    /// Returns error if storage operation fails
    async fn store_relationship(&self, relationship: &EpisodeRelationship) -> Result<()> {
        let _ = relationship;
        Ok(())
    }

    /// Remove a relationship by ID
    ///
    /// # Arguments
    ///
    /// * `relationship_id` - The UUID of the relationship to remove
    ///
    /// # Errors
    ///
    /// Returns error if storage operation fails
    async fn remove_relationship(&self, relationship_id: Uuid) -> Result<()> {
        let _ = relationship_id;
        Ok(())
    }

    /// Get relationships for an episode
    ///
    /// # Arguments
    ///
    /// * `episode_id` - The episode to query
    /// * `direction` - Which relationships to return (Outgoing, Incoming, or Both)
    ///
    /// # Returns
    ///
    /// Vector of relationships matching the query
    ///
    /// # Errors
    ///
    /// Returns error if storage operation fails
    async fn get_relationships(
        &self,
        episode_id: Uuid,
        direction: Direction,
    ) -> Result<Vec<EpisodeRelationship>> {
        let _ = (episode_id, direction);
        Ok(Vec::new())
    }

    /// Check if a relationship exists
    ///
    /// # Arguments
    ///
    /// * `from_episode_id` - Source episode
    /// * `to_episode_id` - Target episode  
    /// * `relationship_type` - Type of relationship
    ///
    /// # Returns
    ///
    /// `true` if the relationship exists
    ///
    /// # Errors
    ///
    /// Returns error if storage operation fails
    async fn relationship_exists(
        &self,
        from_episode_id: Uuid,
        to_episode_id: Uuid,
        relationship_type: RelationshipType,
    ) -> Result<bool> {
        let _ = (from_episode_id, to_episode_id, relationship_type);
        Ok(false)
    }

    // ========== Recommendation Attribution (ADR-044) ==========

    /// Persist a recommendation session for durability and analytics.
    async fn store_recommendation_session(&self, session: &RecommendationSession) -> Result<()> {
        let _ = session;
        Ok(())
    }

    /// Retrieve a recommendation session by ID.
    async fn get_recommendation_session(
        &self,
        session_id: Uuid,
    ) -> Result<Option<RecommendationSession>> {
        let _ = session_id;
        Ok(None)
    }

    /// Retrieve the most recent recommendation session for an episode.
    async fn get_recommendation_session_for_episode(
        &self,
        episode_id: Uuid,
    ) -> Result<Option<RecommendationSession>> {
        let _ = episode_id;
        Ok(None)
    }

    /// Persist feedback associated with a recommendation session.
    async fn store_recommendation_feedback(&self, feedback: &RecommendationFeedback) -> Result<()> {
        let _ = feedback;
        Ok(())
    }

    /// Retrieve feedback for a recommendation session.
    async fn get_recommendation_feedback(
        &self,
        session_id: Uuid,
    ) -> Result<Option<RecommendationFeedback>> {
        let _ = session_id;
        Ok(None)
    }

    /// Compute global recommendation statistics.
    async fn get_recommendation_stats(&self) -> Result<RecommendationStats> {
        Ok(RecommendationStats::default())
    }

    // ========== Episode GC/TTL (WG-075) ==========

    /// Clean up expired episodes based on retention policy
    ///
    /// Implements garbage collection for episodes that exceed age limits,
    /// have low reward scores, or are unreferenced by patterns/heuristics.
    ///
    /// # Arguments
    ///
    /// * `policy` - Retention policy specifying cleanup criteria
    ///
    /// # Returns
    ///
    /// `CleanupResult` with count of deleted episodes and any errors
    ///
    /// # Errors
    ///
    /// Returns error if storage operation fails
    async fn cleanup_episodes(&self, policy: &EpisodeRetentionPolicy) -> Result<CleanupResult> {
        let _ = policy;
        Ok(CleanupResult::new())
    }

    /// Get count of episodes that would be cleaned up (dry run)
    ///
    /// Useful for monitoring and pre-cleanup analysis.
    ///
    /// # Arguments
    ///
    /// * `policy` - Retention policy specifying cleanup criteria
    ///
    /// # Returns
    ///
    /// Number of episodes eligible for cleanup
    ///
    /// # Errors
    ///
    /// Returns error if storage operation fails
    async fn count_cleanup_candidates(&self, policy: &EpisodeRetentionPolicy) -> Result<usize> {
        let _ = policy;
        Ok(0)
    }
}