We use cookies to enhance your experience on the site
CodeWorlds
Back to collections
Guide23 min read

claude-mem

claude-mem is an open-source tool for managing persistent memory and context in Claude Code sessions for better workflow continuity.

claude-mem - Persystentna Pamięć dla Claude Code

Czym jest claude-mem?

claude-mem to innowacyjne narzędzie open-source stworzone do rozwiązania jednego z największych wyzwań przy pracy z AI asystentami - braku ciągłości pamięci między sesjami. Podczas gdy Claude ma imponujące okno kontekstowe (do 200K tokenów), każda nowa rozmowa zaczyna się od zera, bez wiedzy o poprzednich interakcjach.

claude-mem zmienia ten paradygmat, wprowadzając warstwę persystentnej pamięci, która zachowuje kluczowe informacje między sesjami. Narzędzie działa jako "external brain" dla Claude, przechowując fakty o projekcie, preferencje kodowania, podjęte decyzje i inny kontekst, który normalnie musiałbyś powtarzać przy każdej nowej sesji.

Projekt został stworzony przez społeczność deweloperów pracujących intensywnie z Claude Code i szybko zyskał popularność dzięki znaczącej poprawie produktywności. Zamiast tracić czas na przekazywanie Claude'owi kontekstu za każdym razem, claude-mem automatycznie wstrzykuje relevantną wiedzę do każdej sesji.

GitHub

Repository: github.com/anthropics/claude-mem

Dlaczego claude-mem?

Problem z pamięcią AI

Standardowy workflow z Claude wygląda tak:

Code
TEXT
Sesja 1: "Pracuję nad projektem Next.js 15 z Prisma..."
         Claude: "Rozumiem, pomogę Ci z projektem Next.js..."

Sesja 2: "Dokończmy wczorajszą pracę"
         Claude: "Nie mam kontekstu poprzedniej sesji.
                  Możesz mi przypomnieć czym się zajmowaliśmy?"

To wymaga ciągłego powtarzania informacji, co jest:

  • Czasochłonne - Tracisz minuty przy każdej sesji
  • Podatne na błędy - Możesz zapomnieć o ważnych szczegółach
  • Frustrujące - AI "zapomina" wszystko co ustaliliście

Rozwiązanie claude-mem

Z claude-mem workflow wygląda tak:

Code
Bash
# Raz dodajesz informację do pamięci
claude-mem add "Projekt używa Next.js 15 App Router z Prisma i PostgreSQL"
claude-mem add "Preferuję Server Components gdzie możliwe"
claude-mem add "Testy piszemy w Vitest, nie w Jest"

# Każda sesja automatycznie ma dostęp do tej wiedzy
claude --memory
# Claude: "Widzę że pracujemy nad projektem Next.js 15
#          z App Router i Prisma. Preferujesz Server Components
#          i Vitest do testów. Jak mogę pomóc?"

Kluczowe zalety

  1. Ciągłość pracy - Claude pamięta kontekst między sesjami
  2. Oszczędność czasu - Koniec z powtarzaniem tych samych informacji
  3. Lepsza jakość - Claude ma pełny kontekst i daje trafniejsze odpowiedzi
  4. Skalowalność - Pamięć rośnie wraz z projektem
  5. Organizacja - Struktura kategorii i tagów
  6. Selektywność - Kontrolujesz co trafia do pamięci
  7. Lokalność - Dane pozostają na Twoim komputerze
  8. Integracja - Działa seamlessly z Claude Code CLI

Instalacja i konfiguracja

Wymagania systemowe

  • Node.js 18+ lub Python 3.10+
  • Claude Code CLI zainstalowany
  • ANTHROPIC_API_KEY skonfigurowany

Instalacja

Code
Bash
# Klonowanie repozytorium
git clone https://github.com/anthropics/claude-mem
cd claude-mem

# Instalacja zależności (Node.js)
npm install

# Lub instalacja globalna
npm install -g claude-mem

# Alternatywnie przez Python
pip install claude-mem

Konfiguracja początkowa

Code
Bash
# Inicjalizacja pamięci
claude-mem init

# Konfiguracja (interaktywna)
claude-mem config

# Lub ręcznie
cat > ~/.config/claude-mem/config.json << 'EOF'
{
  "storage": {
    "type": "local",
    "path": "~/.claude-mem/data"
  },
  "retrieval": {
    "maxItems": 20,
    "relevanceThreshold": 0.7,
    "useEmbeddings": true
  },
  "integration": {
    "autoInject": true,
    "injectPosition": "system"
  },
  "categories": [
    "project",
    "preferences",
    "decisions",
    "context",
    "todo"
  ]
}
EOF

Podstawowe użycie

Dodawanie do pamięci

Code
Bash
# Podstawowe dodanie
claude-mem add "Projekt nazywa się CodeWorlds i jest platformą edukacyjną"

# Z kategorią
claude-mem add --category project "Stack: Next.js 15, TypeScript, Prisma"

# Z tagami
claude-mem add --tags "database,schema" "Tabela users ma pola: id, email, name, role"

# Z priorytetem
claude-mem add --priority high "WAŻNE: Nie commituj plików .env"

# Interaktywnie
claude-mem add -i
# > Kategoria: preferences
# > Treść: Preferuję funkcyjne komponenty z hooks
# > Tagi: react, style
# > Dodano!

# Z pliku
cat project-context.md | claude-mem add --category project

# Masowe dodanie z JSON
claude-mem import memories.json

Przeglądanie pamięci

Code
Bash
# Lista wszystkich wspomnień
claude-mem list

# Filtrowanie po kategorii
claude-mem list --category project

# Filtrowanie po tagach
claude-mem list --tags database

# Wyszukiwanie
claude-mem search "Next.js"

# Szczegóły konkretnego wpisu
claude-mem show mem_123456

# Eksport do pliku
claude-mem export --format json > memories.json
claude-mem export --format markdown > memories.md

Zarządzanie pamięcią

Code
Bash
# Edycja wpisu
claude-mem edit mem_123456

# Usunięcie wpisu
claude-mem delete mem_123456

# Usunięcie po kategorii
claude-mem delete --category old-project

# Czyszczenie całej pamięci
claude-mem clear --confirm

# Archiwizacja
claude-mem archive --older-than 30d

# Statystyki
claude-mem stats
# Memories: 156
# Categories: 5
# Most used: project (45), preferences (32)
# Storage: 2.3 MB

Integracja z Claude Code

Code
Bash
# Uruchom Claude z pamięcią
claude --memory

# Określ które kategorie wstrzyknąć
claude --memory --mem-categories project,preferences

# Wstrzyknij tylko relevantne
claude --memory --mem-query "database schema"

# Tryb debug - pokaż co zostało wstrzyknięte
claude --memory --mem-debug

# Tymczasowo wyłącz pamięć
claude --no-memory

Zaawansowane funkcje

Automatyczne uczenie się

Code
Bash
# Włącz auto-learning z sesji Claude
claude-mem config set autoLearn true

# Claude będzie automatycznie zapisywał:
# - Podjęte decyzje
# - Rozwiązane problemy
# - Ustalone konwencje

# Przykład sesji
$ claude --memory
You: Zdecydowałem że będziemy używać Zod do walidacji

Claude: Rozumiem, zapisuję tę decyzję. Zod będzie główną
        biblioteką do walidacji w projekcie.

# Automatycznie dodane do pamięci:
# [decision] Projekt używa Zod do walidacji schematów

Semantic Search

Code
Bash
# claude-mem używa embeddings do semantycznego wyszukiwania
claude-mem search "jak obsługujemy błędy"
# Znajdzie wpisy o: error handling, exceptions, try-catch,
# nawet jeśli nie zawierają dokładnie tych słów

# Konfiguracja embeddings
claude-mem config set embeddingModel "text-embedding-3-small"
claude-mem config set similarityThreshold 0.75

Kontekst projektowy (Project Memory)

Code
Bash
# Każdy projekt może mieć własną pamięć
claude-mem init --project my-app
claude-mem add --project my-app "Ten projekt to..."

# Przełączanie między projektami
claude-mem switch my-app
claude-mem switch other-project

# Wspólna pamięć globalna
claude-mem add --global "Mój styl kodowania to..."

# Hierarchia: project memory > global memory

Synchronizacja i backup

Code
Bash
# Eksport do backupu
claude-mem backup --output ~/backups/claude-mem.tar.gz

# Import z backupu
claude-mem restore ~/backups/claude-mem.tar.gz

# Synchronizacja między maszynami (przez Git)
cd ~/.claude-mem
git init
git remote add origin git@github.com:user/my-claude-mem.git
git push -u origin main

# Na innej maszynie
git clone git@github.com:user/my-claude-mem.git ~/.claude-mem
claude-mem rebuild-index

# Synchronizacja z chmurą (eksperymentalne)
claude-mem config set sync.enabled true
claude-mem config set sync.provider "s3"
claude-mem config set sync.bucket "my-claude-mem"

API do integracji

Code
TypeScript
// Użycie claude-mem jako biblioteki
import { ClaudeMem } from 'claude-mem'

const mem = new ClaudeMem({
  storagePath: './memory',
  embeddingModel: 'text-embedding-3-small'
})

// Dodaj wspomnienie
await mem.add({
  content: 'Projekt używa Next.js 15',
  category: 'project',
  tags: ['framework', 'nextjs'],
  priority: 'high'
})

// Wyszukaj relevantne
const memories = await mem.search('framework frontend', {
  limit: 10,
  threshold: 0.7
})

// Wygeneruj kontekst dla Claude
const context = await mem.generateContext({
  query: 'dodaj nowy komponent',
  maxTokens: 2000
})

// Użyj z Claude API
const response = await anthropic.messages.create({
  model: 'claude-sonnet-4-5-20241022',
  system: context,
  messages: [{ role: 'user', content: 'Dodaj komponent Button' }]
})
Code
Python
# Python API
from claude_mem import ClaudeMem

mem = ClaudeMem(storage_path="./memory")

# Dodaj wspomnienie
mem.add(
    content="Projekt używa FastAPI z SQLAlchemy",
    category="project",
    tags=["backend", "python"]
)

# Wyszukaj
results = mem.search("database", limit=5)

# Generuj kontekst
context = mem.generate_context(
    query="add new endpoint",
    max_tokens=2000
)

Struktura danych

Format Memory Entry

Code
JSON
{
  "id": "mem_abc123def456",
  "content": "Projekt CodeWorlds używa Next.js 15 App Router",
  "category": "project",
  "tags": ["framework", "nextjs", "frontend"],
  "priority": "high",
  "created": "2025-01-15T10:30:00Z",
  "updated": "2025-01-15T10:30:00Z",
  "accessCount": 15,
  "lastAccessed": "2025-01-25T14:20:00Z",
  "embedding": [0.023, -0.145, 0.089, ...],
  "metadata": {
    "source": "manual",
    "project": "codeworlds",
    "confidence": 1.0
  }
}

Organizacja kategorii

Code
Bash
# Rekomendowana struktura kategorii

# project - Informacje o projekcie
claude-mem add --category project "Stack: Next.js, TypeScript, Prisma"

# preferences - Twoje preferencje kodowania
claude-mem add --category preferences "Preferuję single quotes w JS"

# decisions - Podjęte decyzje architekturalne
claude-mem add --category decisions "Wybraliśmy Redux Toolkit zamiast Zustand"

# context - Kontekst biznesowy
claude-mem add --category context "Aplikacja ma 50k aktywnych użytkowników"

# patterns - Używane wzorce
claude-mem add --category patterns "Używamy Repository Pattern dla data access"

# todo - Rzeczy do zrobienia
claude-mem add --category todo "TODO: Zrefaktorować moduł auth"

# issues - Znane problemy
claude-mem add --category issues "Bug: Memory leak w Dashboard component"

Best Practices

Co warto zapisywać w pamięci

Code
Bash
# ✅ DOBRE - zapisuj:

# Stack technologiczny
claude-mem add --category project "Next.js 15, TypeScript strict, Prisma, PostgreSQL"

# Konwencje kodowania
claude-mem add --category preferences "Komponenty nazywamy PascalCase, hooki useCamelCase"

# Decyzje architekturalne
claude-mem add --category decisions "2025-01-15: Wybraliśmy tanstack-query zamiast SWR"

# Struktura projektu
claude-mem add --category project "src/components/ - UI, src/features/ - logika biznesowa"

# Ważne ograniczenia
claude-mem add --category context "Max 100 produktów na zapytanie API (rate limit)"

# Rozwiązane problemy
claude-mem add --category patterns "Fix na hydration mismatch: useEffect + mounted state"

# ❌ ZŁYCH - nie zapisuj:

# Zbyt szczegółowego kodu
# claude-mem add "function calculateTotal() { return items.reduce(...) }"

# Tymczasowych rzeczy
# claude-mem add "Dzisiaj debuguję komponent X"

# Oczywistości
# claude-mem add "JavaScript to język programowania"

Utrzymanie pamięci

Code
Bash
# Regularne przeglądy (np. raz w tygodniu)
claude-mem list --sort lastAccessed
# Usuń nieużywane wpisy

# Konsolidacja podobnych wpisów
claude-mem merge mem_123 mem_456 --into "Połączony wpis"

# Archiwizacja starych projektów
claude-mem archive --project old-project

# Monitoring rozmiaru
claude-mem stats
# Jeśli > 1000 wpisów, rozważ cleanup

Optymalizacja wydajności

Code
Bash
# Ogranicz liczbę wstrzykiwanych wspomnień
claude-mem config set retrieval.maxItems 15

# Zwiększ próg relevancji
claude-mem config set retrieval.relevanceThreshold 0.8

# Używaj kategorii do filtrowania
claude --memory --mem-categories "project,decisions"

# Przebuduj indeks po dużych zmianach
claude-mem rebuild-index

# Kompresuj stare embeddingi
claude-mem optimize --compress-old 90d

Integracje

VS Code Extension

.vscode/settings.json
JSON
// .vscode/settings.json
{
  "claudeMem.enabled": true,
  "claudeMem.autoInject": true,
  "claudeMem.categories": ["project", "preferences"],
  "claudeMem.showInStatusBar": true
}

// Komendy VS Code:
// Ctrl+Shift+M - Dodaj zaznaczenie do pamięci
// Ctrl+Shift+L - Lista wspomnień
// Ctrl+Shift+S - Szukaj w pamięci

Git Hooks

Code
Bash
# .git/hooks/post-commit
#!/bin/bash
# Automatycznie zapisz podsumowanie commita

commit_msg=$(git log -1 --pretty=%B)
claude-mem add --category "commits" --tags "git,history" \
  "Commit: $commit_msg"

CI/CD Integration

.github/workflows/update-mem.yml
YAML
# .github/workflows/update-mem.yml
name: Update Claude Memory

on:
  push:
    branches: [main]
    paths: ['package.json', 'tsconfig.json']

jobs:
  update-memory:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Extract project info
        run: |
          deps=$(jq -r '.dependencies | keys | join(", ")' package.json)
          echo "DEPS=$deps" >> $GITHUB_ENV

      - name: Update memory
        run: |
          claude-mem add --category project \
            "Dependencies: ${{ env.DEPS }}"

claude-mem vs alternatywy

Funkcjaclaude-memWłasny plikRęczne prompty
Persystencja✅ Automatyczna⚠️ Manualna❌ Brak
Semantic search✅ Embeddings❌ Brak❌ Brak
Integracja z CLI✅ Natywna⚠️ Ręczna⚠️ Ręczna
Organizacja✅ Kategorie/tagi❌ Płaska❌ Brak
Auto-learning✅ Opcjonalne❌ Brak❌ Brak
Multi-project✅ Tak⚠️ Trudne❌ Nie
SetupŚredniBrakBrak
SkalowanieŚwietneSłabeSłabe

Rozwiązywanie problemów

Typowe problemy

Code
Bash
# Problem: Pamięć nie jest wstrzykiwana
claude-mem doctor
# Sprawdzi: konfigurację, połączenie z Claude, indeks

# Problem: Wolne wyszukiwanie
claude-mem rebuild-index
claude-mem optimize

# Problem: Zbyt dużo irrelevantnych wspomnień
claude-mem config set retrieval.relevanceThreshold 0.85

# Problem: Za mało kontekstu
claude-mem config set retrieval.maxItems 30

# Problem: Konflikt między projektami
claude-mem switch --project correct-project

# Problem: Uszkodzony indeks
claude-mem repair --rebuild

Debug mode

Code
Bash
# Włącz szczegółowe logi
export CLAUDE_MEM_DEBUG=1
claude --memory

# Pokaż co zostało wstrzyknięte
claude --memory --mem-debug

# Sprawdź embeddingi
claude-mem show mem_123 --show-embedding

# Testuj retrieval
claude-mem test-retrieval "add new component"

FAQ - Najczęściej zadawane pytania

Czy moje dane są bezpieczne?

Tak, wszystkie dane są przechowywane lokalnie na Twoim komputerze. claude-mem nie wysyła wspomnień do żadnych zewnętrznych serwisów (chyba że sam skonfigurujesz synchronizację z chmurą).

Ile wspomnień mogę przechowywać?

Nie ma twardego limitu. Testowano z ponad 10,000 wpisów bez problemów z wydajnością. Rekomendowane jest utrzymywanie < 500 aktywnych wspomnień na projekt dla optymalnej relevancji.

Czy claude-mem zużywa tokeny API?

Samo przechowywanie i wyszukiwanie nie zużywa tokenów Claude. Tokeny są zużywane tylko gdy pamięć jest wstrzykiwana do sesji Claude (jako część system prompt lub kontekstu).

Jak działa semantic search?

claude-mem używa modeli embedding (np. text-embedding-3-small) do konwersji tekstu na wektory. Przy wyszukiwaniu oblicza cosine similarity między zapytaniem a wszystkimi wpisami.

Czy mogę używać claude-mem bez Claude Code?

Tak, claude-mem może być używany jako samodzielna biblioteka do zarządzania wiedzą. Ma też API do integracji z dowolnym klientem Claude API.

Jak migrować z własnego systemu notatek?

Code
Bash
# Import z markdown
claude-mem import notes.md --format markdown

# Import z JSON
claude-mem import data.json

# Import z katalogu
claude-mem import-dir ./my-notes --recursive

Czy wspierane są zespoły?

Obecnie claude-mem jest narzędziem single-user. Synchronizacja zespołowa jest w roadmapie. Workaround: shared Git repo z pamięcią.

Cennik

claude-mem jest w pełni darmowy i open-source (licencja MIT).

Jedyne koszty to:

  • Tokeny API Claude (przy wstrzykiwaniu pamięci)
  • Opcjonalnie: API embeddings jeśli używasz zaawansowanego semantic search

Podsumowanie

claude-mem rozwiązuje fundamentalny problem pracy z AI - brak ciągłości między sesjami:

  • Persystentna pamięć - Zachowaj kontekst między rozmowami
  • Semantic search - Automatyczne znajdowanie relevantnych informacji
  • Integracja z Claude Code - Seamless workflow z CLI
  • Organizacja - Kategorie, tagi, priorytety
  • Prywatność - Dane pozostają lokalnie
  • Open-source - Darmowy, MIT License

Zacznij używać claude-mem i przestań tracić czas na powtarzanie kontekstu przy każdej sesji z Claude.


claude-mem - Persistent memory for Claude Code

What is claude-mem?

claude-mem is an innovative open-source tool created to solve one of the biggest challenges when working with AI assistants - the lack of memory continuity between sessions. While Claude has an impressive context window (up to 200K tokens), every new conversation starts from scratch, with no knowledge of previous interactions.

claude-mem changes this paradigm by introducing a persistent memory layer that preserves key information between sessions. The tool acts as an "external brain" for Claude, storing facts about the project, coding preferences, decisions made, and other context that you would normally have to repeat at the beginning of each new session.

The project was created by a community of developers who work intensively with Claude Code, and it quickly gained popularity thanks to a significant boost in productivity. Instead of wasting time providing Claude with context every time, claude-mem automatically injects relevant knowledge into each session.

GitHub

Repository: github.com/anthropics/claude-mem

Why claude-mem?

The AI memory problem

A standard workflow with Claude looks like this:

Code
TEXT
Session 1: "I'm working on a Next.js 15 project with Prisma..."
           Claude: "I understand, I'll help you with the Next.js project..."

Session 2: "Let's finish yesterday's work"
           Claude: "I don't have context from the previous session.
                    Can you remind me what we were working on?"

This requires constantly repeating information, which is:

  • Time-consuming - You lose minutes at the start of each session
  • Error-prone - You may forget important details
  • Frustrating - The AI "forgets" everything you established

The claude-mem solution

With claude-mem the workflow looks like this:

Code
Bash
# You add information to memory once
claude-mem add "Project uses Next.js 15 App Router with Prisma and PostgreSQL"
claude-mem add "I prefer Server Components where possible"
claude-mem add "We write tests in Vitest, not Jest"

# Every session automatically has access to this knowledge
claude --memory
# Claude: "I see we're working on a Next.js 15 project
#          with App Router and Prisma. You prefer Server Components
#          and Vitest for testing. How can I help?"

Key advantages

  1. Work continuity - Claude remembers context between sessions
  2. Time savings - No more repeating the same information
  3. Better quality - Claude has full context and gives more accurate answers
  4. Scalability - Memory grows alongside the project
  5. Organization - Category and tag structure
  6. Selectivity - You control what goes into memory
  7. Locality - Data stays on your machine
  8. Integration - Works seamlessly with Claude Code CLI

Installation and configuration

System requirements

  • Node.js 18+ or Python 3.10+
  • Claude Code CLI installed
  • ANTHROPIC_API_KEY configured

Installation

Code
Bash
# Clone the repository
git clone https://github.com/anthropics/claude-mem
cd claude-mem

# Install dependencies (Node.js)
npm install

# Or install globally
npm install -g claude-mem

# Alternatively via Python
pip install claude-mem

Initial configuration

Code
Bash
# Initialize memory
claude-mem init

# Configuration (interactive)
claude-mem config

# Or manually
cat > ~/.config/claude-mem/config.json << 'EOF'
{
  "storage": {
    "type": "local",
    "path": "~/.claude-mem/data"
  },
  "retrieval": {
    "maxItems": 20,
    "relevanceThreshold": 0.7,
    "useEmbeddings": true
  },
  "integration": {
    "autoInject": true,
    "injectPosition": "system"
  },
  "categories": [
    "project",
    "preferences",
    "decisions",
    "context",
    "todo"
  ]
}
EOF

Basic usage

Adding to memory

Code
Bash
# Basic addition
claude-mem add "The project is called CodeWorlds and it's an educational platform"

# With a category
claude-mem add --category project "Stack: Next.js 15, TypeScript, Prisma"

# With tags
claude-mem add --tags "database,schema" "The users table has fields: id, email, name, role"

# With priority
claude-mem add --priority high "IMPORTANT: Do not commit .env files"

# Interactively
claude-mem add -i
# > Category: preferences
# > Content: I prefer functional components with hooks
# > Tags: react, style
# > Added!

# From a file
cat project-context.md | claude-mem add --category project

# Bulk import from JSON
claude-mem import memories.json

Browsing memory

Code
Bash
# List all memories
claude-mem list

# Filter by category
claude-mem list --category project

# Filter by tags
claude-mem list --tags database

# Search
claude-mem search "Next.js"

# Details of a specific entry
claude-mem show mem_123456

# Export to file
claude-mem export --format json > memories.json
claude-mem export --format markdown > memories.md

Managing memory

Code
Bash
# Edit an entry
claude-mem edit mem_123456

# Delete an entry
claude-mem delete mem_123456

# Delete by category
claude-mem delete --category old-project

# Clear all memory
claude-mem clear --confirm

# Archiving
claude-mem archive --older-than 30d

# Statistics
claude-mem stats
# Memories: 156
# Categories: 5
# Most used: project (45), preferences (32)
# Storage: 2.3 MB

Integration with Claude Code

Code
Bash
# Launch Claude with memory
claude --memory

# Specify which categories to inject
claude --memory --mem-categories project,preferences

# Inject only relevant ones
claude --memory --mem-query "database schema"

# Debug mode - show what was injected
claude --memory --mem-debug

# Temporarily disable memory
claude --no-memory

Advanced features

Automatic learning

Code
Bash
# Enable auto-learning from Claude sessions
claude-mem config set autoLearn true

# Claude will automatically save:
# - Decisions made
# - Problems solved
# - Established conventions

# Example session
$ claude --memory
You: I've decided we'll use Zod for validation

Claude: Understood, I'm saving this decision. Zod will be the main
        validation library in the project.

# Automatically added to memory:
# [decision] Project uses Zod for schema validation

Semantic search

Code
Bash
# claude-mem uses embeddings for semantic search
claude-mem search "how do we handle errors"
# Will find entries about: error handling, exceptions, try-catch,
# even if they don't contain exactly those words

# Configure embeddings
claude-mem config set embeddingModel "text-embedding-3-small"
claude-mem config set similarityThreshold 0.75

Project context (project memory)

Code
Bash
# Each project can have its own memory
claude-mem init --project my-app
claude-mem add --project my-app "This project is..."

# Switching between projects
claude-mem switch my-app
claude-mem switch other-project

# Shared global memory
claude-mem add --global "My coding style is..."

# Hierarchy: project memory > global memory

Synchronization and backup

Code
Bash
# Export to backup
claude-mem backup --output ~/backups/claude-mem.tar.gz

# Import from backup
claude-mem restore ~/backups/claude-mem.tar.gz

# Sync between machines (via Git)
cd ~/.claude-mem
git init
git remote add origin git@github.com:user/my-claude-mem.git
git push -u origin main

# On another machine
git clone git@github.com:user/my-claude-mem.git ~/.claude-mem
claude-mem rebuild-index

# Cloud synchronization (experimental)
claude-mem config set sync.enabled true
claude-mem config set sync.provider "s3"
claude-mem config set sync.bucket "my-claude-mem"

API for integration

Code
TypeScript
// Using claude-mem as a library
import { ClaudeMem } from 'claude-mem'

const mem = new ClaudeMem({
  storagePath: './memory',
  embeddingModel: 'text-embedding-3-small'
})

// Add a memory
await mem.add({
  content: 'Project uses Next.js 15',
  category: 'project',
  tags: ['framework', 'nextjs'],
  priority: 'high'
})

// Search for relevant entries
const memories = await mem.search('frontend framework', {
  limit: 10,
  threshold: 0.7
})

// Generate context for Claude
const context = await mem.generateContext({
  query: 'add new component',
  maxTokens: 2000
})

// Use with Claude API
const response = await anthropic.messages.create({
  model: 'claude-sonnet-4-5-20241022',
  system: context,
  messages: [{ role: 'user', content: 'Add a Button component' }]
})
Code
Python
# Python API
from claude_mem import ClaudeMem

mem = ClaudeMem(storage_path="./memory")

# Add a memory
mem.add(
    content="Project uses FastAPI with SQLAlchemy",
    category="project",
    tags=["backend", "python"]
)

# Search
results = mem.search("database", limit=5)

# Generate context
context = mem.generate_context(
    query="add new endpoint",
    max_tokens=2000
)

Data structure

Memory entry format

Code
JSON
{
  "id": "mem_abc123def456",
  "content": "The CodeWorlds project uses Next.js 15 App Router",
  "category": "project",
  "tags": ["framework", "nextjs", "frontend"],
  "priority": "high",
  "created": "2025-01-15T10:30:00Z",
  "updated": "2025-01-15T10:30:00Z",
  "accessCount": 15,
  "lastAccessed": "2025-01-25T14:20:00Z",
  "embedding": [0.023, -0.145, 0.089, ...],
  "metadata": {
    "source": "manual",
    "project": "codeworlds",
    "confidence": 1.0
  }
}

Category organization

Code
Bash
# Recommended category structure

# project - Project information
claude-mem add --category project "Stack: Next.js, TypeScript, Prisma"

# preferences - Your coding preferences
claude-mem add --category preferences "I prefer single quotes in JS"

# decisions - Architectural decisions made
claude-mem add --category decisions "We chose Redux Toolkit over Zustand"

# context - Business context
claude-mem add --category context "The app has 50k active users"

# patterns - Patterns in use
claude-mem add --category patterns "We use the Repository Pattern for data access"

# todo - Things to do
claude-mem add --category todo "TODO: Refactor the auth module"

# issues - Known problems
claude-mem add --category issues "Bug: Memory leak in the Dashboard component"

Best practices

What to save in memory

Code
Bash
# GOOD - save these:

# Tech stack
claude-mem add --category project "Next.js 15, TypeScript strict, Prisma, PostgreSQL"

# Coding conventions
claude-mem add --category preferences "Components use PascalCase, hooks use useCamelCase"

# Architectural decisions
claude-mem add --category decisions "2025-01-15: We chose tanstack-query over SWR"

# Project structure
claude-mem add --category project "src/components/ - UI, src/features/ - business logic"

# Important constraints
claude-mem add --category context "Max 100 products per API request (rate limit)"

# Solved problems
claude-mem add --category patterns "Fix for hydration mismatch: useEffect + mounted state"

# BAD - don't save these:

# Overly detailed code
# claude-mem add "function calculateTotal() { return items.reduce(...) }"

# Temporary things
# claude-mem add "Today I'm debugging component X"

# Obvious facts
# claude-mem add "JavaScript is a programming language"

Memory maintenance

Code
Bash
# Regular reviews (e.g., once a week)
claude-mem list --sort lastAccessed
# Remove unused entries

# Consolidate similar entries
claude-mem merge mem_123 mem_456 --into "Merged entry"

# Archive old projects
claude-mem archive --project old-project

# Monitor size
claude-mem stats
# If > 1000 entries, consider a cleanup

Performance optimization

Code
Bash
# Limit the number of injected memories
claude-mem config set retrieval.maxItems 15

# Increase the relevance threshold
claude-mem config set retrieval.relevanceThreshold 0.8

# Use categories for filtering
claude --memory --mem-categories "project,decisions"

# Rebuild the index after major changes
claude-mem rebuild-index

# Compress old embeddings
claude-mem optimize --compress-old 90d

Integrations

VS Code extension

.vscode/settings.json
JSON
// .vscode/settings.json
{
  "claudeMem.enabled": true,
  "claudeMem.autoInject": true,
  "claudeMem.categories": ["project", "preferences"],
  "claudeMem.showInStatusBar": true
}

// VS Code commands:
// Ctrl+Shift+M - Add selection to memory
// Ctrl+Shift+L - List memories
// Ctrl+Shift+S - Search memory

Git hooks

Code
Bash
# .git/hooks/post-commit
#!/bin/bash
# Automatically save a commit summary

commit_msg=$(git log -1 --pretty=%B)
claude-mem add --category "commits" --tags "git,history" \
  "Commit: $commit_msg"

CI/CD integration

.github/workflows/update-mem.yml
YAML
# .github/workflows/update-mem.yml
name: Update Claude Memory

on:
  push:
    branches: [main]
    paths: ['package.json', 'tsconfig.json']

jobs:
  update-memory:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Extract project info
        run: |
          deps=$(jq -r '.dependencies | keys | join(", ")' package.json)
          echo "DEPS=$deps" >> $GITHUB_ENV

      - name: Update memory
        run: |
          claude-mem add --category project \
            "Dependencies: ${{ env.DEPS }}"

claude-mem vs alternatives

Featureclaude-memCustom fileManual prompts
PersistenceAutomaticManualNone
Semantic searchEmbeddingsNoneNone
CLI integrationNativeManualManual
OrganizationCategories/tagsFlatNone
Auto-learningOptionalNoneNone
Multi-projectYesDifficultNo
SetupModerateNoneNone
ScalingExcellentPoorPoor

Troubleshooting

Common problems

Code
Bash
# Problem: Memory is not being injected
claude-mem doctor
# Will check: configuration, connection to Claude, index

# Problem: Slow search
claude-mem rebuild-index
claude-mem optimize

# Problem: Too many irrelevant memories
claude-mem config set retrieval.relevanceThreshold 0.85

# Problem: Not enough context
claude-mem config set retrieval.maxItems 30

# Problem: Conflict between projects
claude-mem switch --project correct-project

# Problem: Corrupted index
claude-mem repair --rebuild

Debug mode

Code
Bash
# Enable detailed logs
export CLAUDE_MEM_DEBUG=1
claude --memory

# Show what was injected
claude --memory --mem-debug

# Inspect embeddings
claude-mem show mem_123 --show-embedding

# Test retrieval
claude-mem test-retrieval "add new component"

FAQ - Frequently asked questions

Are my data safe?

Yes, all data is stored locally on your machine. claude-mem does not send memories to any external services (unless you configure cloud synchronization yourself).

How many memories can I store?

There is no hard limit. It has been tested with over 10,000 entries without performance issues. It is recommended to keep fewer than 500 active memories per project for optimal relevance.

Does claude-mem consume API tokens?

Storing and searching alone does not consume Claude tokens. Tokens are only consumed when memory is injected into a Claude session (as part of the system prompt or context).

How does semantic search work?

claude-mem uses embedding models (e.g., text-embedding-3-small) to convert text into vectors. When searching, it calculates cosine similarity between the query and all entries.

Can I use claude-mem without Claude Code?

Yes, claude-mem can be used as a standalone library for knowledge management. It also has an API for integration with any Claude API client.

How do I migrate from my own note system?

Code
Bash
# Import from markdown
claude-mem import notes.md --format markdown

# Import from JSON
claude-mem import data.json

# Import from a directory
claude-mem import-dir ./my-notes --recursive

Is team usage supported?

Currently claude-mem is a single-user tool. Team synchronization is on the roadmap. Workaround: a shared Git repo with memory.

Pricing

claude-mem is completely free and open-source (MIT license).

The only costs are:

  • Claude API tokens (when injecting memory)
  • Optionally: embeddings API if you use advanced semantic search

Summary

claude-mem solves a fundamental problem of working with AI - the lack of continuity between sessions:

  • Persistent memory - Preserve context between conversations
  • Semantic search - Automatically find relevant information
  • Claude Code integration - Seamless workflow with CLI
  • Organization - Categories, tags, priorities
  • Privacy - Data stays local
  • Open-source - Free, MIT License

Start using claude-mem and stop wasting time repeating context at every session with Claude.