How it Works

Architecture overview

Agent (Claude Code, Cursor, etc.)
  │
  ├── add_memory ──→ FactStore (SQLite, WAL mode)
  │                      │
  │                      ├──→ KeywordIndex (SQLite FTS5, BM25 + porter)
  │                      ├──→ TemporalIndex (time-sorted, recency)
  │                      └──→ EmbeddingIndex (dense vectors, opt-in)
  │
  ├── recall_memory ──→ Multi-index retrieval ──→ Ranked facts
  │
  └── ask_memory ──→ Question-Answering Pipeline
                       ├── Classify question type
                       ├── Retrieve facts (multi-index)
                       ├── Format context (timestamps, sessions)
                       ├── Build type-specific prompt
                       ├── Generate answer (LLM)
                       └── Extract clean answer

Storage

Facts

Facts are the atomic unit of memory. Each fact is a piece of text with metadata:

  • Content: The actual text (a user message, agent response, or tool output)
  • Source: user, llm, or tool
  • Timestamp: When the fact was stored
  • Caller: Who stored it (user identity + agent name)
  • Metadata: String key/value pairs, including the agent's session_id and the provenance stamps below

Provenance stamps

Each captured fact records where it was captured, in metadata keys prefixed stamp_. Hooks and shmem add record what they can work out from the agent's working directory and environment; anything that can't be determined is left off.

Key Value
stamp_repo The git repository's origin as host/owner/name (github.com/acme/billing). SSH and HTTPS spellings normalize to the same value, credentials are never kept, and a linked worktree reports its main repository. A repository with no remote records its root directory (~/src/notes). Absent outside a repository.
stamp_branch The checked-out branch. Absent when HEAD is detached.
stamp_dir The agent's working directory, relative to home (~/src/billing/svc).
stamp_host The machine's short hostname.
stamp_cloud The hosted environment the agent runs in: claude-code-cloud (CLAUDE_CODE_REMOTE=true), codespaces (CODESPACES=true), or github-actions (GITHUB_ACTIONS=true). Absent elsewhere.
stamp_project_source How the fact's project was chosen: marker (a .shmem/project file), env (SHMEM_DEFAULT_PROJECT, or the deprecated SHMEM_PROJECT), or fallback (the default project).
stamp_app_project The Claude app project the agent reported working in, via the app_project input of add_memory or session_digest.

Git state is read from the repository's .git files, not by running git, so stamping never slows a hook. Other write paths stamp only what they can vouch for:

  • shmem add --batch stamps stamp_host and stamp_cloud, plus stamp_project_source for records that don't name a project. A batch is often a bulk or historical load, so the checkout it runs in says nothing about its records; repo, branch and dir come only from the records' own metadata, which always wins.

  • A local stdio MCP server stamps stamp_host, stamp_cloud and, when the call names no project, stamp_project_source. For the agents known to say where their session is rooted, it also stamps that root's stamp_repo and the stamp_branch checked out at the time of the call (or stamp_dir when the root isn't a repository), and the agent's session_id:

    Agent Session root session_id
    Claude Code CLAUDE_PROJECT_DIR CLAUDE_CODE_SESSION_ID (the id when the server started)
    Codex the server's working directory (the session's -C directory) sent with each tool call
    Gemini CLI the server's working directory (where Gemini was started) —

    Other clients get neither: their server's working directory says nothing reliable about where the agent works. A session_id the call already carries is kept.

  • A remote MCP server stamps only stamp_app_project.

Stamps are ordinary metadata, so a metadata filter narrows a read to them: shmem ask "why did we cap retries?" --meta stamp_repo=github.com/acme/billing.

Stamps belong to the fact's owner. They sync to the owner's own server copy with the rest of the metadata, but are removed from every copy that reaches another account: a fact shared into someone else's space, a fact written directly into another user's project, and any fact a teammate reads from a shared space. A teammate can't filter a read of your project on stamp_* keys either.

When you ask a question, the answering model sees your own facts' stamps as a short provenance line — github.com/acme/billing (branch fix/retry-cap) · on laptop · app: Q4 pricing — so it can say where work happened. A teammate's stamps are removed before the model sees anything, whether the answer runs on your machine or on a server, and their facts' citations show who they came from instead of a repository. Asking in another account's project, its facts reach the model with only the metadata their audience may see, as get_facts would show them to you.

Facts are immutable — insert or delete only, never modified. They're stored in SQLite with WAL mode for concurrent reads.

Atomicity matters for retrieval, not just storage. The keyword index ranks whole facts, so each fact needs to carry the names and keywords it should be found by. One self-contained statement per fact keeps every entity at the surface; a paragraph that packs several facts together ("Batch of facts: (1)… (2)… (3)…") buries them — BM25 sees one long, diluted document, the write succeeds, and reads quietly miss. Writers (integrations especially) should split multi-fact content into separate writes rather than storing it as one blob.

Projects

Projects provide namespace isolation. Each project gets its own SQLite database and index files. The default project lives at ~/.shmem/projects/default/.

Switch projects via a .shmem/project file at your repo root (written by shmem init and discovered by walking up from the current directory), SHMEM_DEFAULT_PROJECT for global mode, or the shmem admin project command. The legacy SHMEM_PROJECT env var is deprecated for the shmem CLI but still the canonical config mechanism for shmem-mcp server instances.

Retrieval

shmem uses a keyword index and a temporal index by default (plus an opt-in embedding index). Each captures a different signal:

Keyword index

A persisted SQLite FTS5 index with BM25 ranking and porter stemming. Fast, deterministic, and works well for specific terms. Because it's a SQLite index maintained by triggers, it's kept current at write time — no rebuild-from-scan when a process starts.

  • BM25 ranks matches by term rarity and frequency
  • porter stemming matches word variants (e.g. "running" ↔ "run")
  • User messages receive a configurable boost (they tend to carry more signal)

Temporal index

Time-sorted index for recency queries and context expansion.

  • Returns recent facts with recency scoring (most recent = highest score)
  • Supports range queries (facts between two timestamps)
  • Context expansion: given an anchor fact, retrieves surrounding facts within a time window (like grep -C)

Embedding index (opt-in)

Off by default. A fresh install runs keyword + temporal retrieval only — that's the intended zero-config setup (no embedding service, no per-fact embedding cost), not a broken one. This index is an optional extra.

When enabled, it's a dense-vector similarity index that bridges the vocabulary gap keyword search can't — matching facts by meaning even when they share no words with the query. Backed by a pluggable embedder (in-process POTION, local Ollama, or a hosted API), enabled by setting SHMEM_EMBED_MODEL. If your QA/LLM provider has no embeddings API (anthropic, bedrock, gemini, …), also set SHMEM_EMBED_PROVIDER to route the embedder elsewhere. The recommended setup is SHMEM_EMBED_PROVIDER=potion with SHMEM_EMBED_MODEL=potion-retrieval-32M: a static embedder that runs in-process, with no API key, no daemon and no network at query time. Its model files (~123 MB resident) are downloaded from Hugging Face on first use and cached under the user cache directory (override with GO_POTION_HOME). shmem admin status reports the index's state on its Embeds: line.

  • Facts are embedded once; vectors are persisted in SQLite and only new facts are embedded on later runs (no re-embedding the whole corpus)
  • Queries are ranked by brute-force cosine similarity against the stored vectors; an approximate-nearest-neighbor index (e.g. sqlite-vec) is the next step if that becomes a bottleneck at scale
  • Its ranking is fused with the keyword index's by rank (reciprocal rank fusion), since BM25 and cosine scores aren't on one scale

Full-scan mode: Below 10K facts, shmem scores all facts directly rather than using the capped index lookup. This is faster and more accurate for small datasets.

Multi-index fusion

When you query recall_memory, shmem runs the enabled indexes and merges results:

  1. Keyword index returns BM25-ranked matches
  2. Temporal index returns recency-scored facts
  3. Embedding index (if enabled) returns similarity-ranked facts
  4. Results are deduplicated and ranked by combined score
  5. Token budget packing selects the highest-scoring facts that fit within the budget

Multi-hop questions, which span several topics, are the hardest case: the facts that answer them often share no keywords with each other, so no single index ranks them all highly.

Question-answering pipeline

ask_memory goes beyond raw retrieval. It runs a full question-answering pipeline:

1. Question classification

The question is classified into one of five types:

Type Example Strategy
Temporal "When did we fix the auth bug?" Chain-of-thought with date reasoning
Aggregative "How many times have we discussed caching?" Additive counting across sessions
Knowledge-update "What's our current API rate limit?" Most recent information wins
Preference "What testing framework do I prefer?" Identify patterns in preferences
Default "What approach did we use for pagination?" Direct answer from context

2. Fact retrieval

Multi-index retrieval finds the most relevant facts for the question.

3. Context formatting

Facts are grouped by date and session, with timestamps:

=== 2025/02/12 ===
--- Conversation at 17:50 (claude-code) ---
[17:50] [user] Let's go with JWT for auth.
[17:51] [llm] Good choice. Short-lived access tokens with refresh...

=== 2025/02/14 ===
--- Conversation at 09:15 (claude-code) ---
[09:15] [user] What about rate limiting on the JWT endpoint?

Sessions are detected automatically: a gap of 30+ minutes between facts starts a new session.

4. Answer generation

A type-specific prompt is built and sent to the LLM. Temporal questions get chain-of-thought reasoning. Aggregative questions are told to count across sessions. Knowledge-update questions focus on the most recent information.

5. Answer extraction

The raw LLM response is parsed to extract a clean answer — stripping chain-of-thought reasoning, removing preambles, and cleaning up formatting.

Performance

Retrieval is fast enough that the QA model dominates end-to-end latency:

Metric Result
Recall p50 0.9ms
Insert 1000 facts (batch) ~17ms

QA accuracy is measured on LongMemEval — 500 questions, 50 max facts, judged by Claude Sonnet 5. Those numbers are regenerated from the run data on every refresh, so the benchmarks page is the single source for them rather than a copy kept here.

The system is designed for datasets from hundreds to millions of facts. Months or years of conversations across several agents lands in the hundreds of thousands, which is an ordinary deployment rather than a stress case. Keeping the queries shmem supports fast at that size is our job, not something you should be rationing captures around.

Total content size matters more than fact count: a store full of large tool outputs is heavier work than the same number of short conversational turns.

Sharing & permissions

Projects can be shared between users on multi-user HTTP servers using unix-style group permissions.

  • Groups: Named owner/group-name. The owner creates the group and invites members. Members must accept before gaining access.
  • Per-project permissions: Each project has an optional .permissions.json specifying a group and permission level (r for read, rw for read-write).
  • Cross-user references: Shared projects are accessed via owner/project syntax (e.g., recall_memory(project="alice/my-app")).
  • Backward compatible: STDIO mode (single-user) has no permission checks. Projects without .permissions.json are owner-only.

See the Reference docs for the full set of group and sharing tools.

Security model

  • Data locality: Everything stored on your machine (SQLite + JSON files). No cloud required.
  • File permissions: Data files written with 0600, directories with 0700.
  • Auth on HTTP: Bearer token auth with constant-time comparison. Per-user API keys for team setups.
  • Caller identity: Server-side stamping from auth tokens on HTTP transports. Environment variables on STDIO.
  • Trust boundary: Facts are trusted content — shmem is a personal/team tool where the writers are the users.