memory engine

A living memory that decays, learns, and evolves with your AI.

Documentation

Version License: MIT Python

Memory Engine Logo

๐Ÿง  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, or archive_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_hash prevents 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

FilePurpose
server.pyMCP server โ€” exposes 31 tools via FastMCP
db.pySQLite layer โ€” CRUD, FTS, bonds, versions, embeddings, error memory
engine.pyHybrid ranking (BM25 + semantic), graph recall, decay, similarity, gap detection
curator.pyCognitive curator โ€” compact, bonds, promotions, merges, isolated classification
embeddings.pyLocal embedding generation via Ollama (nomic-embed-text)
auto_bond.pyRule-based + semantic auto-bonding engine
learning.pyQuestion generation (5 trigger types, graph_gap opt-in)
session_watcher.pyWatchdog-based session JSONL monitor with auto-digest
importer.pyMarkdown โ†’ SQLite one-way importer
schema.sqlDatabase schema (atoms, bonds, FTS, versions, embeddings, offsets, error_memory)

~5,000 lines of Python. Dependencies: mcp SDK, watchdog, requests.

๐Ÿ”ง MCP Tools (31)

Memory Operations

ToolDescription
rememberCreate or update an atom
recallSmart query (FTS ร— semantic ร— confidence ร— recency ร— weight)
semantic_searchPure semantic search via Ollama embeddings
get_atomGet full atom details with all bonds
list_atomsList atoms with filters (domain, type, status)
merge_atomsMerge two atoms (secondary โ†’ primary)
export_atomExport an atom as markdown
find_similarFind atoms semantically similar to a given atom

Knowledge Graph

ToolDescription
linkCreate a typed bond between atoms
unlinkRemove a bond
search_graphTraverse the knowledge graph from an atom
suggest_bondsSuggest bonds for an atom (rule-based + semantic)
suggest_bonds_allScan all atoms and suggest/create bonds in bulk

Session Management

ToolDescription
recall_sessionSearch messages within a specific session
session_summaryGet session overview (message count, time range)
cleanup_sessionsDelete expired session atoms (TTL cleanup)
cleanup_duplicatesRemove duplicate session_msg atoms
reindex_embeddingsRegenerate embeddings for all atoms

System & Learning

ToolDescription
statsMemory statistics (counts, domains, types)
memory_summaryHierarchical 3-level summary (global โ†’ domain โ†’ detail)
cognitive_statusGraph health metrics (isolated atoms, bonds, gaps, stale)
working_setTask-oriented context pack (recall + graph + procedures)
curator_runConservative curation pass (compact, bonds, classification)
versionGet server version
decay_runExecute decay cycle (reduce unused atom weights)
learning_runRun learning engine (detect gaps, contradictions)
ask_pendingGet pending human questions
answer_humanAnswer a pending question
import_markdownImport markdown files (bulk or single)

Error Memory & Preferences

ToolDescription
error_logLog a mistake and its correction (auto-promotes after 3+ occurrences)
error_checkCheck if a task has failed before (retrieve past errors)
error_listList recorded errors filtered by resolution status
preference_searchSearch 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:

  1. Raw messages (session_msg atoms, TTL 7 days) โ€” ingested in real-time with dedup
  2. Session digests (session_digest atoms, permanent) โ€” auto-created after 30 min of inactivity, extracting user messages
  3. 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 .md mirror 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_embeddings tool 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_to bonds
  • 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

PassWhat it does
body_compactGenerates extractive summaries for long atoms (>1200 chars)
bond_passSuggests/creates rule-based bonds across active atoms
promotionDetects recurring session/daily concepts worth promoting to durable facts
mergeFlags potential duplicates by normalized title
isolated_classificationClassifies atoms without bonds into actionable states

Isolated Atom States

When curator_run runs, atoms without bonds are classified:

StateMeaning
needs_linkDurable, high-weight or frequently accessed โ€” should be connected
standalone_okNaturally standalone (preferences, explicitly allowed)
volatile_candidateSession/chat material or too new โ€” let TTL/digest handle it
archive_candidateOld, 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_run no longer generates graph_gap pending questions by default. Isolated-atom review is handled entirely by the curator. Set learning.graph_gap_enabled=true in 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

SectionWhat it controls
decayInterval, decay factor, critical threshold, archive timeout
rankingFTS, semantic, confidence, recency, and weight balance
ollamaEmbedding model, host, dimensions, reindex settings
auto_bondSemantic threshold, domain cluster threshold, max suggestions
learningContradiction, merge similarity, gap detection thresholds
session_ttl_daysTTL for session message atoms (default 7)
session_inactive_threshold_minutesInactivity before session digest (default 30)

๐Ÿงฌ How It Differs

Featurememory-graphsqlite-memoryMemory Engine
StorageSQLiteSQLiteSQLite
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 traversalBasicโŒโœ… (depth + relation)
Merge atomsโŒโŒโœ…
TTLโŒโŒโœ…
VersioningโŒโŒโœ…

๐Ÿ“ License

MIT โ€” see LICENSE.


Made with ๐Ÿง  by SimoneB79