Claude Code persistent memory across sessions

Document type
Tutorial
Updated
Reading time
13 min

Claude-Mem stores Claude Code session history in SQLite and ChromaDB. Learn installation, search, privacy controls, token limits, and alternatives.

SourceOpen original report
Document details
thedotmack/claude-mem
stars
79.8K
forks
6.9K
Data as of

Claude-Mem is a Claude Code plugin installed with a single command. It saves session decisions, bug fixes, and file context in local SQLite and ChromaDB, then injects relevant context at the next startup. This manual covers installation, architecture, queries, privacy controls, and troubleshooting.

Author
Alex Newman @thedotmack
License
AGPL-3.0 (free and open source)
GitHub
44,000+ stars
Local storage
~/.claude-mem/

01Section

Contents

10 chapters · About 15 minutes to read

02Chapter 01

Problems addressed by Claude-Mem

Claude Code has no cross-session memory by default. Whenever it reopens, it knows nothing about the codebase, so architecture decisions, authentication bugs, and Docker volume settings need to be explained again. Developer communities call this "Goldfish Brain."

The two traditional approaches have limitations: record all context in CLAUDE.md, or let Claude write memory automatically. The former loads the entire document into context at every session start, regardless of the feature being worked on; Anthropic itself acknowledges that the latter is unstructured and not searchable. Once a project grows beyond several thousand lines, neither approach can maintain the full working context.

Claude-Mem adds an observer through Claude Code lifecycle hooks (SessionStart, PostToolUse, UserPromptSubmit, and Stop) to capture the input and output of every tool call. It compresses them into structured observations through Claude's agent-sdk, stores them in local SQLite, and builds a vector index with ChromaDB. The next time you ask, "How did we fix that Docker mount bug last time?", it can search memory and reply.

Three features and limitations

  1. Architecture decisions need explaining only once: Answers to questions such as "Why does this service use PostgreSQL instead of Redis?" are carried into later sessions automatically.

  2. The same bug does not need fixing twice: A previously fixed Docker volume mount error is recognized when it occurs again.

  3. Lower token consumption: The original author claims a 95% reduction in token usage on long-running tasks, though that figure is disputed; see chapter 8.

03Chapter 02

The three-tier retrieval architecture

Claude-Mem uses three-tier Progressive Disclosure retrieval to avoid loading every memory into context at once and consuming many tokens. It expands a record only when full details are needed.

Three-tier retrieval architecture
  1. Tier 1

    Index layer: titles and timestamps

    • Lists matching observation IDs, titles, types, and times. Claude checks these first to judge relevance.
    • ~50–100 tokens / result
  2. Tier 2

    Timeline layer: contextual narrative

    • Provides the timeline around an observation so Claude can understand the event sequence without opening the full content.
    • Moderate token consumption
  3. Tier 3

    Full Details layer: complete observations

    • Retrieves full data only when Claude judges that the ID is needed. Includes facts, narrative, concepts, and other fields.
    • ~500–1000 tokens / result

According to the official documentation, progressive retrieval uses about 10 times fewer tokens than loading everything at once. mem-search runs in a forked subagent, so intermediate search steps do not affect the main conversation's context window.

Underlying components

  • SQLite (~/.claude-mem/claude-mem.db): Structured observation storage.

  • ChromaDB: Vector embeddings for semantic search.

  • Bun + uv: Installed automatically on first setup. Bun runs the worker, and uv manages Chroma's Python packages.

  • Worker Service: An Express API on port 37700 + (uid % 100). Older versions used the fixed default 37777.

  • 6 Hooks: Setup, SessionStart, UserPromptSubmit, PreToolUse(Read), PostToolUse, and Stop.

04Chapter 03

Installation methods and common errors

If no memory features appear after installation, the usual cause is running npm install -g claude-mem. That command installs only the library; it neither registers Claude Code hooks nor starts the background worker.

Method A: Installation inside Claude Code (official recommendation)

Open any Claude Code session and enter these two lines:

claude code

text
/plugin marketplace add thedotmack/claude-mem
/plugin install claude-mem

Then exit Claude Code completely and reopen it. A full exit is required; /clear does not suffice. After restarting, the hooks are registered and the worker starts.

Method B: npx installation compared with npm install -g

terminal

bash
npx claude-mem install

This command checks that Node is ≥ 18, installs Bun and uv automatically, registers hooks in ~/.claude/plugins/, creates ~/.claude-mem/ and the default settings.json, and starts the worker.

Installation verification

After restarting Claude Code, open a new session and check for a section at the top labeled "previous observations relevant to what you're working on." Its presence confirms installation. If it is absent, open http://localhost:37777 (or your custom port) in a browser to check the Web Viewer.

05Chapter 04

First-use procedure

Installation does not immediately create memory. Claude-Mem compresses and saves observations when a session ends. Run a sample session first so there is something to remember; the effect becomes visible in the next session.

  1. Enter your project folder

    Enter the codebase root as usual and start Claude Code with claude. Claude-Mem stores memory by folder, so the path matters.

  2. Run a complete workflow

    Ask Claude to perform a task, such as 'Review the auth module structure, then fix this login bug.' It reads files, runs bash, and edits files; every step is captured as an observation by the PostToolUse hook.

  3. End the session

    Exit normally with /exit or close the terminal. The Stop hook triggers compression and organizes the session observations into structured memory. Compression takes several tens of seconds and runs in the background without blocking you.

  4. Open Claude Code again

    Reopen Claude Code in the same folder. The SessionStart hook compares your current work with past memory and injects relevant observations into context. A summary appears at the top.

  5. Ask in natural language

    Questions such as 'How did we handle that auth bug last time?' automatically trigger the mem-search skill. Claude searches local memory in a subagent and returns only relevant excerpts.

06Chapter 05

Everyday queries: memory search

Use natural language to query memory. Claude decides whether local memory needs searching. When it performs a query, the UI shows that the mem-search skill has been triggered.

5.1 Natural-language query patterns

Any of the following sentences triggers mem-search:

natural language queries

text
# Review
"What did we do last time?"
"What did we do last session?"

# Find a specific bug or decision
"Have we fixed this bug before?"
"How did we implement authentication?"
"What changes were made to worker-service.ts?"

# Recent activity
"Show me recent work on this project"
"What was happening when we added the viewer UI?"

5.2mem-search skill: 10 search modes

OperationDescription
Search ObservationsFull-text search across all observations
Search SessionsFull-text search of session summaries
Semantic SearchSemantic search through ChromaDB vectors
Timeline QueryRetrieve a timeline around a time period or ID
Get Observation by IDRetrieve one complete record by ID
File HistoryCheck a file's modification history
Concept SearchSearch by concept tags such as "auth" or "caching"
Filter by TypeFilter for types such as decision / bug-fix / refactor
Recent ActivityList recent observations, defaulting to the last N records
Cross-Session SearchFind consistent patterns across sessions

07Chapter 06

Web Viewer: memory inspection

Claude-Mem includes a React Web Viewer at the local address http://localhost:37777 (or the port assigned to your user). Open it in a browser to view the live memory stream, search the entire history, and manage settings.

Viewer UI features

  • Live observation stream: New observations appear in the viewer whenever Claude runs a tool.

  • Full-text and semantic search: Search past work in the browser without opening Claude Code.

  • Release channel switching: Enable beta features in Settings.

  • Smart Trash: Restore memories deleted by mistake from the trash.

  • Observation ID references: Link to /api/observation/{id} for the full content, allowing other tools to reference it.

08Chapter 07

Privacy controls: the <private> tag

Claude-Mem records the input and output of all session tool calls, including file contents, bash output, and user prompts. Data is stored mainly locally, but summaries are sent to the Anthropic API during compression. Keep this behavior in mind when handling secrets in the terminal.

Wrap content you do not want recorded in <private> tags:

prompt

text
This is my API key setup procedure. Please check whether the format is correct:

<private>
AWS_ACCESS_KEY=AKIA...
DATABASE_URL=postgres://user:pass@host/db
</private>

Would .env or JSON be a better format?

Tags are stripped at the hook boundary, so private content does not enter the worker or database. Users must remember to apply the tags; Claude-Mem does not detect secrets automatically.

Memory separation with multiple profiles

Work and personal memory can be separated on the same machine. Claude-Mem supports multiple profiles selected through environment variables. Ports are also separated automatically to avoid conflicts.

09Chapter 08

Community findings and 10 usage recommendations

The following findings come from Reddit, GitHub Issues, and community reviews. They cover practical feedback and known limitations.

Found an open-source tool that gives Claude Persistent Memory via SQLite and reduces token usage by 95% on long-running tasks

r/ClaudeAI·2025-12-15

Token usage claim: This is the original post that promoted claude-mem. The 95% figure applies to long-running tasks; everyday use produces a less pronounced reduction.

Hit 5-hour usage limit in a SINGLE session with ~140k tokens

r/ClaudeAI · User warning

Token usage report: Reports indicate that PostToolUse calls agent-sdk for a summary every time, exhausting the Pro plan's 5-hour rolling limit. GitHub issue #618 is still tracking the problem.

Anytime it uses observation instead of relearning something… that's basically 8× more efficient to run off of Claude-mem observations

The author · Celebrating 45K stars

Memory hit efficiency: Use 8× as the evaluation metric; exclude 95%. Every memory hit represents 8 times the efficiency. This makes the memory hit rate more important than the compression ratio.

CLAUDE.md is a blunt instrument: it loads the entire file into context at session start, regardless of relevance.

DataCamp · 2026 tutorial

Selection guidance: CLAUDE.md is sufficient for small projects. Use claude-mem for large projects with many files. The two can coexist.

On a managed machine (corporate laptop, shared dev box) this is a real amount of "stuff" — port 37777, Bun, uv, SQLite all auto-install

andrew.ooo review · 2026-04

Corporate restrictions: On a tightly managed company laptop, check that port 37777 (or the newer 37700+) is not blocked and that uv and Bun can be installed.

Once you've built up a few weeks of memory, switching away from Claude Code feels worse. Memory is a soft form of stickiness.

Medium @markchen69·2026-04

Long-term considerations: After accumulating a few weeks of memory, leaving Claude Code becomes more costly. Memory data is stored in SQLite and can theoretically be exported, but there is currently no official export tool.

10 community usage recommendations

01

A sample session after installation

Do not expect an immediate effect after installation. Run a complete workflow of reading files, editing code, and testing so there is something to remember. The effect appears in the next session.

02

Memory quality checks in Web Viewer

Open localhost:37777 once a week to inspect memory quality. Many meaningless observations, such as repeated ls results, may indicate that your workflow captures too much noise.

03

Separate folders for each project

claude-mem separates memory by folder path. Working on five different projects in the home directory mixes their memory. Use a separate git repository folder for each project.

04

<private> tags and secret-handling limits

Tags are manual and can be forgotten. A safer approach is to load .env and handle secrets in a shell session that Claude Code has not accessed.

05

Token usage tests on small tasks

Because of issue #618, test a small project for a week before heavy use and compare token consumption. Pause use if it rises sharply.

06

The WSL2 path for Windows

Native Windows installation encounters npm path problems. WSL2 + Ubuntu is the only Windows path explicitly supported in the official documentation.

07

Claude Desktop MCP integration

Configure the mcp-search server in Claude Desktop's claude_desktop_config.json to search your terminal work memory directly from desktop chat.

08

Backups of the ~/.claude-mem/ folder

After a few weeks, this folder contains your work's intellectual property. Configure an rsync or Time Machine exclusion path, but keep a backup. Copy it to a new machine to resume using the memory.

09

GitHub issue #618 progress

'Uses too much tokens' is currently claude-mem's largest open issue. Check its current GitHub status before using it in production.

10

Diagnosis with the troubleshoot skill

claude-mem includes a troubleshoot skill. Describe your problem for automatic diagnosis; you do not need to search GitHub issues first.

10Chapter 09

CLAUDE.md, Auto Memory, and alternatives

claude-mem is one of several memory options for Claude Code. Alternatives include the official CLAUDE.md, Anthropic's built-in Memory feature, Cole Medin's claude-memory-compiler, memsearch, and Omega. The following table compares their features and suitable uses.

OptionSearch capabilityAutomatic captureStorageSuitable uses
CLAUDE.mdNoneManualStatic fileSmall projects and shared team rules
Auto Memory (official)WeakAutomaticUnstructuredPersonal preferences and lightweight memory
claude-memThree tiers and semantic searchEvery tool callSQLite + ChromaLong-term projects and decision review
memsearchSemantic and structured searchAutomaticMarkdown + MilvusReadable memory tracked with git
claude-memory-compilerMediumAutomaticKnowledge articlesKarpathy-style learning notes

Decision procedure

  1. Project < 1000 lines with simple rules → CLAUDE.md is enough.

  2. Personal preferences such as tone or coding style → Anthropic's built-in Memory is sufficient.

  3. Long-term projects lasting weeks or more, with frequent difficulty recalling yesterday's work → claude-mem.

  4. Memory that supports git diff tracking and team sharing → memsearch.

  5. A tight token budget → Run a small test to assess whether issue #618 affects you.

11Chapter 10

Troubleshooting and FAQ

These common problems and solutions cover installation failures, port conflicts, unusual token consumption, and privacy controls.

Missing memory and session summaries after installation

In 99% of cases, the cause is running npm install -g claude-mem. Use npx claude-mem install or /plugin install claude-mem inside Claude Code instead. Then exit Claude Code completely and reopen it.

Failed connections to localhost:37777

The newer default port is 37700 + (uid % 100), which is not necessarily 37777. Check workerPort in ~/.claude-mem/settings.json, or set the CLAUDE_MEM_WORKER_PORT environment variable directly.

Token usage and the 5-hour limit

This is known issue #618. Temporary approaches are (1) reducing PostToolUse summary frequency in settings, (2) summarizing only at session end, and (3) temporarily disabling the plugin during large sessions. An official patch is the long-term solution.

Native Windows support and WSL2

The README includes Windows Setup Notes, but the official recommendation is WSL2. Native PowerShell can encounter errors such as npm: The term 'npm' is not recognized.

Checking whether sensitive files were recorded

Search the filename in Web Viewer and check the observation list. If it appears, move it to the trash through Smart Trash. For ongoing use, apply <private> tags or avoid letting Claude read that file.

Memory export and migration between machines

Copy the entire ~/.claude-mem/ folder to the new machine; it contains SQLite and the Chroma index. There is no official export command, but any sqlite3 tool can read the SQLite data.

Compatibility with Cursor, Gemini CLI, and other AI tools

The official README mentions Gemini CLI support, which takes effect after a restart. Cursor is not currently listed as officially supported. The SQLite database has an open structure, so an adapter could theoretically be written.

OpenClaw gateway features and uses

OpenClaw is a self-hosted gateway. A single command can install claude-mem as a persistent plugin and add observation notifications through Telegram, Discord, and Slack. Typical local users do not need it; teams or self-hosted servers may use it.

Useful Links

Content sources and licensing

This content draws on Claude-Mem's official documentation, GitHub README, the andrew.ooo review, DataCamp's tutorial, developer tests on Medium, and r/ClaudeAI discussions.

License note: Claude-Mem uses AGPL-3.0, while some components, including Ragtime, use PolyForm Noncommercial. Check the license before commercial use.

Editorial & design: Tenten

Updated · May 2026

References