memory crate provides persistent memory storage with semantic search, deduplication, knowledge graphs, session management, and automatic eviction policies.
memory::store
Store a memory entry with SHA-256 content deduplication and optional embedding generation.Agent identifier for memory ownership
Memory content to store
Message role: “user”, “assistant”, or “system”
Optional session identifier for grouping related memories
UUID of the created memory entry
True if memory was stored (false if deduplicated)
True if content already exists (duplicate detected via SHA-256)
Storage Details
- Deduplication: SHA-256 hash of content prevents duplicates
- Embeddings: Automatically generated via
embedding::generateif available - Importance: Auto-calculated based on content length, role, and keywords
- Confidence: Starts at 1.0, decays over time if unaccessed
- Session Tracking: Updates session metadata if sessionId provided
Memory Entry Structure
memory::recall
Hybrid semantic + keyword + recency search across agent memories.Agent ID to search memories for
Search query text
Maximum number of results to return
Scoring Algorithm
The recall function uses a weighted hybrid scoring system:- Semantic Similarity (50%): Cosine similarity between query and memory embeddings
- Keyword Match (25%): Proportion of query keywords found in content (case-insensitive)
- Recency (10%): Exponential decay with 1-week half-life
- Importance (10%): Stored importance score
- Confidence (5%): Current confidence value
Side Effects
- Increments
accessCountfor returned memories - Updates
lastAccessedtimestamp - Prevents confidence decay for recently accessed memories
memory::evict
Evict stale, low-importance, or low-confidence memories across all agents.Maximum age in milliseconds (default: 30 days)
Minimum importance threshold (0.0-1.0)
Maximum memories per agent (evicts lowest importance if exceeded)
Total number of memories evicted
Evict Stale Memories
Eviction Criteria
A memory is evicted if:- (age > maxAge AND importance < minImportance) OR
- confidence < 0.1 OR
- Memory count exceeds cap (evicts lowest importance)
This function is automatically triggered daily at 3 AM via cron expression
0 3 * * *.memory::consolidate
Decay confidence on unaccessed memories (runs every 6 hours via cron).Confidence decay rate (0.0-1.0)
Number of memories with decayed confidence
Number of duplicate memories merged (future feature, currently 0)
Execution time in milliseconds
Consolidate Memories
Consolidation Logic
- Applies to memories not accessed in 7+ days
- New confidence =
confidence * (1 - decayRate), minimum 0.1 - Skips memories already at minimum confidence (0.1)
Automatic consolidation runs every 6 hours via cron expression
0 */6 * * *.memory::kg::add
Add or update knowledge graph entity with bidirectional relation tracking.Agent ID for knowledge graph ownership
Entity object to store
Unique entity identifier
Entity type (e.g., “person”, “project”, “concept”)
Entity attributes as key-value pairs
True if entity was stored successfully
Entity ID
Bidirectional Relations
When adding relations, the function automatically creates inverse relations:- If A → B with type “works_on”, creates B → A with type “inverse:works_on”
- Prevents duplicate inverse relations
- Maintains graph consistency across updates
memory::kg::query
Traverse knowledge graph from a starting entity up to specified depth.Agent ID for knowledge graph
Starting entity ID for traversal
Maximum traversal depth (default: 2)
Array of entity objects encountered during traversal
Query Knowledge Graph
Traversal Algorithm
- Breadth-first search from starting entity
- Tracks visited nodes to prevent cycles
- Stops at specified depth or when all paths exhausted
- Returns entities in order discovered
memory::session::list
List all sessions for a specific agent.Agent ID to list sessions for
Array of session metadata objects
List Sessions
memory::session::compact
Compact long sessions by summarizing old messages via LLM.Agent ID
Session ID to compact
Minimum messages before compaction
Number of recent messages to preserve
True if compaction was performed
Number of messages summarized
Number of recent messages kept
Memory ID of the generated summary
Compact Session
Compaction Process
- Check if session has ≥ threshold messages
- Split into: messages to summarize and recent messages to keep
- Fetch full message content from memory
- Chunk conversation text (max 80K chars per chunk)
- Generate summaries via
llm::completewith claude-haiku - Store combined summary as system message with importance 0.9
- Update session with summary + recent messages
memory::session::repair
7-phase validation and repair for corrupted session data.Agent ID
Session ID to repair
True if any repairs were performed
Total number of fixes applied
Breakdown of repair statistics by type
Repair Session
7 Repair Phases
- Remove Empty Messages: Filter messages with missing or empty IDs
- Deduplicate: Remove duplicate message IDs
- Merge Consecutive: Merge consecutive messages with same role (except system)
- Detect Orphans: Count message references without corresponding memory entries
- Fix Ordering: Repair out-of-order timestamps
- Detect Oversized: Flag messages with content > 500KB
- Update Session: Write repaired session with stats
Repair is idempotent - running multiple times produces the same result.
Cron Automation
The memory worker automatically runs maintenance tasks:- Consolidation: Every 6 hours (
0 */6 * * *) - Eviction: Daily at 3 AM (
0 3 * * *)