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:
| Operation | Route | What it does |
|---|---|---|
| Remember | POST /remember | Writes a memory with its provenance, confidence and validity period |
| Recall | POST /recall | Ranks stored memories against a query |
| Forget | DELETE /facts/{id}, DELETE /forget/{kind}/{id} | Closes the validity period; the row stays as history |
| Session | POST /session/start, POST /session/{id}/turn, POST /session/{id}/collapse | Records a conversation and extracts memories from it |
What sets it apart from a vector store:
- Bitemporal. Every kind of memory has
validFromandvalidTo, 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.nullmeans 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.
| Package | What it is |
|---|---|
@mnemo-ai/cli | The mnemo command (49 commands): recall, remember, sessions, keys, export and import, and mnemo install for agent hosts. |
@mnemo-ai/mcp | MCP server over stdio with 37 tools. It binds no port and calls the server over HTTP. |
@mnemo-ai/client-ts | Typed HTTP client with no runtime dependencies. |
@mnemo-ai/types | Shared 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.
| Package | What it is |
|---|---|
server | The Hono HTTP API: OpenAPI 3.1, gRPC, WebSocket, bearer auth, the cron registry. |
core | The engine: the kinds of memory, recall, bitemporal facts, session collapse. |
adapter-postgres | Storage adapter (Drizzle), the schema and its migrations. |
adapter-vector | Vector search over pgvector. |
adapter-redis | Cache adapter for Redis or Valkey: the hot tier and sessions. |
llm-providers | The eight LLM providers. |
adapter-llm | A thin wrapper that exposes llm-providers through the engine’s LLM port. |
consolidation | The background consolidation worker. See Consolidation. |
federation | Ed25519-signed sync between servers. |
plugins | The plugin runtime and 10 built-in plugins. |
cup | The v2 to v3 data migration tool. |
dashboard | The Next.js web dashboard, served under /dashboard. |
harness, plugin | Conversation capture behind mnemo install --capture, and the host plugin. |
mock-server | An 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
| Kind | Table | What it holds |
|---|---|---|
fact | mnemo_fact | Durable knowledge about a user, an agent or a domain, with confidence and a validity period |
decision | mnemo_decision | A decision with its rationale; a later one can supersede it |
episode | mnemo_episode | A bounded record of a session or event |
entity | mnemo_entity | A person, organization, project, concept or place that other memories mention |
strategy | mnemo_strategy | A trigger and action rule of thumb, scored by success and failure |
workflow | mnemo_workflow | A reusable multi-step process |
skill | mnemo_skill | A stored prompt template for a repeatable task |
task | mnemo_task | An action item with a lifecycle and delegation |
event | mnemo_event | An append-only record of something that happened. DELETE /events/{id} answers 409 |
reasoning | mnemo_reasoning | A 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);SET LOCAL ROLE app_usermoves the transaction to a role withoutBYPASSRLS. If the connection cannot assume that role and is itself a superuser or hasBYPASSRLS, the adapter refuses to run the query.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.
| Layer | What it does |
|---|---|
| Table | RLS with FORCE, scoped by app.workspace_id, failing closed when unset |
| Transaction | Role downgrade to app_user and a transaction-local workspace setting |
| Credential | API 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 |
| Encryption | Confidential 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 |
| Sensitivity | Four tiers: public, internal, confidential, restricted. A read above the key’s ceiling answers 404 |
| Content | PII detection and a poisoning gate on writes (422 poisoning_rejected) |
| Region | With 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.
tokenBudgeton 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-smallSupported 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:
| Group | Routes |
|---|---|
| Remember and recall | POST /remember, POST /recall, POST /recall/hot, POST /recall/explain |
| Facts | GET /facts, GET, PATCH and DELETE /facts/{id}, POST /facts/{id}/pin, POST /facts/{id}/restore, GET /facts/{id}/citations |
| Forget | DELETE /forget/{kind}/{id} |
| Entities | GET and POST /entities, GET and PATCH /entities/{id}, GET /entities/{id}/facts |
| Episodes | GET and POST /episodes, GET /episodes/{id}, GET /episodes/{id}/timeline |
| Decisions | GET and POST /decisions, GET and PATCH /decisions/{id} |
| Relations | GET and POST /relations, PATCH and DELETE /relations/{id}, POST /relations/traverse |
| Hyperedges | GET and POST /hyperedges, GET, PATCH and DELETE /hyperedges/{id} |
| Sessions | POST /session/start, POST /session/{id}/turn, POST /session/{id}/collapse, POST /session/{id}/discard, GET /session/{id} |
| Self | POST /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 |
| Graph | GET /graph, GET /graph/traverse, GET /graph/path, GET /graph/stats |
| Review and conflicts | GET /review, POST /review/{id}/resolve, GET /conflicts, POST /conflicts/{id}/resolve |
| Timeline and audit | GET /timeline, GET /audit |
| Federation | /memory/federation/* (10 routes) |
| Agent policies | GET /admin/agent-policies, GET, PUT and DELETE /admin/agent-policy |
| Export and import | GET and POST /export, GET /export/jsonl, POST /import |
| Webhooks | /webhooks with their /{id} routes |
| Health | GET /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.
| Status | code |
|---|---|
| 400 | bad_request |
| 401 | unauthorized |
| 403 | forbidden |
| 404 | not_found |
| 409 | conflict |
| 422 | unprocessable_entity, poisoning_rejected |
| 429 | rate_limited |
| 500 | internal_error |
| 501 | not_implemented |
| 503 | service_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:
| Group | Tools |
|---|---|
| Read and write | memory_recall, memory_search, memory_remember, memory_update, memory_fact, memory_forget, memory_pin, memory_timeline, memory_suggest_topic_key |
| Graph | memory_relate, memory_entity, memory_hyperedge, memory_compare, memory_judge |
| Decisions | memory_decide |
| Sessions | memory_session, memory_episode_start, memory_episode_end, memory_context |
| Work | memory_task, memory_event, memory_workflow, memory_skill, memory_strategy |
| Reasoning | memory_reasoning, memory_self_edit, memory_introspect |
| Inference | memory_anticipate, memory_compose |
| Maintenance | memory_consolidate, memory_remind_when, memory_relocate, memory_purge |
| Status | memory_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 key | Schedule | Purpose |
|---|---|---|
mnemo.session.collapse | every 5 minutes | Collapses inactive sessions |
mnemo.webhook.deliver | every minute | Delivers webhooks, with retries |
mnemo.querycache.evict | hourly | Trims mnemo_query_cache |
mnemo.hot.decay | hourly | Lowers every hot tier score by one |
mnemo.policy.change.purge | hourly | Trims the agent policy change log the replicas poll |
mnemo.retention.purge | daily, 02:30 | Closes facts past the retention window of their sensitivity tier |
mnemo.reasoning.decay | daily, 03:00 | Decay for reasoning records |
mnemo.semantic.decay | daily, 03:15 | Decay for facts |
mnemo.procedural.decay | daily, 03:30 | Decay for strategies, workflows and skills |
mnemo.hot.rebuild | daily, 04:00 | Re-seeds the hot tier from the facts with the highest worth |
mnemo.anticipate.mine | daily, 06:30 | Refreshes the anticipation views |
mnemo.metacognition.refresh | daily, 07:00 | Refreshes the metacognition views |
mnemo.task.stale | daily, 08:00 | Sends 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 -ddocker/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 LLMThe 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
| Decision | Why |
|---|---|
| Postgres only, no separate vector database | A memory and its vector live in the same row, so a write and its searchability are one transaction. |
| Validity period on every kind of memory | Time-travel reads need no event log. Forgetting is an update, not a delete. |
RLS with FORCE and a role downgrade | A query that forgets to filter by workspace still cannot read another tenant’s rows. |
halfvec embeddings, one HNSW index per dimension | Half the storage of vector, and a workspace can change embedding model without a schema change. |
| Relevance decides the ranking | Activation 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 path | The 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 database | Clients hold an API key, not database credentials. |
| MCP as a thin client | The MCP server only adapts the HTTP API, so it cannot drift from it. |
14. Further reading
- Full guide: from an empty database to the first recall.
- Recall pipeline: the seven stages of the cold tier.
- Consolidation: the background merge worker.
- Rendering the Memory Graph: the graph data contract.
- Security: keys, scopes and isolation.
docs/STATUS.md: what works today, what is partial and what is not there.