memory engine
A living memory that decays, learns, and evolves with your AI.
Documentation
๐ง Memory Engine
A living memory system for AI assistants โ built on SQLite + MCP (Model Context Protocol).
Not just a key-value store. Not just a knowledge graph. A living memory that decays, learns, and evolves with your AI.
Works with: Claude Code ยท Claude Desktop ยท Cursor ยท Cline ยท Windsurf ยท OpenClaw ยท Any MCP client
โจ Features
Core Memory
- Atomic memory model โ knowledge stored as atoms (facts, decisions, events, preferences, logs, procedures, notes, session messages, session digests)
- Hybrid ranking โ recall combines FTS relevance ร semantic similarity ร confidence ร recency ร weight
- Graph-aware recall โ top results are expanded bidirectionally via bonds, enriching context with related atoms
- Semantic search โ local embeddings via Ollama (
nomic-embed-text) for meaning-based recall, not just keyword match - Organic decay โ atoms lose weight over time if not accessed; critical ones get flagged for review
- Learning engine โ generates questions for the human when it detects contradictions, gaps, weak atoms, or merge candidates
- Cognitive curator โ conservative maintenance pass: body compaction, bond suggestions, duplicate detection, promotion candidates, and isolated-atom classification โ all without creating pending questions by default
- Isolated atom classification โ atoms without bonds are classified as
needs_link,standalone_ok,volatile_candidate, orarchive_candidate, with metadata tagging (no destructive actions) - Error memory โ tracks mistakes and corrections; auto-promotes recurring errors (3+ occurrences) to permanent preference rules
- Structured preferences โ searchable preference atoms with category, scope, and condition metadata
- Graph traversal โ navigate the knowledge graph with depth control and relation filtering
- Hierarchical summaries โ 3-level memory overview (global โ per-domain โ detail) for quick orientation
- Markdown import โ one-way sync from your existing markdown notes (coexistence, not replacement)
- Merge & deduplicate โ consolidate similar atoms intelligently
- TTL support โ atoms that expire automatically
- Versioning โ automatic atom history tracking
Auto-Bonding
- Rule-based bonding โ automatically creates relationships between atoms using domain clustering, keyword overlap, and pattern detection
- Semantic suggestions โ uses embeddings to find non-obvious connections between atoms
- Bulk operations โ scan all atoms and suggest/create bonds in batch
- 8 relation types โ
is_a,part_of,depends_on,contradicts,refines,derived_from,detail_of,related_to
Session Watcher v2.1
- Real-time ingestion โ monitors OpenClaw session JSONL files via watchdog/inotify + polling fallback
- Session digests โ automatically creates permanent summary atoms when sessions go inactive (after 30 min)
- Two-tier lifecycle โ raw session messages (7-day TTL) โ permanent session digests โ human daily logs
- Persistent offsets โ read positions stored in SQLite, survive container restarts
- Deduplication โ
content_hashprevents duplicates on rescan or restart - Smart filtering โ skips tool results, system messages, heartbeat noise, and system sessions
๐๏ธ Architecture
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Your AI Assistant โ
โ (via MCP Protocol) โ
โโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ MCP Server (FastMCP) โ
โ 31 tools (recall, remember, ...) โ
โโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Engine Layer โ
โ hybrid ranking ยท graph recall ยท decay โ
โ auto-bond ยท embeddings (Ollama) โ
โ error memory ยท preferences ยท learning โ
โโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Cognitive Curator (curator.py) โ
โ compact ยท bond pass ยท promotion detection โ
โ merge detection ยท isolated classification โ
โโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Session Watcher v2.1 (watchdog/inotify) โ
โ session JSONL โ atoms + auto-digests โ
โโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ SQLite (FTS5 + JSON1) โ
โ atoms ยท bonds ยท versions ยท embeddings ยท Q&Aโ
โ error_memory ยท session_offsets โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Files
| File | Purpose |
|---|---|
server.py | MCP server โ exposes 31 tools via FastMCP |
db.py | SQLite layer โ CRUD, FTS, bonds, versions, embeddings, error memory |
engine.py | Hybrid ranking (BM25 + semantic), graph recall, decay, similarity, gap detection |
curator.py | Cognitive curator โ compact, bonds, promotions, merges, isolated classification |
embeddings.py | Local embedding generation via Ollama (nomic-embed-text) |
auto_bond.py | Rule-based + semantic auto-bonding engine |
learning.py | Question generation (5 trigger types, graph_gap opt-in) |
session_watcher.py | Watchdog-based session JSONL monitor with auto-digest |
importer.py | Markdown โ SQLite one-way importer |
schema.sql | Database schema (atoms, bonds, FTS, versions, embeddings, offsets, error_memory) |
~5,000 lines of Python. Dependencies: mcp SDK, watchdog, requests.
๐ง MCP Tools (31)
Memory Operations
| Tool | Description |
|---|---|
remember | Create or update an atom |
recall | Smart query (FTS ร semantic ร confidence ร recency ร weight) |
semantic_search | Pure semantic search via Ollama embeddings |
get_atom | Get full atom details with all bonds |
list_atoms | List atoms with filters (domain, type, status) |
merge_atoms | Merge two atoms (secondary โ primary) |
export_atom | Export an atom as markdown |
find_similar | Find atoms semantically similar to a given atom |
Knowledge Graph
| Tool | Description |
|---|---|
link | Create a typed bond between atoms |
unlink | Remove a bond |
search_graph | Traverse the knowledge graph from an atom |
suggest_bonds | Suggest bonds for an atom (rule-based + semantic) |
suggest_bonds_all | Scan all atoms and suggest/create bonds in bulk |
Session Management
| Tool | Description |
|---|---|
recall_session | Search messages within a specific session |
session_summary | Get session overview (message count, time range) |
cleanup_sessions | Delete expired session atoms (TTL cleanup) |
cleanup_duplicates | Remove duplicate session_msg atoms |
reindex_embeddings | Regenerate embeddings for all atoms |
System & Learning
| Tool | Description |
|---|---|
stats | Memory statistics (counts, domains, types) |
memory_summary | Hierarchical 3-level summary (global โ domain โ detail) |
cognitive_status | Graph health metrics (isolated atoms, bonds, gaps, stale) |
working_set | Task-oriented context pack (recall + graph + procedures) |
curator_run | Conservative curation pass (compact, bonds, classification) |
version | Get server version |
decay_run | Execute decay cycle (reduce unused atom weights) |
learning_run | Run learning engine (detect gaps, contradictions) |
ask_pending | Get pending human questions |
answer_human | Answer a pending question |
import_markdown | Import markdown files (bulk or single) |
Error Memory & Preferences
| Tool | Description |
|---|---|
error_log | Log a mistake and its correction (auto-promotes after 3+ occurrences) |
error_check | Check if a task has failed before (retrieve past errors) |
error_list | List recorded errors filtered by resolution status |
preference_search | Search preference atoms by category, scope, or free text |
๐ Usage Examples
Remember a decision
remember(
title="Switched from npm to pnpm",
body="Faster installs, better monorepo support.",
type="decision",
domain="project:frontend",
confidence=0.9,
tags=["tooling", "npm", "pnpm"]
)
Recall with hybrid ranking
recall(query="frontend build tool choice", limit=5)
# Combines FTS match, semantic similarity, confidence, recency, and weight
Pure semantic search
semantic_search(query="how to deploy the app", limit=5)
# Uses Ollama embeddings โ finds by meaning, not just keywords
Auto-suggest bonds
suggest_bonds(atom_id="my_atom_id", auto_apply=False)
# Returns rule-based + semantic bond suggestions
suggest_bonds_all(auto_apply=True, max_atoms=30)
# Scans all active atoms and creates bonds automatically
Search within a session
recall_session(
session_id="abc123-def456",
query="database schema design",
limit=10
)
๐ Session Watcher v2.1
The session watcher monitors OpenClaw session JSONL files with a two-tier lifecycle:
- Raw messages (
session_msgatoms, TTL 7 days) โ ingested in real-time with dedup - Session digests (
session_digestatoms, permanent) โ auto-created after 30 min of inactivity, extracting user messages - Daily logs (human-written markdown) โ primary high-quality summary
This ensures continuity: if a session is lost, the digest provides context without searching thousands of raw messages.
Features
- Event-driven โ watchdog/inotify + polling fallback (30s) for Docker overlayfs
- Persistent offsets โ survive container restarts
- Deduplication โ content_hash on every atom
- Markdown digests โ lightweight
.mdmirror per session - Smart filtering โ skips tool results, system messages, heartbeats, cron/mqtt/isolated sessions
- Truncation detection โ auto-resets offset on file rotation
- Auto-expiring โ TTL cleanup every 60 minutes
Configuration
volumes:
- /path/to/openclaw/sessions:/sessions:ro
environment:
- OPENCLAW_SESSIONS_DIR=/sessions
- SESSION_TTL_DAYS=7
- SESSION_INACTIVE_THRESHOLD_MINUTES=30
- SESSION_DIGEST_DIR=/data/session_digests
๐ง Embeddings & Semantic Search
Local embeddings via Ollama (nomic-embed-text, 768-dim):
- Automatic โ embeddings generated on atom creation (async)
- Hybrid ranking โ
recall()combines BM25 + cosine similarity - Configurable weights โ tune FTS vs semantic balance
- Reindexable โ
reindex_embeddingstool for batch regeneration - Local & private โ no external API calls
{
"ollama": { "enabled": true, "host": "http://ollama:11434", "model": "nomic-embed-text", "dim": 768 },
"ranking": { "fts_weight": 0.30, "semantic_weight": 0.30, "confidence_weight": 0.20, "recency_weight": 0.10, "weight_factor": 0.10 }
}
๐ Auto-Bonding
Automatically discovers relationships between atoms:
- Domain clustering โ same domain โ
related_tobonds - Keyword overlap โ shared tags trigger connections
- Pattern detection โ naming conventions matched
- Semantic similarity โ embeddings find non-obvious links
{
"auto_bond": { "semantic_threshold": 0.65, "domain_cluster_threshold": 0.4, "max_suggestions": 10 }
}
๐ง Cognitive Curator
The curator is a conservative maintenance engine that runs in dry-run mode by default. It never deletes durable atoms or rewrites markdown source.
Passes
| Pass | What it does |
|---|---|
| body_compact | Generates extractive summaries for long atoms (>1200 chars) |
| bond_pass | Suggests/creates rule-based bonds across active atoms |
| promotion | Detects recurring session/daily concepts worth promoting to durable facts |
| merge | Flags potential duplicates by normalized title |
| isolated_classification | Classifies atoms without bonds into actionable states |
Isolated Atom States
When curator_run runs, atoms without bonds are classified:
| State | Meaning |
|---|---|
needs_link | Durable, high-weight or frequently accessed โ should be connected |
standalone_ok | Naturally standalone (preferences, explicitly allowed) |
volatile_candidate | Session/chat material or too new โ let TTL/digest handle it |
archive_candidate | Old, never accessed โ consider archiving |
With auto_apply=True, the curator writes only non-destructive metadata (isolated_state, isolated_reason, isolated_reviewed_at). It never archives or deletes atoms automatically.
v1.5.2 change:
learning_runno longer generatesgraph_gappending questions by default. Isolated-atom review is handled entirely by the curator. Setlearning.graph_gap_enabled=truein config to re-enable the old behavior.
Error Memory
The error memory subsystem tracks mistakes and corrections:
- error_log โ record what went wrong and the fix
- error_check โ check before attempting a task if it has failed before
- error_list โ review resolved/unresolved errors
- Auto-promotion โ after 3+ occurrences, an error is promoted to a permanent preference rule automatically
error_log(
mistake="Used dotnet build without --framework",
correction="Always use: dotnet build -f net48",
task_type="compilation",
error_category="logic_error",
severity="minor"
)
๐ Quick Start
Docker (recommended)
services:
memory-engine:
build: .
restart: unless-stopped
expose:
- "8085"
volumes:
- memory-data:/data
- ./your-markdown-notes:/workspace/memory:ro
- /path/to/openclaw/sessions:/sessions:ro
environment:
- MEMORY_DB_PATH=/data/memory.db
- MARKDOWN_SOURCE=/workspace/memory
- MEMORY_HOST=0.0.0.0
- MEMORY_PORT=8085
- OPENCLAW_SESSIONS_DIR=/sessions
- SESSION_TTL_DAYS=7
- SESSION_INACTIVE_THRESHOLD_MINUTES=30
Local (Python โฅ3.12)
pip install -r requirements.txt
python server.py
Connect to your MCP client
{
"mcpServers": {
"memory-engine": {
"url": "http://localhost:8085/sse",
"transport": "sse"
}
}
}
โ๏ธ Configuration
| Section | What it controls |
|---|---|
decay | Interval, decay factor, critical threshold, archive timeout |
ranking | FTS, semantic, confidence, recency, and weight balance |
ollama | Embedding model, host, dimensions, reindex settings |
auto_bond | Semantic threshold, domain cluster threshold, max suggestions |
learning | Contradiction, merge similarity, gap detection thresholds |
session_ttl_days | TTL for session message atoms (default 7) |
session_inactive_threshold_minutes | Inactivity before session digest (default 30) |
๐งฌ How It Differs
| Feature | memory-graph | sqlite-memory | Memory Engine |
|---|---|---|---|
| Storage | SQLite | SQLite | SQLite |
| FTS search | โ | โ (BM25) | โ (multi-factor) |
| Semantic search | โ | โ | โ (Ollama) |
| Hybrid ranking | โ | โ | โ (BM25 + semantic) |
| Graph-aware recall | โ | โ | โ (bidirectional) |
| Decay | โ | โ | โ |
| Learning/Q&A | โ | โ | โ |
| Auto-bonding | โ | โ | โ (rules + semantic) |
| Cognitive curator | โ | โ | โ |
| Isolated classification | โ | โ | โ |
| Error memory | โ | โ | โ |
| Structured preferences | โ | โ | โ |
| Hierarchical summaries | โ | โ | โ |
| Session watcher | โ | โ | โ (v2.1 + digests) |
| Session digests | โ | โ | โ (auto-summary) |
| Markdown import | โ | โ | โ |
| Graph traversal | Basic | โ | โ (depth + relation) |
| Merge atoms | โ | โ | โ |
| TTL | โ | โ | โ |
| Versioning | โ | โ | โ |
๐ License
MIT โ see LICENSE.
Made with ๐ง by SimoneB79