InternalsArchitecture

Architecture

Mnemosyne is a memory server for AI agents. Agents write what they learn and ask for it back; the server stores it in Postgres, keeps its history, and ranks it on recall. This page describes how the parts fit together, with links to the code.

It is written for contributors and for people evaluating Mnemosyne. It assumes you know Postgres. For a first run, see the full guide.

Mnemosyne is alpha, on the 3.6.x line, and self-hosted only. The API can still change within 3.x.


1. What Mnemosyne is

The server is the only piece that touches the database. The MCP server, the CLI, the SDKs and the dashboard all talk to it over HTTP with an API key, and the key decides the workspace.

Four operations cover most of the surface:

OperationRouteWhat it does
RememberPOST /rememberWrites a memory with its provenance, confidence and validity period
RecallPOST /recallRanks stored memories against a query
ForgetDELETE /facts/{id}, DELETE /forget/{kind}/{id}Closes the validity period; the row stays as history
SessionPOST /session/start, POST /session/{id}/turn, POST /session/{id}/collapseRecords a conversation and extracts memories from it

What sets it apart from a vector store:

  • Bitemporal. Every kind of memory has validFrom and validTo, so the server can answer what is true now and what was believed at an earlier time.
  • Isolation in the database. Workspace data is protected by row-level security with FORCE, scoped to the workspace of the current transaction.
  • Sensitivity ceiling. Each memory has a sensitivity tier, and a key reads at or below its ceiling. A read above it answers 404, not 403.
  • Your own LLM. Eight providers are supported: OpenAI, Anthropic, Google, Cohere, Mistral, Voyage, AWS Bedrock and Ollama.

2. The bitemporal model

A fact is not a row you overwrite. It carries a validity period:

  • validFrom: when the fact became true.
  • validTo: when it stopped being true. null means it is still valid.

Forgetting a fact sets validTo; it does not delete the row. Correcting a fact (memory_update) closes the original and creates a new one, so the fact id changes and the old statement stays as history. A read with asOf sees the memory as it stood at that instant.

A fact has one of three stored statuses:

Recall returns facts that are active and open. A forgotten fact comes back only when the caller asks for archived rows, and it can be restored with POST /facts/{id}/restore. A merged fact never comes back.

Hard deletion exists as a separate operation (DELETE /facts/{id}/hard) and needs the memory:hard_delete scope.


3. System topology

Mnemosyne is one Postgres database with pgvector, a Redis cache, and a pnpm monorepo of packages. The server exposes REST, gRPC and a WebSocket on the same port.

Packages on npm

Four packages are published. All four are clients: they need a running server.

PackageWhat it is
@mnemo-ai/cliThe mnemo command (49 commands): recall, remember, sessions, keys, export and import, and mnemo install for agent hosts.
@mnemo-ai/mcpMCP server over stdio with 37 tools. It binds no port and calls the server over HTTP.
@mnemo-ai/client-tsTyped HTTP client with no runtime dependencies.
@mnemo-ai/typesShared types and port interfaces. The other three install it for you.

The Python and Go SDKs are in the repository (packages/sdk-python, packages/sdk-go) and install from it. They are not on PyPI and have no Go module tag.

Internal packages

Everything else is marked private and is not on npm. It runs inside the server and migrate images, or is bundled into the CLI.

PackageWhat it is
serverThe Hono HTTP API: OpenAPI 3.1, gRPC, WebSocket, bearer auth, the cron registry.
coreThe engine: the kinds of memory, recall, bitemporal facts, session collapse.
adapter-postgresStorage adapter (Drizzle), the schema and its migrations.
adapter-vectorVector search over pgvector.
adapter-redisCache adapter for Redis or Valkey: the hot tier and sessions.
llm-providersThe eight LLM providers.
adapter-llmA thin wrapper that exposes llm-providers through the engine’s LLM port.
consolidationThe background consolidation worker. See Consolidation.
federationEd25519-signed sync between servers.
pluginsThe plugin runtime and 10 built-in plugins.
cupThe v2 to v3 data migration tool.
dashboardThe Next.js web dashboard, served under /dashboard.
harness, pluginConversation capture behind mnemo install --capture, and the host plugin.
mock-serverAn in-memory mock of the REST API for offline development.

examples/graph-viewer is the only example in the repository. It draws the Memory Graph from GET /graph.

There is no library mode. core cannot be installed from npm, so the way to use Mnemosyne from your own process is to call a running server.


4. Ten kinds of memory

KindTableWhat it holds
factmnemo_factDurable knowledge about a user, an agent or a domain, with confidence and a validity period
decisionmnemo_decisionA decision with its rationale; a later one can supersede it
episodemnemo_episodeA bounded record of a session or event
entitymnemo_entityA person, organization, project, concept or place that other memories mention
strategymnemo_strategyA trigger and action rule of thumb, scored by success and failure
workflowmnemo_workflowA reusable multi-step process
skillmnemo_skillA stored prompt template for a repeatable task
taskmnemo_taskAn action item with a lifecycle and delegation
eventmnemo_eventAn append-only record of something that happened. DELETE /events/{id} answers 409
reasoningmnemo_reasoningA question, its reasoning steps and the conclusion

By default, recall searches fact, decision, strategy, workflow, skill and episode, plus entities. task, event and reasoning are indexed but are returned only when the request lists them in kinds.

Relations between memories live in mnemo_relation, with one of nine verbs: related, compatible, scoped, conflicts_with, supersedes, not_conflict, derived_from, part_of and member_of. Relations that join three or more memories live in mnemo_hyperedge.

Tables that support the pipeline:

  • mnemo_recall_log: one row per served fact. ACT-R activation reads it.
  • mnemo_query_cache: recent query embeddings and their results.
  • mnemo_audit_log: the audit trail, partitioned by month.

5. Multi-tenant isolation

The workspace-scoped mnemo_* tables have row-level security with FORCE, so the policies apply to the table owner too. A row is visible only when its workspace matches the setting of the current transaction. With the setting absent, the policies return no rows.

Each transaction in the storage adapter starts the same way:

SET LOCAL ROLE app_user;
SELECT set_config('app.workspace_id', $1, true);
  1. SET LOCAL ROLE app_user moves the transaction to a role without BYPASSRLS. If the connection cannot assume that role and is itself a superuser or has BYPASSRLS, the adapter refuses to run the query.
  2. set_config(..., true) sets the workspace for this transaction only. It is released on commit or rollback, so it cannot leak to the next request on a pooled connection.

The workspace id comes from the API key. It is never read from the request.

LayerWhat it does
TableRLS with FORCE, scoped by app.workspace_id, failing closed when unset
TransactionRole downgrade to app_user and a transaction-local workspace setting
CredentialAPI keys are stored as a bcrypt hash and an HMAC lookup hash keyed by MNEMO_KEY_PEPPER. The optional scoped scheme (MNEMO_SCOPED_AUTH=1) hashes its own keys with Argon2id, and POST /admin/scoped-keys issues, rotates and revokes them
EncryptionConfidential and restricted text is encrypted per author under MNEMO_MASTER_KEY and opened on every read for a caller allowed the tier. POST /admin/erasure destroys a person’s keys, and their encrypted text then reads [erased]. MNEMO_SENSITIVE_TEXT_TO_PROVIDERS (none, embed or all) decides which external providers get that text in the clear
SensitivityFour tiers: public, internal, confidential, restricted. A read above the key’s ceiling answers 404
ContentPII detection and a poisoning gate on writes (422 poisoning_rejected)
RegionWith MNEMO_REGION set, a workspace is pinned to the region that created it, and calls for it from another region are refused (403 wrong_region)

Two opt-in settings narrow fact reads further, inside a workspace: app.enforce_actor_isolation limits them to one actor and app.enforce_user_isolation to one user. Both are off by default.

The local Docker stack does not isolate workspaces. It connects to Postgres as the database owner, which bypasses row-level security (MNEMO_ALLOW_UNSAFE_DB_ROLE is set to true in docker/docker-compose.override.yml). The production overlay provisions a restricted role and turns isolation on, and the server refuses to start in production with that switch set.

See Security for more.


6. Recall

A recall goes through a cascade. Each step can answer and end the request:

  • Token budget. tokenBudget on the request prunes the cascade: under 500 nothing runs, under 2,000 only the hot tier (3 hits), under 8,000 hot and pointer (5 hits), otherwise the full cascade. Without it, everything runs.
  • Query cache. A query whose embedding has cosine 0.95 or more against one stored in the last 5 minutes reuses that result. It applies only to requests with default options, from a key whose ceiling admits every sensitivity tier.
  • Hot tier. A Redis sorted set of recently active facts. If Redis is down, it counts as a miss.
  • Pointer tier. Full-text and LSH narrowing, then exact cosine. It answers when at least 3 candidates score above 0.7.
  • Cold tier. Seven stages: parse, candidates, relation and hyperedge hints, ACT-R activation, score, sensitivity ceiling, assemble. The score is relevance × kind weight × worth prior, and activation only breaks ties (at most ×1.02).

HyDE and an LLM rerank are opt-in; no rerank runs by default. If the embedding provider does not answer, recall falls back to full-text search, except in semantic mode, which answers 503. A request with asOf skips the query cache and the hot and pointer tiers: only the cold tier can read a past instant.

The stages are described in Recall pipeline.

A pinned fact is never consolidated. Pinning gives no ranking boost in recall today.


7. The Memory Graph

Entities, episodes and decisions are connected by typed relations that carry a confidence and a provenance. The server returns that graph at GET /graph: canonical entities, non-synthetic episodes, active decisions, and the open relations that were not dismissed. Nodes above the caller’s sensitivity ceiling are omitted with their edges.

GET /graph/traverse walks the graph from a root node and GET /graph/path finds the shortest path between two nodes.

The data contract and rendering recipes are in Rendering the Memory Graph.


8. LLM providers

The server reads its providers from the environment:

MNEMO_LLM_PROVIDER=anthropic
MNEMO_LLM_API_KEY=...
MNEMO_EMBED_PROVIDER=openai
MNEMO_EMBED_API_KEY=...
MNEMO_EMBED_MODEL=text-embedding-3-small

Supported values are openai, anthropic, google, cohere, mistral, voyage, bedrock and ollama. The completion provider and the embedding provider can differ. A workspace can override the server’s configuration with PUT /config/llm.

Every provider implements one interface, in packages/llm-providers:

interface LLMProvider {
  readonly name: string;
  readonly capabilities: LLMCapabilities;
  readonly defaultCompleteModel?: string;
  embed?(input: EmbedRequest): Promise<EmbedResponse>;
  complete?(input: CompleteRequest): Promise<CompleteResponse>;
}

Both methods are optional because some providers only embed and some only complete.

The embedding dimension follows the model (1024, 1536 and others), and each dimension has its own HNSW index. It is detected from the model; MNEMO_EMBED_DIMENSIONS sets it explicitly.

What needs an LLM: session collapse and extraction, the optional rerank, and replay validation in consolidation. What needs embeddings: semantic recall. Without embeddings, recall uses full-text search.

With MNEMO_LLM_DAILY_BUDGET_USD set, the server routes its completions through the BudgetGuard of llm-providers, a daily USD cap kept in memory per process; embeddings are not capped (see Cost control). When MNEMO_LLM_JUDGE_*, _SUMMARY_* or _PREFILTER_* is set, the server builds the LLMRouter of the same package before the cap: every engine completion declares its task (judge, summary, prefilter or default) and goes to that task’s provider, and the cap counts all of them.


9. HTTP API

The server registers 202 routes. They are mounted at the root: there is no /v1 prefix. Requests carry Authorization: Bearer mns_live_..., and the server resolves the workspace from the key. gRPC (ConnectRPC, under /mnemosyne.v1.MnemosyneService/) and the WebSocket (/memory/ws) share the same port, 3939 by default.

A slice of the surface:

GroupRoutes
Remember and recallPOST /remember, POST /recall, POST /recall/hot, POST /recall/explain
FactsGET /facts, GET, PATCH and DELETE /facts/{id}, POST /facts/{id}/pin, POST /facts/{id}/restore, GET /facts/{id}/citations
ForgetDELETE /forget/{kind}/{id}
EntitiesGET and POST /entities, GET and PATCH /entities/{id}, GET /entities/{id}/facts
EpisodesGET and POST /episodes, GET /episodes/{id}, GET /episodes/{id}/timeline
DecisionsGET and POST /decisions, GET and PATCH /decisions/{id}
RelationsGET and POST /relations, PATCH and DELETE /relations/{id}, POST /relations/traverse
HyperedgesGET and POST /hyperedges, GET, PATCH and DELETE /hyperedges/{id}
SessionsPOST /session/start, POST /session/{id}/turn, POST /session/{id}/collapse, POST /session/{id}/discard, GET /session/{id}
SelfPOST /self/edit, POST /self/reflect, GET /self/profile
Tasks, events, reasoning/tasks, /events, /reasoning with their /{id} routes
Strategies, workflows, skills/strategies, /workflows, /skills with their /{id} routes
GraphGET /graph, GET /graph/traverse, GET /graph/path, GET /graph/stats
Review and conflictsGET /review, POST /review/{id}/resolve, GET /conflicts, POST /conflicts/{id}/resolve
Timeline and auditGET /timeline, GET /audit
Federation/memory/federation/* (10 routes)
Agent policiesGET /admin/agent-policies, GET, PUT and DELETE /admin/agent-policy
Export and importGET and POST /export, GET /export/jsonl, POST /import
Webhooks/webhooks with their /{id} routes
HealthGET /health (authenticated), GET /health/ready, GET /health/live

There is no POST /facts: facts are created with POST /remember.

The OpenAPI 3.1 document is served at /openapi.json and needs a bearer key. A Scalar reference UI is served at /docs.

Errors

A failed request returns a JSON body with one error object:

{
  "error": {
    "type": "not_found_error",
    "code": "not_found",
    "message": "Fact not found",
    "request_id": "...",
    "retryable": false
  }
}

code is a stable snake_case string. Branch on it, not on the message.

Statuscode
400bad_request
401unauthorized
403forbidden
404not_found
409conflict
422unprocessable_entity, poisoning_rejected
429rate_limited
500internal_error
501not_implemented
503service_unavailable, semantic_search_unavailable

retryable is true for 429 and 503. Some routes use more specific codes; see Errors.


10. MCP

@mnemo-ai/mcp exposes the server as 37 MCP tools:

GroupTools
Read and writememory_recall, memory_search, memory_remember, memory_update, memory_fact, memory_forget, memory_pin, memory_timeline, memory_suggest_topic_key
Graphmemory_relate, memory_entity, memory_hyperedge, memory_compare, memory_judge
Decisionsmemory_decide
Sessionsmemory_session, memory_episode_start, memory_episode_end, memory_context
Workmemory_task, memory_event, memory_workflow, memory_skill, memory_strategy
Reasoningmemory_reasoning, memory_self_edit, memory_introspect
Inferencememory_anticipate, memory_compose
Maintenancememory_consolidate, memory_remind_when, memory_relocate, memory_purge
Statusmemory_status, memory_stats, memory_doctor, memory_workspace

The transport is stdio only. The MCP server holds no data: each tool call is an HTTP request to the server with the key from MNEMO_KEY, so scoping and isolation are the same as for REST.


11. Background jobs

The server runs its jobs from a registry in packages/server/src/cron/jobs.ts. A job that throws does not stop the schedule. Schedules are in UTC. Some of them:

Job keySchedulePurpose
mnemo.session.collapseevery 5 minutesCollapses inactive sessions
mnemo.webhook.deliverevery minuteDelivers webhooks, with retries
mnemo.querycache.evicthourlyTrims mnemo_query_cache
mnemo.hot.decayhourlyLowers every hot tier score by one
mnemo.policy.change.purgehourlyTrims the agent policy change log the replicas poll
mnemo.retention.purgedaily, 02:30Closes facts past the retention window of their sensitivity tier
mnemo.reasoning.decaydaily, 03:00Decay for reasoning records
mnemo.semantic.decaydaily, 03:15Decay for facts
mnemo.procedural.decaydaily, 03:30Decay for strategies, workflows and skills
mnemo.hot.rebuilddaily, 04:00Re-seeds the hot tier from the facts with the highest worth
mnemo.anticipate.minedaily, 06:30Refreshes the anticipation views
mnemo.metacognition.refreshdaily, 07:00Refreshes the metacognition views
mnemo.task.staledaily, 08:00Sends tasks inactive for more than 14 days to the review queue

Each plugin that implements sync gets its own job, mnemo.plugin.sync:<id>, and mnemo.plugin.verify runs the plugins’ verify once a day.

With several replicas, each tick of a job that touches the shared database or Redis runs on one replica only, the one that takes a Postgres advisory lock for it. Only mnemo.meter.persist runs on every replica.

MNEMO_CRON_DISABLE takes a comma-separated list of job keys to turn off.

Consolidation is not in this registry. It has its own scheduler, which ticks every 60 seconds.


12. Deployment

No Docker image is published. The stack is built with docker compose from the repository’s docker/ folder:

git clone https://github.com/lucasmailland/mnemosyne
cd mnemosyne/docker
cp .env.example .env
echo "MNEMO_DASHBOARD_SECRET=$(openssl rand -hex 32)" >> .env
docker compose up -d

docker/docker-compose.yml defines five services:

postgres   pgvector/pgvector:pg17
redis      redis:7-alpine
migrate    one-shot job, built from docker/Dockerfile.migrate
server     built from docker/Dockerfile.server, host port 3939
ollama     local embeddings and LLM

The migrate service must finish before the server starts. The schema is never created by the server on boot. There are 70 v3 migrations in packages/adapter-postgres/migrations/baseline/, plus the 40-file v2 stream.

The server is ready when curl http://localhost:3939/health/ready reports every check as ok.

For production there is an overlay, docker/docker-compose.prod.yml. It adds pgBouncer, a restricted database role, a password-protected Redis and the dashboard container, and it refuses to start without its secrets. To use a managed Postgres, point DATABASE_URL at it; pgvector must be installed there.

The server is stateless and can run as several replicas (MNEMO_SERVER_REPLICAS). A fly.toml and a Railway config (deploy/railway.json) are in the repository; nothing is deployed from it.

There is no CI: GitHub Actions is off. The release gate is FULL=1 bash scripts/full-sweep.sh, run locally.


13. Load-bearing decisions

DecisionWhy
Postgres only, no separate vector databaseA memory and its vector live in the same row, so a write and its searchability are one transaction.
Validity period on every kind of memoryTime-travel reads need no event log. Forgetting is an update, not a delete.
RLS with FORCE and a role downgradeA query that forgets to filter by workspace still cannot read another tenant’s rows.
halfvec embeddings, one HNSW index per dimensionHalf the storage of vector, and a workspace can change embedding model without a schema change.
Relevance decides the rankingActivation and worth are bounded priors. An earlier blend gave 40% of the score to recency of recall, and unrelated memories outranked relevant ones.
No LLM on the default recall pathThe rerank is opt-in, because by default it added seconds per recall with a local model.
The server is the only thing that touches the databaseClients hold an API key, not database credentials.
MCP as a thin clientThe MCP server only adapts the HTTP API, so it cannot drift from it.

14. Further reading