do-memory-core 0.1.30

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
418
419
420
421
422
423
424
425
426
//! Relationship API for [`SelfLearningMemory`].
//!
//! This module extends [`SelfLearningMemory`] with episode relationship management,
//! providing methods to add, remove, and query relationships between episodes.

use crate::episode::{
    Direction, EpisodeRelationship, RelationshipManager, RelationshipMetadata, RelationshipType,
};
use crate::error::Result;
use crate::security::audit::{AuditContext, relationship_added, relationship_removed};
use uuid::Uuid;

use super::relationship_query::{EpisodeWithRelationships, RelationshipFilter, RelationshipGraph};
use super::types::SelfLearningMemory;

impl SelfLearningMemory {
    /// Add a relationship between two episodes.
    ///
    /// Creates a directed relationship from one episode to another with optional
    /// metadata. The relationship is validated before being stored.
    ///
    /// # Arguments
    ///
    /// * `from_episode_id` - Source episode UUID
    /// * `to_episode_id` - Target episode UUID
    /// * `relationship_type` - Type of relationship (`DependsOn`, `ParentChild`, etc.)
    /// * `metadata` - Optional metadata (reason, priority, custom fields)
    ///
    /// # Returns
    ///
    /// The UUID of the created relationship on success.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Either episode does not exist
    /// - Self-relationship is attempted
    /// - Duplicate relationship exists
    /// - Cycle would be created (for acyclic relationship types)
    ///
    /// # Example
    ///
    /// ```no_run
    /// use do_memory_core::memory::SelfLearningMemory;
    /// use do_memory_core::episode::{RelationshipType, RelationshipMetadata};
    /// use uuid::Uuid;
    ///
    /// # async fn example() -> anyhow::Result<()> {
    /// let memory = SelfLearningMemory::new();
    /// let parent_id = Uuid::new_v4();
    /// let child_id = Uuid::new_v4();
    ///
    /// let rel_id = memory.add_episode_relationship(
    ///     parent_id,
    ///     child_id,
    ///     RelationshipType::ParentChild,
    ///     RelationshipMetadata::with_reason("Child task spawned from parent".to_string()),
    /// ).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn add_episode_relationship(
        &self,
        from_episode_id: Uuid,
        to_episode_id: Uuid,
        relationship_type: RelationshipType,
        metadata: RelationshipMetadata,
    ) -> Result<Uuid> {
        // Validate both episodes exist (get_episode returns Error::NotFound if missing)
        self.get_episode(from_episode_id).await?;
        self.get_episode(to_episode_id).await?;

        // Use RelationshipManager for validation
        let mut manager = RelationshipManager::new();

        // Load existing relationships for cycle detection
        let existing = self.get_all_relationships_internal().await?;
        manager.load_relationships(existing);

        // Add with validation (handles self-ref, duplicates, cycles)
        let relationship = manager
            .add_with_validation(from_episode_id, to_episode_id, relationship_type, metadata)
            .map_err(|e| crate::error::Error::ValidationFailed(e.to_string()))?;

        let relationship_id = relationship.id;

        // Store to durable storage if available
        if let Some(storage) = &self.turso_storage {
            storage.store_relationship(&relationship).await?;
        }

        // Store to cache if available
        if let Some(cache) = &self.cache_storage {
            let _ = cache.store_relationship(&relationship).await;
        }

        // In-memory fallback storage (when no backends configured)
        if self.turso_storage.is_none() && self.cache_storage.is_none() {
            let mut relationships = self.relationships_fallback.write().await;
            relationships.insert(relationship_id, relationship.clone());
        }

        // Audit log: relationship added
        let context = AuditContext::system();
        let audit_entry = relationship_added(
            &context,
            relationship_id,
            from_episode_id,
            to_episode_id,
            relationship_type.as_str(),
        );
        self.audit_logger.log(audit_entry);

        Ok(relationship_id)
    }

    /// Remove a relationship by its ID.
    ///
    /// # Arguments
    ///
    /// * `relationship_id` - The UUID of the relationship to remove
    ///
    /// # Returns
    ///
    /// `Ok(())` on success, or an error if the relationship was not found.
    pub async fn remove_episode_relationship(&self, relationship_id: Uuid) -> Result<()> {
        // Remove from durable storage
        if let Some(storage) = &self.turso_storage {
            storage.remove_relationship(relationship_id).await?;
        }

        // Remove from cache
        if let Some(cache) = &self.cache_storage {
            let _ = cache.remove_relationship(relationship_id).await;
        }

        // In-memory fallback removal (when no backends configured)
        if self.turso_storage.is_none() && self.cache_storage.is_none() {
            let mut relationships = self.relationships_fallback.write().await;
            relationships.remove(&relationship_id);
        }

        // Audit log: relationship removed
        let context = AuditContext::system();
        let audit_entry = relationship_removed(&context, relationship_id);
        self.audit_logger.log(audit_entry);

        Ok(())
    }

    /// Get all relationships for an episode.
    ///
    /// # Arguments
    ///
    /// * `episode_id` - The episode to query
    /// * `direction` - Which relationships to return (Outgoing, Incoming, or Both)
    ///
    /// # Returns
    ///
    /// A vector of relationships matching the query.
    pub async fn get_episode_relationships(
        &self,
        episode_id: Uuid,
        direction: Direction,
    ) -> Result<Vec<EpisodeRelationship>> {
        // Try cache first
        if let Some(cache) = &self.cache_storage {
            if let Ok(rels) = cache.get_relationships(episode_id, direction).await {
                if !rels.is_empty() {
                    return Ok(rels);
                }
            }
        }

        // Fall back to durable storage
        if let Some(storage) = &self.turso_storage {
            return storage.get_relationships(episode_id, direction).await;
        }

        // In-memory fallback (no storage configured)
        if self.turso_storage.is_none() && self.cache_storage.is_none() {
            let relationships = self.relationships_fallback.read().await;
            let filtered = relationships
                .values()
                .filter(|rel| match direction {
                    Direction::Outgoing => rel.from_episode_id == episode_id,
                    Direction::Incoming => rel.to_episode_id == episode_id,
                    Direction::Both => {
                        rel.from_episode_id == episode_id || rel.to_episode_id == episode_id
                    }
                })
                .cloned()
                .collect();
            return Ok(filtered);
        }

        Ok(Vec::new())
    }

    /// Find related episodes with filtering options.
    ///
    /// # Arguments
    ///
    /// * `episode_id` - The episode to find relationships for
    /// * `filter` - Optional filter criteria (type, direction, limit, priority)
    ///
    /// # Returns
    ///
    /// A vector of related episode IDs matching the filter.
    pub async fn find_related_episodes(
        &self,
        episode_id: Uuid,
        filter: RelationshipFilter,
    ) -> Result<Vec<Uuid>> {
        let direction = filter.direction.unwrap_or(Direction::Both);
        let relationships = self
            .get_episode_relationships(episode_id, direction)
            .await?;

        let mut related: Vec<Uuid> = relationships
            .into_iter()
            .filter(|rel| Self::matches_filter(rel, &filter))
            .map(|rel| {
                if rel.from_episode_id == episode_id {
                    rel.to_episode_id
                } else {
                    rel.from_episode_id
                }
            })
            .collect();

        // Apply limit
        if let Some(limit) = filter.limit {
            related.truncate(limit);
        }

        Ok(related)
    }

    /// Get an episode with all its relationships.
    ///
    /// # Arguments
    ///
    /// * `episode_id` - The episode to retrieve
    ///
    /// # Returns
    ///
    /// The episode along with its incoming and outgoing relationships.
    pub async fn get_episode_with_relationships(
        &self,
        episode_id: Uuid,
    ) -> Result<EpisodeWithRelationships> {
        let episode = self.get_episode(episode_id).await?;

        let outgoing = self
            .get_episode_relationships(episode_id, Direction::Outgoing)
            .await?;
        let incoming = self
            .get_episode_relationships(episode_id, Direction::Incoming)
            .await?;

        Ok(EpisodeWithRelationships {
            episode,
            outgoing,
            incoming,
        })
    }

    /// Build a relationship graph starting from an episode.
    ///
    /// Traverses relationships up to a specified depth to build a graph
    /// that can be visualized or analyzed.
    ///
    /// # Arguments
    ///
    /// * `root_episode_id` - The starting episode
    /// * `max_depth` - Maximum traversal depth (default: 3)
    ///
    /// # Returns
    ///
    /// A `RelationshipGraph` containing nodes and edges.
    pub async fn build_relationship_graph(
        &self,
        root_episode_id: Uuid,
        max_depth: usize,
    ) -> Result<RelationshipGraph> {
        let mut graph = RelationshipGraph::new(root_episode_id);
        let mut visited = std::collections::HashSet::new();
        let mut queue = std::collections::VecDeque::new();

        queue.push_back((root_episode_id, 0));

        while let Some((episode_id, depth)) = queue.pop_front() {
            if visited.contains(&episode_id) || depth > max_depth {
                continue;
            }
            visited.insert(episode_id);

            // Add episode node (ignore if not found)
            if let Ok(episode) = self.get_episode(episode_id).await {
                graph.add_node(episode);
            }

            // Get relationships and add edges
            let relationships = self
                .get_episode_relationships(episode_id, Direction::Both)
                .await?;
            for rel in relationships {
                graph.add_edge(rel.clone());

                // Queue connected episodes
                let connected = if rel.from_episode_id == episode_id {
                    rel.to_episode_id
                } else {
                    rel.from_episode_id
                };
                if !visited.contains(&connected) {
                    queue.push_back((connected, depth + 1));
                }
            }
        }

        Ok(graph)
    }

    /// Check if a relationship exists between two episodes.
    ///
    /// # Arguments
    ///
    /// * `from_episode_id` - Source episode
    /// * `to_episode_id` - Target episode
    /// * `relationship_type` - Type of relationship to check
    ///
    /// # Returns
    ///
    /// `true` if the relationship exists, `false` otherwise.
    pub async fn relationship_exists(
        &self,
        from_episode_id: Uuid,
        to_episode_id: Uuid,
        relationship_type: RelationshipType,
    ) -> Result<bool> {
        if let Some(storage) = &self.turso_storage {
            return storage
                .relationship_exists(from_episode_id, to_episode_id, relationship_type)
                .await;
        }
        if self.turso_storage.is_none() && self.cache_storage.is_none() {
            let relationships = self.relationships_fallback.read().await;
            let exists = relationships.values().any(|rel| {
                rel.from_episode_id == from_episode_id
                    && rel.to_episode_id == to_episode_id
                    && rel.relationship_type == relationship_type
            });
            return Ok(exists);
        }
        Ok(false)
    }

    /// Get all dependencies for an episode (episodes it depends on).
    ///
    /// Convenience method for getting `DependsOn` relationships.
    pub async fn get_episode_dependencies(&self, episode_id: Uuid) -> Result<Vec<Uuid>> {
        self.find_related_episodes(
            episode_id,
            RelationshipFilter::new()
                .with_type(RelationshipType::DependsOn)
                .with_direction(Direction::Outgoing),
        )
        .await
    }

    /// Get all dependents for an episode (episodes that depend on it).
    ///
    /// Convenience method for getting reverse `DependsOn` relationships.
    pub async fn get_episode_dependents(&self, episode_id: Uuid) -> Result<Vec<Uuid>> {
        self.find_related_episodes(
            episode_id,
            RelationshipFilter::new()
                .with_type(RelationshipType::DependsOn)
                .with_direction(Direction::Incoming),
        )
        .await
    }

    // -------------------------------------------------------------------------
    // Internal helpers
    // -------------------------------------------------------------------------

    /// Check if a relationship matches the given filter criteria.
    fn matches_filter(rel: &EpisodeRelationship, filter: &RelationshipFilter) -> bool {
        // Filter by type
        if let Some(ref rel_type) = filter.relationship_type {
            if rel.relationship_type != *rel_type {
                return false;
            }
        }
        // Filter by priority
        if let Some(min_priority) = filter.min_priority {
            if let Some(priority) = rel.metadata.priority {
                if priority < min_priority {
                    return false;
                }
            }
        }
        true
    }

    #[allow(clippy::unused_async)]
    async fn get_all_relationships_internal(&self) -> Result<Vec<EpisodeRelationship>> {
        // For cycle detection, we would need to query all relationships
        // For now, return empty - full implementation would query storage
        if let Some(_storage) = &self.turso_storage {
            // This would need a method to get all relationships
            // For now, return empty vec
        }
        if self.turso_storage.is_none() && self.cache_storage.is_none() {
            let relationships = self.relationships_fallback.read().await;
            return Ok(relationships.values().cloned().collect());
        }
        Ok(Vec::new())
    }
}

#[cfg(test)]
mod tests;