Sandbox
@yoloshii/ClawMem

Local memory layer for Claude Code and MCP clients

ClawMem keeps a local memory vault for agent sessions, project notes, and mined conversations. It surfaces relevant context, extracts decisions and handoffs, and shares the same SQLite store across Claude Code hooks, an MCP server, OpenClaw, and Hermes.

210 stars34 forksTypeScriptUpdated 29d ago
Who it's for

Builders who want shared memory across Claude Code, OpenClaw, Hermes, or any MCP-compatible client.

What it delivers

You can carry context, decisions, and project history from one agent session to the next without re-explaining yourself.

What it does

Hybrid retrieval

Uses BM25, vector search, query expansion, reranking, and graph traversal to find relevant context.

Session hooks

Injects context on prompt start and captures decisions, handoffs, and feedback on session end.

MCP server

Exposes memory tools through an MCP server for any compatible client.

Native plugins

Integrates as a memory plugin for OpenClaw and a MemoryProvider for Hermes.

Local SQLite vault

Keeps all memory on device and lets multiple agent runtimes share the same vault.

How to get it

  1. 1Run
    npm install -g clawmem
  2. 2If you use Bun as your package manager
    bun add -g clawmem
  3. 3Run
    git clone https://github.com/yoloshii/clawmem.git ~/clawmem
    cd ~/clawmem && bun install
    ln -sf ~/clawmem/bin/clawmem ~/.bun/bin/clawmem
  4. 4Run
    bun update -g clawmem   # or: npm update -g clawmem
  5. 5After major version updates (e.g. 0.1.x → 0.2.0) that add new enrichment pipelines, run…
    clawmem reindex --enrich  # Full enrichment: entity extraction + links + evolution for all docs
    clawmem embed             # Re-embed if upgrading embedding models (not needed for most updates)
  6. 6ClawMem integrates via hooks (settings.json) and an MCP stdio server. Hooks handle 90%…
    clawmem setup hooks    # Install lifecycle hooks (SessionStart, UserPromptSubmit, Stop, PreCompact)
    clawmem setup mcp      # Register MCP server in ~/.claude.json (33 tools)

README

ClawMem — On-device memory layer for Claude Code, OpenClaw, and Hermes agents

ClawMem

On-device memory for Claude Code, OpenClaw, Hermes, and AI agents. Retrieval-augmented search, hooks, and an MCP server in a single local system. No API keys, no cloud dependencies.

ClawMem fuses recent research into a retrieval-augmented memory layer that agents actually use. The hybrid architecture combines QMD-derived multi-signal retrieval (BM25 + vector search + reciprocal rank fusion + query expansion + cross-encoder reranking), SAME-inspired composite scoring (recency decay, confidence, content-type half-lives, co-activation reinforcement), MAGMA-style intent classification with multi-graph traversal (semantic, temporal, and causal beam search), and A-MEM self-evolving memory notes that enrich documents with keywords, tags, and causal links between entries. Pattern extraction from Engram adds deduplication windows, frequency-based durability scoring, and temporal navigation.

Integrates via Claude Code hooks, an MCP server (works with any MCP-compatible client), a native OpenClaw plugin, or a Hermes Agent MemoryProvider plugin. All paths write to the same local SQLite vault. A decision captured during a Claude Code session shows up immediately when an OpenClaw or Hermes agent picks up the same project.

TypeScript on Bun. MIT License.

What It Does

ClawMem turns your markdown notes, project docs, and research dumps into persistent memory for AI coding agents. It automatically:

  • Surfaces relevant context on every prompt (context-surfacing hook)
  • Bootstraps sessions with your profile, latest handoff, recent decisions, and stale notes
  • Captures decisions, preferences, milestones, and problems from session transcripts using a local GGUF observer model
  • Imports conversation exports from Claude Code, ChatGPT, Claude.ai, Slack, and plain text via clawmem mine, with optional post-import LLM fact extraction (--synthesize) that pulls structured decisions / preferences / milestones / problems and cross-fact links out of otherwise full-text conversation dumps (v0.7.2). Imports preserve authorship time (v0.27.0): ranking recency and temporal queries run on when content was actually written, so historical conversations mined today don't rank as fresh — with a metadata-only --backfill-dates lane for vaults mined earlier
  • Generates handoffs at session end so the next session can pick up where you left off
  • Learns what matters via a feedback loop that boosts referenced notes and decays unused ones
  • Guards against prompt injection in surfaced content
  • Classifies query intent (WHY / WHEN / ENTITY / WHAT) to weight search strategies
  • Traverses multi-graphs (semantic, temporal, causal) via adaptive beam search
  • Evolves memory metadata as new documents create or refine connections
  • Infers causal relationships between facts extracted from session observations
  • Detects contradictions between new and prior decisions, auto-decaying superseded ones — when a contradiction judge is configured (CLAWMEM_JUDGE_*, v0.29.0; disabled otherwise) (with an additional merge-time contradiction gate in the consolidation worker that blocks cross-observation contradictions before they land, v0.7.1)
  • Guards against cross-entity merges during consolidation — name-aware dual-threshold merge safety compares entity anchors before merging similar observations, preventing "Alice decided X" from merging into "Bob decided X" (v0.7.1)
  • Prevents context bleed in derived insights — the Phase 3 deductive synthesis pipeline validates every draft against an anti-contamination wrapper (deterministic entity contamination check + LLM validator + dedupe) before writing cross-session deductive observations (v0.7.1)
  • Frames surfaced facts as background knowledgecontext-surfacing wraps injected content in <instruction> + <facts> + <relationships> blocks, telling the model to treat facts as already-known and exposing memory-graph edges between surfaced docs directly in-prompt (v0.7.1)
  • Injects knowledge-graph facts as structured triples — when the user's prompt mentions entities already known to the vault, context-surfacing resolves them via a three-path prompt-only extractor (canonical IDs, proper nouns, lowercased n-grams), queries the SPO graph for current-state triples, and appends a <vault-facts> block of raw subject predicate object lines to <vault-context> — off for speed, 200 tokens on balanced, 250 on deep, token-truncated at the triple boundary (v0.9.0)
  • Session-scoped focus topic boostclawmem focus set "<topic>" --session-id <id> writes a per-session focus file that steers query expansion, reranking, chunk selection, snippet extraction, and post-composite-score topic boosting (1.4× match / 0.75× demote) for that session only — session-isolated, fail-open, never writes to SQLite or lifecycle columns (v0.9.0)
  • Scores document quality using structure, keywords, and metadata richness signals
  • Boosts co-accessed documents — notes frequently surfaced together get retrieval reinforcement
  • Decomposes complex queries into typed retrieval clauses (BM25/vector/graph) for multi-topic questions
  • Cleans stale embeddings automatically before embed runs, removing orphans from deleted/changed documents
  • Transaction-safe indexing — crash mid-index leaves zero partial state (atomic commit with rollback)
  • Deduplicates hook-generated observations within a 30-minute window using normalized content hashing, preventing memory bloat from repeated hook output
  • Navigates temporal neighborhoods around any document via the timeline tool — progressive disclosure from search to chronological context to full content
  • Boosts frequently-revised memories — documents with higher revision counts get a durability signal in composite scoring (capped at 10%)
  • Supports pin/snooze lifecycle for persistent boosts and temporary suppression
  • Manages document lifecycle — policy-driven archival sweeps with restore capability
  • Auto-routes queries via memory_retrieve — classifies intent and dispatches to the optimal search backend
  • Syncs project issues from Beads issue trackers into searchable memory
  • Runs a quiet-window heavy maintenance lane — a second consolidation worker, off by default behind CLAWMEM_HEAVY_LANE=true, that runs on a longer interval only inside a configurable hour window. Gated by context_usage query-rate so it never competes for CPU/GPU with interactive sessions, scoped exclusively via DB-backed worker_leases, stale-first by default with an optional surprisal selector, and journals every attempt in maintenance_runs for operator visibility (v0.8.0)

Runs fully local with no API keys and no cloud services. Integrates via Claude Code hooks and MCP tools, as a native OpenClaw plugin, or as a Hermes Agent MemoryProvider plugin. All modes share the same vault for cross-runtime memory. Works with any MCP-compatible client.

Full version history is in RELEASE_NOTES.md. Upgrade instructions for existing vaults are in docs/guides/upgrading.md.

Architecture

ClawMem Architecture

Install

Platform Support

PlatformStatusNotes
LinuxFull supportPrimary target. systemd services for watcher + embed timer.
macOSFull supportHomebrew SQLite handled automatically. GPU via Metal (llama.cpp).
Windows (WSL2)Full supportRecommended for Windows users. Install Bun + ClawMem inside WSL2.
Windows (native)Not recommendedBun and sqlite-vec work, but bin/clawmem wrapper is bash, hooks expect bash commands, and systemd services have no equivalent. Use WSL2 instead.

Prerequisites

Required:

  • Bun v1.0+ — runtime for ClawMem. On Linux, install via curl -fsSL https://bun.sh/install | bash (not snap — snap Bun cannot read stdin, which breaks hooks).
  • SQLite with FTS5 — included with Bun. On macOS, install brew install sqlite for extension loading support (ClawMem detects and uses Homebrew SQLite automatically).

Optional (for better performance):

  • llama.cpp (llama-server) — for dedicated GPU inference. Without it, node-llama-cpp runs models in-process (auto-downloads on first use). GPU servers give better throughput and prevent silent CPU fallback.
  • systemd (Linux) or launchd (macOS) — for persistent background services (watcher, embed timer, GPU servers). ClawMem ships systemd unit templates; macOS users can create equivalent launchd plists. See systemd services.

Optional integrations:

  • Claude Code — for hooks + MCP integration
  • OpenClaw — for native plugin integration
  • Hermes Agent — for MemoryProvider plugin integration
  • bd CLI v0.58.0+ (verified through v1.1.0) — for Beads issue tracker sync (only if using Beads)

Install from npm (recommended)

npm install -g clawmem

If you use Bun as your package manager:

bun add -g clawmem

Install from source

git clone https://github.com/yoloshii/clawmem.git ~/clawmem
cd ~/clawmem && bun install
ln -sf ~/clawmem/bin/clawmem ~/.bun/bin/clawmem

Setup roadmap

After installing, here's the full journey from zero to working memory:

StepWhatHowDetails
1. BootstrapCreate a vault, index your first collection, embed, install hooks and MCPclawmem bootstrap ~/notes --name notesOne command does it all. Or run each step manually (see below).
2. Choose modelsPick embedding + reranker models based on your hardware16GB+ VRAM → SOTA stack (zembed-1 + zerank-2 sidecar). Less → QMD native combo. No GPU → cloud embedding or CPU fallback.Inference services
3. Download modelsGet the model files for your chosen stack (GGUFs for embedding/LLM/default-reranker; the zerank-2 SOTA reranker builds its own sidecar artifact)wget from HuggingFace, let node-llama-cpp auto-download the QMD native models, or run the sidecar recipeInference services
4. Start servicesRun GPU servers (if using dedicated GPU) and background services. Optionally enable the v0.8.2 background maintenance workers in the watcher unit so consolidation + deductive synthesis run automatically.llama-server for each model. systemd units for watcher + embed timer. Drop-in for the watcher to enable workers + tune intervals + set the quiet window.systemd services, background workers
5. Decide what to indexAdd collections for your projects, notes, research, and domain docsclawmem collection add ~/project --name projectThe more relevant markdown you index, the better retrieval works. See building a rich context field.
6. Connect your agentHook into Claude Code, OpenClaw, Hermes, or any MCP clientclawmem setup hooks && clawmem setup mcp for Claude Code. clawmem setup openclaw for OpenClaw. Copy src/hermes/ to Hermes plugins for Hermes.Integration
7. VerifyConfirm everything is workingclawmem doctor (full health check) or clawmem status (quick index stats)Verify Installation

Fastest path: Step 1 alone gets you a working system with in-process CPU/GPU inference and default models — no manual model downloads or service configuration needed. Steps 2-4 are optional upgrades for better performance. Steps 5-6 are where you customize what gets indexed and how your agent connects.

Customize what gets indexed: Each collection has a pattern field in ~/.config/clawmem/config.yaml (default: **/*.md). Tailor it per collection — index project docs, research notes, decision records, Obsidian vaults, or anything else your agents should know about. The more relevant content in the vault, the better retrieval works. See the quickstart for config examples.

Quick start commands

# One command: init + index + embed + hooks + MCP
clawmem bootstrap ~/notes --name notes

# Or step by step:
clawmem init
clawmem collection add ~/notes --name notes
clawmem update --embed
clawmem setup hooks
clawmem setup mcp

# Add more collections (the more you index, the richer retrieval gets)
clawmem collection add ~/projects/myapp --name myapp
clawmem collection add ~/research --name research
clawmem update --embed

# Verify
clawmem doctor

Upgrading

bun update -g clawmem   # or: npm update -g clawmem

Database schema migrates automatically on next startup (new tables and columns are added via CREATE IF NOT EXISTS / ALTER TABLE ADD COLUMN).

After major version updates (e.g. 0.1.x → 0.2.0) that add new enrichment pipelines, run a full enrichment pass to backfill existing documents:

clawmem reindex --enrich  # Full enrichment: entity extraction + links + evolution for all docs
clawmem embed             # Re-embed if upgrading embedding models (not needed for most updates)

--enrich forces the complete A-MEM pipeline (entity extraction, link generation, memory evolution) on all documents, not just new ones. Without it, reindex only refreshes metadata for existing docs.

Routine patch updates (e.g. 0.2.0 → 0.2.1) do not require reindexing.

For version-specific upgrade notes (opt-in features, optional cleanup steps, verification commands), see docs/guides/upgrading.md.

Integration

Claude Code

ClawMem integrates via hooks (settings.json) and an MCP stdio server. Hooks handle 90% of retrieval automatically - the agent never needs to call tools for routine context.

clawmem setup hooks    # Install lifecycle hooks (SessionStart, UserPromptSubmit, Stop, PreCompact)
clawmem setup mcp      # Register MCP server in ~/.claude.json (33 tools)

Automatic (90%): context-surfacing injects relevant memory on every prompt. postcompact-inject re-injects state after compaction. decision-extractor, handoff-generator, feedback-loop capture session state on stop.

Agent-initiated (10%): MCP tools (query, intent_search, find_causal_links, timeline, etc.) for targeted retrieval when hooks don't surface what's needed.

OpenClaw

ClawMem registers as a native OpenClaw memory plugin (kind: memory, v0.10.0+). Same 90/10 automatic retrieval, delivered through OpenClaw's plugin-hook bus instead of Claude Code hooks.

# v0.10.4+: profile-aware. Delegates to `openclaw plugins install --force` when the OpenClaw CLI
# is on PATH (auto-enables the plugin, honors OPENCLAW_STATE_DIR, OPENCLAW_CONFIG_PATH, --profile).
# Falls back to a recursive copy honoring OPENCLAW_STATE_DIR when the CLI is absent.
clawmem setup openclaw

# Custom profile (e.g. dev profile at ~/.openclaw-dev):
OPENCLAW_STATE_DIR=~/.openclaw-dev clawmem setup openclaw

What the plugin provides:

  • before_prompt_build hook (load-bearing) - prompt-aware retrieval (context-surfacing + session-bootstrap) AND the pre-emptive precompact-extract run when token usage approaches the compaction threshold. This is the authoritative path for precompact state capture because it runs synchronously before the LLM call that would trigger compaction, so it cannot race the compactor.
  • agent_end hook - decision extraction, handoff generation, feedback loop (parallel, fire-and-forget at the OpenClaw call site). OpenClaw v2026.4.26+ also enforces a 30s default void-hook timeout on agent_end — slow handlers are logged but the underlying postrun work is not cancelled (fail-open).
  • before_compaction hook (defense-in-depth fallback) - fires precompact-extract again for the rare case where before_prompt_build's proximity heuristic missed a sudden token-count jump. Fire-and-forget at OpenClaw's call site, so it races the compactor and offers no correctness guarantee on its own — the before_prompt_build path is what actually holds the invariant.
  • session_start hook - session registration + cached first-turn bootstrap context
  • 5 agent tools - clawmem_search, clawmem_get, clawmem_session_log, clawmem_timeline, clawmem_similar

Disable OpenClaw's native memory search to avoid duplicate injection:

openclaw config set agents.defaults.memorySearch.extraPaths "[]"

ClawMem coexists cleanly with OpenClaw's Active Memory plugin (v2026.4.10+) and, on OpenClaw v2026.4.18+ (#65411), with the memory-core dreaming sidecar — both run alongside ClawMem instead of being mutually exclusive. They search different backends and inject into different prompt regions, so they do not conflict. See the OpenClaw plugin guide — Active Memory coexistence and the memory-core dreaming sidecar section for the two patterns.

Pair ClawMem (memory) with a context-engine plugin (v0.10.0+). OpenClaw and Hermes maintainers have converged on a two-surface plugin model: one slot for memory plugins (cross-session, retrieval-first) and a separate slot for context-engine plugins (in-session, compression/compaction-first). Under that model ClawMem is a memory layer — it has always been one in Hermes via the MemoryProvider ABC, and v0.10.0 moves the OpenClaw integration to the same semantic slot. You can now run ClawMem in the memory slot alongside an LCM-style compression plugin (for example, lossless-claw) in the context-engine slot. The two plugins do not overlap: one persists across sessions, the other reshapes the live window. See the OpenClaw plugin guide — memory vs context engine for the full rationale.

OpenClaw v2026.4.11+ recommended (required for ClawMem v0.10.0+). v2026.4.11 introduced a new plugin discovery contract that requires each plugin directory to ship a package.json with openclaw.extensions declared, and that rejects symlinked plugin directories. ClawMem v0.10.0 includes both fixes. Older ClawMem versions (< v0.10.0) on OpenClaw v2026.4.11+ will fail to discover silently — upgrade ClawMem, then re-run clawmem setup openclaw. See docs/guides/upgrading.md.

Alternative: OpenClaw agents can also use ClawMem's MCP server directly (clawmem setup mcp), with or without hooks. This gives full access to all 33 MCP tools but bypasses OpenClaw's plugin lifecycle, so you lose token budget awareness, native compaction orchestration, and the agent_end message pipeline. The native OpenClaw plugin is recommended for new setups; MCP is available as an additional or standalone integration.

Hermes Agent

ClawMem integrates as a native MemoryProvider plugin — Hermes's pluggable interface for agent memory. Same automatic retrieval and extraction, delivered through Hermes's memory lifecycle instead of Claude Code hooks.

Install:

# Preferred — user-plugin path (Hermes #10529, v2026.4.13+).
# Survives `git pull` of hermes-agent and avoids dual-registration with bundled providers.
cp -r /path/to/ClawMem/src/hermes ${HERMES_HOME:-~/.hermes}/plugins/clawmem

# Or, the bundled-style path (always supported, takes precedence on name collisions).
# Recommended only when you actively work in the hermes-agent source tree.
cp -r /path/to/ClawMem/src/hermes /path/to/hermes-agent/plugins/memory/clawmem

# Symlink alternative for in-place development (either path).
ln -s /path/to/ClawMem/src/hermes ${HERMES_HOME:-~/.hermes}/plugins/clawmem

Configure in your Hermes profile's .env or environment:

CLAWMEM_BIN=/path/to/clawmem          # Path to clawmem binary (or ensure it's on PATH)
CLAWMEM_SERVE_PORT=7438                # REST API port (default: 7438)
CLAWMEM_SERVE_MODE=external            # "external" (you run clawmem serve) or "managed" (plugin manages it)
CLAWMEM_PROFILE=balanced               # speed | balanced | deep

Then set memory.provider: clawmem in your Hermes config.yaml, or run hermes memory setup to configure interactively.

What the plugin provides:

  • prefetch() — prompt-aware retrieval via context-surfacing hook (automatic every turn)
  • on_session_end() — decision extraction, handoff generation, feedback loop (parallel)
  • on_pre_compress() — pre-compaction state preservation
  • session-bootstrap — session registration + first-turn context injection
  • 5 agent toolsclawmem_retrieve, clawmem_get, clawmem_session_log, clawmem_timeline, clawmem_similar
  • Plugin-managed transcript — maintains its own JSONL transcript for ClawMem hooks

Requirements: clawmem binary on PATH and clawmem serve running (external mode) or the plugin starts it automatically (managed mode). Python 3.10+. No pip dependencies beyond Hermes itself (uses urllib for REST calls, httpx optional for better performance).

Alternative: Hermes also has built-in MCP client support. You can add ClawMem as an MCP server in Hermes's config.yaml under mcp_servers for tool-only access. But this misses the lifecycle hooks (prefetch, session_end, pre_compress), so the native plugin is recommended.

See Hermes plugin guide for architecture details, lifecycle mapping, and troubleshooting.

Multi-Framework Operation

All three integrations share the same SQLite vault by default. Claude Code, OpenClaw, and Hermes can run simultaneously — decisions captured in one runtime are immediately available in the others, giving agents persistent shared memory across sessions and platforms. WAL mode + busy_timeout handles concurrent access.

Multi-Vault (Optional)

By default, ClawMem uses a single vault at ~/.cache/clawmem/index.sqlite. For users who want separate memory domains (e.g., work vs personal, or isolated vaults per project), ClawMem supports named vaults.

Configure in ~/.config/clawmem/config.yaml:

vaults:
  work: ~/.cache/clawmem/work.sqlite
  personal: ~/.cache/clawmem/personal.sqlite

Or via environment variable:

export CLAWMEM_VAULTS='{"work":"~/.cache/clawmem/work.sqlite","personal":"~/.cache/clawmem/personal.sqlite"}'

Using vaults with MCP tools:

All retrieval tools (memory_retrieve, query, search, vsearch, intent_search) accept an optional vault parameter. Omit it to use the default vault.

# Search the default vault (no vault param needed)
query("authentication flow")

# Search a named vault
query("project timeline", vault="work")

# List configured vaults
list_vaults()

# Sync content into a vault
vault_sync(vault="work", content_root="~/work/docs")

Single-vault users: No action needed. Everything works without configuration. The vault parameter is always optional and ignored when no vaults are configured.

Inference

Files in the repo

Repository payload25 top-level entries
  • .github
  • agents
  • bin
  • docs
  • eval-bundles
  • extras
  • scripts
  • src
  • tests
  • .env.example
  • .gitignore
  • AGENTS.md
  • bun.lock
  • bunfig.toml
  • CLAUDE.md
  • CODE_OF_CONDUCT.md
  • CONTRIBUTING.md
  • googledd6f95190aef61f7.html
  • LICENSE
  • package.json
  • README.md
  • RELEASE_NOTES.md
  • SECURITY.md
  • SKILL.md
  • tsconfig.json

Discussion (0)

Ask about usage, or say what you built with it

Sign in to join the discussion.

No comments yet. Be the first to say what this is good for.

More connectors

Real-time global intelligence dashboard. AI-powered news aggregation, geopolitical monitoring, and infrastructure tracking in a unified situational awareness interface

86k

High-performance code intelligence MCP server. Indexes codebases into a persistent knowledge graph — average repo in milliseconds. 158 languages, sub-ms queries, 99% fewer tokens. Single static binary, zero dependencies.

43k

Universal provider proxy for OpenAI Codex & Claude Code — use any LLM (Claude, Gemini, Grok, DeepSeek, Ollama…) with Codex CLI, App, SDK, and Claude Code

14k
okf-memory/
okf-agent-memory

Git-native persistent memory for AI coding agents. Implements Google OKF v0.2 with sub-300µs in-memory BM25 search, embedded MCP server, and progressive disclosure. Slashes token bloat by 80% with zero external databases or dependencies. Built in pure Go.

547
tirth8205/
code-review-graph

Local-first code intelligence graph for MCP and CLI. Builds a persistent map of your codebase so AI coding tools read only what matters, with benchmarked context reductions on reviews and large-repo workflows.

31k
2akouwu/
reverify

Stop your AI from making things up — it proposes, deterministic tools decide, every claim checked against ground truth with evidence. Grounded facts and context survive resets. Reverse engineering is the proving ground. MCP server + CLI.

1.1k