shodh-memory 0.2.0

Persistent cognitive memory for AI agents and robots — Hebbian learning, knowledge graph, spatial recall. Zenoh/ROS2 native. Single binary, runs offline.
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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
//! Memory System Visualization using Petgraph
//! Creates a real-time graph of memory connections like a neural network

#![allow(dead_code)]

use crate::memory::{ExperienceType, Memory, MemoryId};
use petgraph::dot::{Config, Dot};
use petgraph::graph::{DiGraph, NodeIndex};
use serde::Serialize;
use std::collections::HashMap;
use std::fmt;
use tracing::{debug, info, trace};

/// Node type in the memory graph
#[derive(Debug, Clone)]
pub enum MemoryNode {
    WorkingMemory {
        id: MemoryId,
        importance: f32,
    },
    SessionMemory {
        id: MemoryId,
        importance: f32,
    },
    LongTermMemory {
        id: MemoryId,
        importance: f32,
        compressed: bool,
    },
    Experience {
        exp_type: ExperienceType,
        content: String,
    },
    Context {
        context_id: String,
        decay: f32,
    },
}

impl fmt::Display for MemoryNode {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            MemoryNode::WorkingMemory { id: _, importance } => {
                write!(f, "WM\\n{importance:.2}")
            }
            MemoryNode::SessionMemory { id: _, importance } => {
                write!(f, "SM\\n{importance:.2}")
            }
            MemoryNode::LongTermMemory {
                id: _,
                importance,
                compressed,
            } => {
                write!(
                    f,
                    "LTM\\n{:.2}{}",
                    importance,
                    if *compressed { "🗜️" } else { "" }
                )
            }
            MemoryNode::Experience { exp_type, .. } => {
                write!(f, "{exp_type:?}")
            }
            MemoryNode::Context {
                context_id: _,
                decay,
            } => {
                write!(f, "CTX\\n{decay:.2}")
            }
        }
    }
}

/// Edge type in the memory graph
#[derive(Debug, Clone)]
pub enum MemoryEdge {
    Promotion,               // Working -> Session -> LongTerm
    SemanticSimilarity(f32), // Similarity score
    TemporalSuccession,      // A happened after B
    CausalLink,              // A caused B
    ContextRelation,         // Related through context
}

impl fmt::Display for MemoryEdge {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            MemoryEdge::Promotion => write!(f, ""),
            MemoryEdge::SemanticSimilarity(score) => write!(f, "~{score:.2}"),
            MemoryEdge::TemporalSuccession => write!(f, ""),
            MemoryEdge::CausalLink => write!(f, ""),
            MemoryEdge::ContextRelation => write!(f, ""),
        }
    }
}

/// Memory visualization graph
pub struct MemoryGraph {
    graph: DiGraph<MemoryNode, MemoryEdge>,
    node_map: HashMap<String, NodeIndex>,
}

impl Default for MemoryGraph {
    fn default() -> Self {
        Self::new()
    }
}

impl MemoryGraph {
    pub fn new() -> Self {
        Self {
            graph: DiGraph::new(),
            node_map: HashMap::new(),
        }
    }

    /// Add a memory to the graph
    pub fn add_memory(&mut self, memory: &Memory, tier: &str) -> NodeIndex {
        let key = format!("{}_{}", tier, memory.id.0);

        if let Some(&idx) = self.node_map.get(&key) {
            return idx;
        }

        let node = match tier {
            "working" => MemoryNode::WorkingMemory {
                id: memory.id.clone(),
                importance: memory.importance(),
            },
            "session" => MemoryNode::SessionMemory {
                id: memory.id.clone(),
                importance: memory.importance(),
            },
            "longterm" => MemoryNode::LongTermMemory {
                id: memory.id.clone(),
                importance: memory.importance(),
                compressed: memory.compressed,
            },
            _ => {
                tracing::error!(
                    "Invalid tier '{}' passed to add_memory for memory {}, defaulting to WorkingMemory",
                    tier,
                    memory.id.0
                );
                MemoryNode::WorkingMemory {
                    id: memory.id.clone(),
                    importance: memory.importance(),
                }
            }
        };

        let idx = self.graph.add_node(node);
        self.node_map.insert(key, idx);
        idx
    }

    /// Add an experience node
    pub fn add_experience(&mut self, exp_type: ExperienceType, content: &str) -> NodeIndex {
        let node = MemoryNode::Experience {
            exp_type,
            content: content.chars().take(50).collect(),
        };
        self.graph.add_node(node)
    }

    /// Add a context node
    pub fn add_context(&mut self, context_id: &str, decay: f32) -> NodeIndex {
        let node = MemoryNode::Context {
            context_id: context_id.to_string(),
            decay,
        };
        self.graph.add_node(node)
    }

    /// Add an edge between nodes
    pub fn add_edge(&mut self, from: NodeIndex, to: NodeIndex, edge_type: MemoryEdge) {
        self.graph.add_edge(from, to, edge_type);
    }

    /// Visualize memory promotion (working -> session -> longterm)
    pub fn log_promotion(&mut self, from_tier: &str, to_tier: &str, memory_id: &MemoryId) {
        let from_key = format!("{}_{}", from_tier, memory_id.0);
        let to_key = format!("{}_{}", to_tier, memory_id.0);

        if let (Some(&from_idx), Some(&to_idx)) =
            (self.node_map.get(&from_key), self.node_map.get(&to_key))
        {
            self.add_edge(from_idx, to_idx, MemoryEdge::Promotion);
            debug!(
                from = from_tier.to_uppercase().as_str(),
                to = to_tier.to_uppercase().as_str(),
                "Graph tier promotion"
            );
        }
    }

    /// Export graph as DOT format for Graphviz
    pub fn to_dot(&self) -> String {
        format!(
            "{:?}",
            Dot::with_config(&self.graph, &[Config::EdgeNoLabel])
        )
    }

    /// Get statistics about the graph
    pub fn stats(&self) -> GraphStats {
        GraphStats {
            total_nodes: self.graph.node_count(),
            total_edges: self.graph.edge_count(),
            working_memory_count: self.count_tier("working"),
            session_memory_count: self.count_tier("session"),
            longterm_memory_count: self.count_tier("longterm"),
        }
    }

    fn count_tier(&self, tier: &str) -> usize {
        self.node_map
            .keys()
            .filter(|k| k.starts_with(&format!("{tier}_")))
            .count()
    }

    /// Print ASCII visualization of current memory state
    pub fn print_ascii_visualization(&self) {
        let stats = self.stats();

        info!(
            working = stats.working_memory_count,
            session = stats.session_memory_count,
            longterm = stats.longterm_memory_count,
            nodes = stats.total_nodes,
            edges = stats.total_edges,
            "Memory system visualization: working={}, session={}, longterm={}, nodes={}, edges={}",
            stats.working_memory_count,
            stats.session_memory_count,
            stats.longterm_memory_count,
            stats.total_nodes,
            stats.total_edges,
        );
    }
}

/// Graph statistics
#[derive(Debug, Clone, Serialize)]
pub struct GraphStats {
    pub total_nodes: usize,
    pub total_edges: usize,
    pub working_memory_count: usize,
    pub session_memory_count: usize,
    pub longterm_memory_count: usize,
}

/// Logger for memory operations
pub struct MemoryLogger {
    pub graph: MemoryGraph,
    enabled: bool,
}

impl MemoryLogger {
    pub fn new(enabled: bool) -> Self {
        Self {
            graph: MemoryGraph::new(),
            enabled,
        }
    }

    /// Log memory creation
    pub fn log_created(&mut self, memory: &Memory, tier: &str) {
        if !self.enabled {
            return;
        }

        debug!(
            tier = tier.to_uppercase().as_str(),
            importance = memory.importance(),
            experience_type = ?memory.experience.experience_type,
            "Memory created"
        );

        self.graph.add_memory(memory, tier);
    }

    /// Log memory access
    pub fn log_accessed(&self, memory_id: &MemoryId, tier: &str) {
        if !self.enabled {
            return;
        }

        trace!(
            tier = tier.to_uppercase().as_str(),
            memory_id = %memory_id.0,
            "Memory accessed"
        );
    }

    /// Log memory promotion
    pub fn log_promoted(&mut self, memory_id: &MemoryId, from: &str, to: &str, count: usize) {
        if !self.enabled {
            return;
        }

        debug!(
            from = from.to_uppercase().as_str(),
            to = to.to_uppercase().as_str(),
            count,
            "Memory tier promotion"
        );

        self.graph.log_promotion(from, to, memory_id);
    }

    /// Log compression
    pub fn log_compressed(
        &self,
        _memory_id: &MemoryId,
        original_size: usize,
        compressed_size: usize,
    ) {
        if !self.enabled {
            return;
        }

        let ratio = (compressed_size as f32 / original_size as f32 * 100.0) as usize;
        debug!(original_size, compressed_size, ratio, "Memory compressed");
    }

    /// Log retrieval
    pub fn log_retrieved(&self, query: &str, result_count: usize, sources: &[&str]) {
        if !self.enabled {
            return;
        }

        debug!(
            query = %query.chars().take(50).collect::<String>(),
            result_count,
            sources = %sources.join(", "),
            "Memory retrieved"
        );
    }

    /// Show visualization
    pub fn show_visualization(&self) {
        if !self.enabled {
            return;
        }

        self.graph.print_ascii_visualization();
    }

    /// Export graph
    pub fn export_dot(&self, path: &std::path::Path) -> anyhow::Result<()> {
        if !self.enabled {
            return Ok(());
        }

        let dot = self.graph.to_dot();
        std::fs::write(path, dot)?;
        info!(path = %path.display(), "Graph exported");
        Ok(())
    }

    /// Get graph statistics
    pub fn get_stats(&self) -> GraphStats {
        self.graph.stats()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::memory::{Experience, ExperienceType, Memory, MemoryId};

    fn create_test_memory() -> Memory {
        use uuid::Uuid;

        let experience = Experience {
            experience_type: ExperienceType::Conversation,
            content: "test content".to_string(),
            ..Default::default()
        };

        Memory::new(
            MemoryId(Uuid::new_v4()),
            experience,
            0.5,  // importance
            None, // agent_id
            None, // run_id
            None, // actor_id
            None, // created_at
        )
    }

    #[test]
    fn test_add_memory_with_valid_tiers() {
        let mut graph = MemoryGraph::new();
        let memory = create_test_memory();

        // Test all valid tier names
        let idx1 = graph.add_memory(&memory, "working");
        let idx2 = graph.add_memory(&memory, "session");
        let idx3 = graph.add_memory(&memory, "longterm");

        // Verify nodes were created
        assert_eq!(graph.graph.node_count(), 3);
        assert!(idx1 != idx2 && idx2 != idx3 && idx1 != idx3);
    }

    #[test]
    fn test_add_memory_with_invalid_tier_does_not_panic() {
        let mut graph = MemoryGraph::new();
        let memory = create_test_memory();

        // This should NOT panic - it should log error and default to WorkingMemory
        let idx = graph.add_memory(&memory, "invalid_tier_name");

        // Verify node was created despite invalid tier
        assert_eq!(graph.graph.node_count(), 1);

        // Verify the node exists
        assert!(graph.graph.node_weight(idx).is_some());

        // Verify it was added as WorkingMemory (default fallback)
        let node = graph.graph.node_weight(idx).unwrap();
        match node {
            MemoryNode::WorkingMemory { .. } => {
                // Success - defaulted to WorkingMemory
            }
            _ => panic!("Expected WorkingMemory for invalid tier, got {node:?}"),
        }
    }

    #[test]
    fn test_add_memory_with_various_invalid_tiers() {
        let mut graph = MemoryGraph::new();
        let memory = create_test_memory();

        // Test various invalid tier names - none should panic
        let invalid_tiers = vec![
            "",
            "Working",
            "WORKING",
            "long-term",
            "unknown",
            "123",
            "session_memory",
        ];

        for tier in invalid_tiers {
            let _ = graph.add_memory(&memory, tier);
        }

        // All should have been created as WorkingMemory
        assert_eq!(graph.graph.node_count(), 7);
    }
}