LLMs Technical Reviews

How is memory and user context stored and retrieved?

Storage (DB, vector store, files); what is remembered; how it is injected into prompts; summarization.

Verdict

Leon has the most developed general memory, and Khoj is best for answering from your own documents. Waku has the cleanest small design. The approaches range from Markdown files placed in the prompt to scored database records.

Curated Markdown in the prompt. Hermes Agent keeps MEMORY.md (2,200 characters) and USER.md (1,375), frozen at session start to protect the prompt cache. A background review saves new facts every 10 user turns, not after each turn as its answer first said. QM keeps a MEMORY.md per scope, with Postgres revisions, and recalls only its last 6,000 characters. The editor confirmed that extraction waits for 3 quiet minutes or 10 turns. There are no embeddings. OpenClaw indexes workspace MEMORY.md with full-text search plus embeddings (OpenAI by default), and auto-injects only owner- or agent-originated entries.

Scored records with search. Leon stores items as persistent, daily or discussion, with importance, expiry and pins. It recalls them with hybrid lexical and vector search, weighted 1.35 for persistent items and 0.65 for discussion. Khoj extracts facts after every turn into pgvector and recalls the last 7 days plus semantic matches. Users can edit them through /api/memories. Waku puts a small-model gate in front of SQLite FTS5 and consolidates every 6 exchanges. Inbox Zero keeps plain Postgres rows. The editor found that ReplyMemory, learned from your edits to drafts, also shapes future replies.

Session or platform memory. Rakazo keeps versioned Markdown documents and compacts old history into a summary. Semantic recall returns at most 5 items, and only after compaction. OpenBot injects confirmed personal facts from Postgres, but threads and learned skills live in CopilotKit Intelligence. Agenvoy has no user fact store: only session summaries and tool-error records, and vector search needs an OpenAI key.

Pick: Khoj to search notes and documents. Pick: Leon or Waku for a personal assistant that learns preferences. Pick: QM for memory that must stay separate per person and channel.

Per-project answers

openclaw/openclaw

answered

Storage. Memory lives in two layers. First, markdown files in the workspace (MEMORY.md as the canonical root memory file — see src/memory/root-memory-files.ts:6). Second, a SQLite database with full-text search (FTS) and optional vector embeddings via sqlite-vec or remote embedding APIs. The core engine is in packages/memory-host-sdk/ with separate module files for storage (engine-storage.ts), embeddings (engine-embeddings.ts), session recall (engine-sessions.ts), and foundation (engine-foundation.ts). Embedding vectors are stored in SQLite with sqlite-vec. The default embedding provider is OpenAI (DEFAULT_MEMORY_EMBEDDING_PROVIDER = "openai" in src/agents/memory-search.ts:70).

What is remembered. Session transcripts, user-authored memory files, and agent-written memory entries. Each entry carries provenance metadata (MemoryEntryProvenance with originClass, sessionKind, observedAt in packages/memory-host-sdk/src/host/types.ts:13). Provenance classes (owner, agent, untrusted, system) determine eligibility for automatic prompt injection — only owner and agent origins qualify (types.ts:41).

Injected into prompts. src/agents/memory-prompt-prepare.ts:8 calls prepareMemoryPromptSection from src/plugins/memory-state.ts which builds a PreparedMemoryPromptSection containing ranked search results with scores, snippets, and scores for relevance. This prompt section is injected into the LLM context.

Summarization. The memory host SDK includes consolidation/dreaming — packages/memory-host-sdk/src/host/curated-annotations.ts handles curated annotations. The memory-host-sdk/dreaming.ts module hints at consolidation processes that summarize or compact memory over time. Memory sync (MemorySyncParams in types.ts:79) supports forced refresh of session transcripts and archive files with progress tracking.

NousResearch/hermes-agent

answered

Storage: The primary store is SQLite in WAL mode (hermes_state.py). It stores session metadata, message history, model config, usage tracking, and FTS5-indexed messages. Memory also lives on disk as MEMORY.md (agent-curated notes) and USER.md (user profile) under ~/.hermes/memories/, managed by the memory tool (tools/memory_tool.py:1-6). FTS5 full-text search across sessions is provided by hermes_state_fts.py.

What is remembered: Three tiers — (1) Session history: every message in the current conversation (SQLite, per-session rows), searchable across sessions via /session_search. (2) Curated memory: the memory tool writes structured entries to MEMORY.md/USER.md (add, replace, remove, batch operations). These are FROZEN into the system prompt snapshot at session start. (3) Background review: after each turn, a background thread (background_review.py) evaluates if new information should be persisted as memory or skills, using an LLM review prompted with _MEMORY_REVIEW_PROMPT (run_agent.py:785-786).

Injection into prompts: The MemoryProvider abstract base (agent/memory_provider.py:84) defines prefetch() (recall context for the upcoming turn), queue_prefetch() (queues background recall), system_prompt_block() (static instruction text), and sync_turn() (persists a completed turn). The built-in provider reads memory files for the system prompt; external plugins (Honcho, etc.) can replace this via memory.provider config.

Summarization: Compression (context_compressor.py, conversation_compression.py) runs mid-session and at compression boundaries, summarizing older history to keep the prompt under context limits. The on_pre_compress() hook on MemoryProvider lets providers extract insights before compression (memory_provider.py:176-177).

khoj-ai/khoj

answered

Khoj has three memory layers, all stored in PostgreSQL with pgvector for vector embeddings:

1. Conversation history. Chat sessions are stored as JSON blobs in Conversation.conversation_log (a Django JSONField). Each user message and assistant response is saved via save_to_conversation_log() in processor/conversation/utils.py. Messages include references, online results, code context, operator trajectories, images, and thoughts — everything needed to reconstruct the agent's full state. Conversations are keyed per user and optionally per client application. The generate_chatml_messages_with_context() function reconstructs the prompt by reading the last N messages, truncating oldest ones to fit the model's context window.

2. User content (notes/docs). User-uploaded files (markdown, org-mode, plaintext, PDF, images, DOCX) are ingested by content processors in processor/content/. Each file is chunked into Entry objects with a vector embedding (pgvector VectorField), raw text, compiled text, heading, and file metadata. When the user asks /notes, semantic search is run against these entries using cosine distance via EntryAdapters.

3. Long-term memories (UserMemory). UserMemory is a vector-indexed store derived automatically from conversations. After every chat turn, ai_update_memories() (in helpers.py) calls the LLM to extract new facts from the conversation and saves them via UserMemoryAdapters.save_memory(). Two retrieval modes exist: pull_memories() (recent, time-windowed — "medium term") and search_memories() (semantic vector search — "long term"). Memories are injected into the chat prompt as a special <retrieved_memories> block right before the user's query.

Memory configuration. Server admins can disable memory entirely (ServerChatSettings.memory_mode = DISABLED) or set defaults on/off. Users can toggle it in UserConversationConfig.enable_memory.

Memories are accessible and editable via the /api/memories REST endpoints (list, update, delete).

leon-ai/leon

answered

Leon's memory is layered into three scopes — persistent, daily, and discussion — plus context files as a separate grounding source. Core storage is SQLite via better-sqlite3 using the schema at server/src/core/memory-manager/sql/schema.sql: memory_items table stores records (lines 1–26) with fields like scope, kind (fact, preference, event, summary, etc.), content_md, importance (0–1), confidence, expires_at, and is_pinned. Chunks are stored in memory_chunks with FTS5 full-text search and optional embeddings. On top of SQLite, QMD (@tobilu/qmd package) provides retrieval via server/src/core/memory-manager/qmd-backend.ts (lines 37–55): content is mirrored into QMD collections, searched with hybrid (lexical + vector) retrieval, and reranked by namespace weight (memory_persistent gets 1.35, discussion gets 0.65). The flow in memory-manager.ts (lines 142–167): recall starts with QMD retrieval for the top-K chunks (default 12), then may run adaptive second passes if results are weak. Extracted durable facts use an LLM schema (EXTRACT_PERSISTENT_MEMORY_SCHEMA, lines 58–75). Memory is injected into prompts via renderRecallPrompt() which formats as "Memory Recall:" with facts and relevant chunks — this string is added to the agent's system prompt context (memory-manager.ts, lines 142–167). Turn observations feed daily and discussion memory automatically via MemoryManager.observeTurn(). Summarization happens through summarizer.ts for daily markdown summaries. Older short-term content is compacted and pruned based on TTLs (5 days for discussion, 30 days active retention, 180 days cold archive). The SelfModelManager (server/src/core/self-model-manager.ts, lines 1–60) distills repeated patterns into behavioral principles from conversation digests, injected as a compact snapshot. Context files (under server/src/core/context-manager/context-files/) are a separate system: files like ACTIVITY.md, HOST_SYSTEM.md, GPU_COMPUTE.md, and HOME.md are refreshed periodically and read via structured_knowledge tools to ground environment-aware answers.

yc-software/qm

answered

Memory is per-scope (personal, channel, team, org) and stored as a sequence of Markdown bullet points in a write-ahead revision log in Postgres (src/memory/postgres-memory-service.ts). Each scope has a MEMORY.md file (path constant memory/MEMORY.md in src/memory/memory-service.ts:17) rendered as an append-only series of dated bullet facts. The revision table (memory_revisions) tracks scope_id, seq, op, body, author, and at timestamp. On each turn, the orchestrator calls memory.recall(scopeId), which appends the last 6,000 chars of memory into the system prompt (src/memory/notebook.ts:1 — RECALL_MAX_CHARS = 6_000). Memory extraction happens automatically after each turn via the per-turn strategy (src/memory/strategies/per-turn.ts), which uses a one-shot model call to extract durable facts from the last conversation exchange. Facts are deduplicated and appended. The system supports multiple memory backends via a provider router (src/memory/provider-router.ts), which can route by scope kind to different providers: Postgres built-in, MCP-based memory providers, or "Memorable" procedural memory (src/memory/memorable/). The config surface is at src/memory/provider-config.ts. Recall is trimmed via capTail to the character limit; there is no vector store for retrieval — it's a flat tail-of-history capture. Context boundaries (src/memory/context-boundary.ts) track which entries the current memory snapshot covers to avoid double-injection. Context compaction (src/harness/context-compaction.ts) and summarization (src/sessions/session-store.ts:39 with ContextSummaryPayload) handle prompt length.

Editor's note. Correction: the default per-turn strategy does not extract after every exchange; it buffers a burst and extracts after 180 s of quiet or 10 turns (per-turn.ts L14-L15, L88-L140). Recalled memory is injected as a delta into the turn's environment note, not appended to the system prompt (orchestrator.ts L3560-L3563).

elie222/inbox-zero

answered

Database storage. Memories are stored in the ChatMemory PostgreSQL table (apps/web/prisma/schema.prisma:1401-1414), keyed by emailAccountId with an optional chatId link. The schema stores: content (the memory text), createdAt, updatedAt. There is no vector store — memory search uses PostgreSQL CONTAINS with case-insensitive matching on the content field (apps/web/utils/ai/assistant/chat-memory-tools.ts:35-48). A query of empty string returns the 10 most recent memories.

What is remembered. The LLM is prompted to save explicit user preferences and facts stated in chat. Two sources exist: user_message (user directly states a fact) and assistant_inference (model infers from context). The saveMemoryTool (apps/web/utils/ai/assistant/chat-memory-tools.ts:125-219) validates that user_message sources have matching evidence quotes from conversation history, enforced by validateUserMemoryEvidence (apps/web/utils/ai/assistant/chat-memory-policy.ts:5-78). Inferred memories (assistant_inference) require UI confirmation before being persisted. Memories are not applied to email processing rules — only assistant chat conversations.

Prompt injection. At the start of each chat turn, the route loads up to 20 recent memories (apps/web/app/api/chat/route.ts:265-278) and passes them into the system context as "Memories from previous conversations: [date] content" (apps/web/utils/ai/assistant/chat.ts:254-261). The LLM can also call searchMemoriesTool dynamically to recall specific facts.

Summarization/compaction. When a conversation exceeds ~8K tokens, compactMessages (apps/web/utils/ai/assistant/compact.ts:63) uses the LLM to summarize the history into a single text message. The compaction summary is stored in ChatCompaction (apps/web/prisma/schema.prisma:1387-1399) and injected as a system message in future turns. Compaction also triggers extractMemories (apps/web/utils/ai/assistant/compact.ts:152) which calls the LLM to identify and save durable facts from the conversation history as ChatMemory records.

Editor's note. Correction: memory also shapes email processing. ReplyMemory records (facts, preferences, procedures) are learned from how the user edits AI drafts before sending and are selected into future reply drafts, together with a learned writing style (apps/web/utils/ai/reply/reply-memory.ts).

CopilotKit/OpenBot

answered

Storage — PostgreSQL. Personal memories live in the personalMemories table in PostgreSQL, accessed through Drizzle ORM (server/src/db/schema/memory). The memory store (server/src/memory/store.ts:16-80) provides CRUD operations: list (up to 500, newest-first), create, formMemory (Bot-observed facts awaiting human review), update, remove. Deduplication uses a SHA-256 hash of lowercased content (deleted memories stay forgotten).

Memory types. Personal memories are free-text records with optional sourceApp and sourceLink. Bot-formed memories (formMemory) are observed facts the person can confirm or dismiss. A MemorySource records where imported data came from (a connected app). Memory import from connected apps is handled by normalizeConnectorRecords (server/src/memory/ingestion.ts:16-80) which parses JSON responses from external services (searching items, files, or results keys), normalizes records to text, and caps at 50 records or 256KB.

Injection into prompts. The PersonalMemoryMiddleware (server/src/memory/tools.ts:29-70) is an AG-UI Middleware that injects the person's memories as both a system message and a context entry on every agent run. The system message id is "openbot:personal-memory" — the middleware also deduplicates stale ones. Memory content is loaded asynchronously and injected before the run begins.

Learning (skills). ``CopilotKit Intelligence's Learning system (server/src/learning/runtime.ts:1-35) provides learned skills — reusable capabilities published from observed patterns. The runtime exposes copilotkit_load_skill and copilotkit_read_skill_file tools to agents, backed by CopilotKit Intelligence. A RemoteLearnedSkillsMiddleware injects learned skill context into agent runs. Learning targets are per-agent or default, configured through admin settings (server/src/learning/settings.ts).

elie222/rakazo

answered

Storage layers. Rakazo has three memory systems:

  1. Conversation history — stored as Message rows in PostgreSQL (packages/db/src/messages.ts), scoped to a thread. Each message has blocks (text, tool calls, images) and a sequential seq. To manage context windows, history is compacted asynchronously via packages/adapters/src/history-compaction.ts: messages beyond a sliding window of 50 are removed and replaced with an LLM-generated summary stored in thread.historyCompactionSummary. Compaction is triggered when the uncompacted window exceeds the batch size threshold (shouldEnqueueCompaction, line 20). The summary is injected as a user-role message in subsequent runs (line 6047-6054 of executor.ts).

  2. Markdown memory store (packages/memory/src/index.ts — MarkdownMemoryStore): a user-and-bot-scoped key-value store for structured facts. Implements the MemoryStore interface from @rakazo/adapter-kit. Documents are stored in memoryDocument and memoryRevision tables. Supports read (list docs by scope/path), commit (upsert with optimistic concurrency via revision numbers), and search (simple substring match on content/path). The agent calls remember/recall_memory tools to write/read from this store. It uses Prisma transactions with Serializable isolation (line 117).

  3. Semantic (vector) memory — optional providers accessed via SpaceMemoryProviderResolver (packages/adapters/src/memory-provider-factory.ts). Supports Serenity (a self-hostable vector memory service) and Supermemory (external SaaS). These providers expose recall(), save(), and forget() operations for semantic similarity search. The memory scope (isolated vs shared, resolved in packages/db/src/memory-config.ts) controls whether a bot sees only its own memories or the whole space's.

Injection into prompts. At run start, the executor calls semanticMemory.recall() (line 3459 of executor.ts) with the user's prompt as query, getting up to 5 relevant memories. The recalled text is formatted and injected into the prompt's historicalContext array (line 6056-6060). Similarly, compacted history summaries are injected as a synthetic user message. All memory content passes through redactSecrets() before injection.

ShenSeanChen/waku-agent

answered

Memory is three pillars managed by waku/memory/init.py (Memory class). Semantic memory (facts) and episodic memory (dated events) live in state.db, a single SQLite file with FTS5 search (schema in waku/db.py). Procedural memory is SKILL.md files loaded via SkillLoader. The retrieval gate (waku/memory/retrieval_gate.py) is the hero pattern: a cheap model decides if memory is needed before touching any store. If yes, the semantic store is searched for top-k facts and episodic store for top 3 episodes. Semantic storage can be swapped from SQLite+FTS5 to Supabase pgvector, Mem0, Zep, or LangMem via WAKU_SEMANTIC_STORE. Episodic storage can switch to Notion. Consolidation (waku/memory/consolidation.py) is batched: after every N exchanges (default 6), a cheap model distills unconsolidated chat_log rows into semantic facts and an episodic summary. Operating state (balances, credits, errors) is filtered by is_ops_state(). Memory is injected into the system prompt in Session.build_system(). Read memory passes as recalled so same facts are not stored again. An optional Jev slot gate (waku/memory/slot_gate.py) scores each fact.

agenvoy/Agenvoy

answered

Agenvoy uses a multi-layered memory system. Persistent storage uses two backends: SQLite (via go-sqlkit) for structured data — session messages (store/migrate.sql creates messages, session, file_history, action_history tables with FTS5 full-text search), and ToriiDB (an embedded vector database) for tool cache, session history, error memory, and online markers (torii/torii.go defines four DBs: DBToolCache, DBSessionHist, DBErrorMemory, DBOnline). Tool error memory (internal/agents/exec/memory/) stores structured Record entries with tool name, symptom, cause, action, outcome, and keywords. Records are persisted via torii.DB(DBErrorMemory).SetVector() with vector embeddings for semantic search. On tool failure, memory.Search() is called to find up to 16 related past errors by vector similarity or keyword scan. Session conversation memory uses summarization: every 15 minutes a system cron runs app.GenerateSummary (internal/agents/exec/summary/generate.go::Generate()), which chunks new session history records, sends them to the summary model with a prompt (configs.SummaryPrompt), and stores a JSON summary dictionary per session in ~/.config/agenvoy/sessions/<id>/summary.json. Context injection happens in systemPrompt.go — the getSystemPrompt() function builds the full system prompt by templating {{.AvailableSkills}}, {{.OfficialGuide}} (model-specific capability docs), {{.PermissionMode}}, {{.GuardrailRules}}, {{.BotPersona}}, and agent guide files (CLAUDE.md/AGENTS.md). The compact/ package handles prompt assembly: AssembleMessages() builds the message array from system prompts, summary message, old histories, user input, and tool histories. Context window management is handled by compact.CheckThreshold() with an 80% ratio trigger, and compact.ExtractOldHistories() moves older messages into a compacted summary when token limits approach.

← How are integrations (email, calendar, chat, docs) implemented? · How are actions on the user's behalf gated? →