ClawMem — On-device memory layer for Claude Code, OpenClaw, and Hermes agents
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 -derived multi-signal retrieval (BM25 + vector search + reciprocal rank fusion + query expansion + cross-encoder reranking), -inspired composite scoring (recency decay, confidence, content-type half-lives, co-activation reinforcement), -style intent classification with multi-graph traversal (semantic, temporal, and causal beam search), and self-evolving memory notes that enrich documents with keywords, tags, and causal links between entries. Pattern extraction from adds deduplication windows, frequency-based durability scoring, and temporal navigation.
On-device memory layer for AI agents. Claude Code, OpenClaw and Hermes. Hooks + MCP server + hybrid RAG search.
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 knowledge — context-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 — clawmem focus set "<topic>" --session-id <id> writes a per-session focus file used as a snippet-selection intent: surfaced docs prefer sentences matching the topic. Presentation only since v0.38.0 — a focus never changes expansion, reranking, scoring, ordering, or the surfaced set — session-isolated, fail-open, never writes to SQLite or lifecycle columns (v0.9.0, narrowed v0.38.0)
Ranks hook injections on one channel-aware key — every retrieval leg (BM25, vector, file-aware, gated prior-turn, expansion variants) contributes a ranked lane; weighted reciprocal-rank fusion yields a single ordering key (current-support band, fused mass) that decides membership, final order, AND admission — no mixed raw-score sorts, no metadata reordering (v0.38.0)
Admits by relevance, abstains honestly — the context-surfacing hook admits candidates by a relative floor on the fused ordering key and abstains at query level when current-turn support is missing or keyword-degenerate, instead of surfacing weak lists (v0.38.0)
Guards the deep rerank lane — cross-encoder scores apply only under full candidate coverage AND a discriminating score set (degeneracy gate); the reranker joins the final order as a rank-fused lane, and remote rerank scores are cached only under an attested provider identity (clawmem rerank-health) (v0.38.0)
Keeps the hook's write path off your prompt latency — turn alignment is one early fail-closed row; recall attribution, token accounting, and vault mirrors are handed to a detached drainer process through an on-disk spool after the payload is emitted (v0.38.0)
Scores document quality using structure, keywords, and metadata richness signals
Boosts co-accessed documents — notes the agent verifiably referenced together in one turn (v0.41.0) get retrieval reinforcement on the composite MCP surfaces (removed from hook ordering in v0.38.0 — the injected order is the channel-aware fusion key alone)
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)
Processes each turn once — the extraction and handoff hooks keep a cursor per transcript and the feedback hook decides each surfaced turn once (v0.41.0), so a turn is extracted, summarised and credited once instead of again at every response, and each session's documents are its own
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.
Primary target. systemd services for watcher + embed timer.
macOS
Full support
Homebrew SQLite handled automatically. GPU via Metal (llama.cpp).
Windows (WSL2)
Full support
Recommended for Windows users. Install Bun + ClawMem inside WSL2.
Windows (native)
Not recommended
Bun 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.
Run 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.
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 (backfill) + links + evolution for all docs
clawmem embed # Re-embed if upgrading embedding models (not needed for most updates)
--enrich runs the complete A-MEM pipeline (entity extraction, link generation, memory evolution) on all documents, not just new ones; entity extraction inside it skips a document unchanged since its last extraction (enrichment lifecycle). 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.
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.
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.
# Copies the directory's CONTENTS, so the same command installs and upgrades.
mkdir -p "${HERMES_HOME:-$HOME/.hermes}/plugins/clawmem"
cp -r /path/to/ClawMem/src/hermes/. "${HERMES_HOME:-$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.
mkdir -p /path/to/hermes-agent/plugins/memory/clawmem
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)
sync_turn() — appends the turn to the plugin's transcript, then runs decision extraction, handoff generation and the feedback loop over it in the background (v0.41.0: after every turn; each turn is processed once)
on_session_end() — a last pass, then the SessionEnd handoff flush
on_pre_compress() — pre-compaction state preservation
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.
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 services (GPU, in-process, or cloud)
ClawMem uses three inference services — embedding, LLM (query expansion / intent / A-MEM / the Stop hooks' observer), and reranker. In the default stack all three run as llama-server instances, each with an in-process node-llama-cpp fallback that auto-downloads on first use, so ClawMem works without a dedicated GPU (Metal on Apple Silicon, Vulkan where available, CPU as last resort). The bin/clawmem wrapper points at localhost:8088/8089/8090. Always run via bin/clawmem — it sets the endpoints.
zembed-1 + qmd-query-expansion-1.7B + zerank-2 (Q8_0 GGUF that carries its score head)
~13 GB
Apache-2.0 — commercial OK
16 GB+ GPU; best recall
Cloud embedding
Jina / OpenAI / Voyage / Cohere (embedding only)
none
provider ToS
No local GPU for embedding; LLM + reranker stay local
Heads-up before you serve: most zerank-2 GGUFs are inert — llama.cpp's standard converter drops the score head. Serve the Q8_0 GGUF that carries it (launch line) or the bf16 seq-cls sidecar, and verify with clawmem rerank-health. zembed-1 / reranking need -ub = -b (non-causal attention). Changing embedding dimensions requires clawmem embed --force. Set CLAWMEM_NO_LOCAL_MODELS=true to fail fast instead of silent CPU fallback.
Active-document export as JSON (?full=true includes legacy precompact-state.md snapshot copies)
POST
/reindex
Trigger re-scan
POST
/graphs/build
Rebuild temporal + semantic graphs
Auth (v0.42.0): every request needs Authorization: Bearer <token>: CLAWMEM_API_TOKEN when set (32+ characters), otherwise the token file serve generates at ~/.config/clawmem/serve-token; clawmem serve-token prints it. Every POST needs Content-Type: application/json, and requests from web pages (a foreign Origin or Host) are refused. See the REST API reference.
./bin/clawmem doctor # Full health check
./bin/clawmem status # Quick index status
bun test # Run test suite (from the repository root)
Agent Instructions
ClawMem ships agent instruction files and an optional maintenance agent:
File
Loaded
Purpose
AGENTS.md
Automatically (most agents, when working in this repo)
Lean root SSOT — agent-facing quick reference (inference at a glance, install, retrieval routing, MCP tools, indexing rules, integrations) + an index into docs/
CLAUDE.md
Automatically (Claude Code)
@AGENTS.md import — Claude Code reads CLAUDE.md natively, so it just pulls in the SSOT
SKILL.md
On-demand (agent reads when needed)
Portable operating reference — escalation gate, tool routing, the 4 query-optimization levers, pipeline behavior, composite scoring, lifecycle. Shipped with the package for cross-project use
docs/
On-demand (linked throughout AGENTS.md)
Deep reference — inference setup, configuration, concepts, internals, guides, troubleshooting
Working in the ClawMem repo: No action needed — CLAUDE.md (which imports AGENTS.md) loads automatically.
Using ClawMem from other projects: Your agent needs instructions on how to use ClawMem's hooks and MCP tools. Two options:
Option A: Copy instructions into your project
Copy the contents of AGENTS.md (or the relevant sections) into your project's own AGENTS.md or CLAUDE.md. Simple but requires manual updates when ClawMem changes.
Option B: Add a trigger block (recommended)
Add this minimal trigger block to your global ~/.claude/CLAUDE.md. It gives the agent routing rules always loaded, and tells it how to find the full reference (SKILL.md) shipped with your installation when deeper guidance is needed:
## ClawMem
Architecture: hooks (automatic, ~90%) + MCP tools (explicit, ~10%).
Vault: `~/.cache/clawmem/index.sqlite` | Config: `~/.config/clawmem/config.yaml`
### Escalation Gate (3 rules — ONLY escalate to MCP tools when one fires)
1. **Low-specificity injection** — `<vault-context>` is empty or lacks the specific fact needed
2. **Cross-session question** — "why did we decide X", "what changed since last time"
3. **Pre-irreversible check** — before destructive or hard-to-reverse changes
### Tool Routing (once escalated)
**Preferred:** `memory_retrieve(query)` — auto-classifies and routes to the optimal backend.
**Direct routing** (when calling specific tools):
"why did we decide X" → intent_search(query) NOT query()
"what happened last session" → session_log() NOT query()
"what else relates to X" → find_similar(file) NOT query()
Complex multi-topic → query_plan(query) NOT query()
General recall → query(query, compact=true)
Keyword spot check → search(query, compact=true)
Conceptual/fuzzy → vsearch(query, compact=true)
Full content → multi_get("path1,path2")
Lifecycle health → lifecycle_status()
Stale sweep → lifecycle_sweep(dry_run=true)
Restore archived → lifecycle_restore(query)
ALWAYS `compact=true` first → review → `multi_get` for full content.
### Proactive Use (no escalation gate needed)
- User says "remember this" / critical decision made → `memory_pin(query)` immediately
- User corrects a misconception → `memory_pin(query)` the correction
- `<vault-context>` surfaces irrelevant/noisy content → `memory_snooze(query, until)` for 30 days
- Need to correct a memory → `memory_forget(query)`
- After bulk ingestion → `build_graphs`
### Anti-Patterns
- Do NOT use `query()` for everything — match query type to tool, or use `memory_retrieve`
- Do NOT call query/intent_search every turn — 3 rules above are the only gates
- Do NOT re-search what's already in `<vault-context>`
- Do NOT pin everything — pin is for persistent high-priority items, not routine decisions
- Do NOT forget memories to "clean up" — let confidence decay handle it
- Do NOT wait for curator to pin decisions — pin immediately when critical
For detailed operating guidance (escalation gate, tool routing, query-optimization levers, pipeline behavior, composite scoring, lifecycle), find and read the shipped SKILL.md (setup, inference, and internals live in AGENTS.md + docs/):
Bash: CLAWMEM_ROOT=$(cd "$(dirname "$(which clawmem)")/.." && pwd) && echo "$CLAWMEM_ROOT/SKILL.md"
Then: Read the file at that path.
This gives your agent the 3-rule gate, tool routing, and proactive behaviors always loaded. When it needs deeper guidance, it locates and reads the full SKILL.md reference shipped with your installation — no symlinks or skill registration required.
CLI Reference
clawmem init Create DB + config
clawmem bootstrap <vault> [--name N] [--skip-embed] One-command setup
clawmem collection add <path> --name <name> Add a collection
clawmem collection list List collections
clawmem collection remove <name> Remove a collection
clawmem update [--pull] [--embed] Incremental re-scan
clawmem mine <dir> [-c name] [--embed] [--synthesize] Import conversation exports (--synthesize runs post-import LLM fact extraction, v0.7.2; preserves per-exchange authored_at, v0.27.0)
clawmem mine <dir> -c name --backfill-dates [--apply] Derive authored_at for already-mined docs (metadata-only; dry-run without --apply)
clawmem embed [-f] Generate fragment embeddings
clawmem reindex [--force] Full re-index
clawmem watch File watcher daemon
clawmem search <query> [-n N] [--json] BM25 keyword search
clawmem vsearch <query> [-n N] [--json] Vector semantic search
clawmem query <query> [-n N] [--json] Full hybrid pipeline
clawmem profile Show user profile
clawmem profile rebuild Force profile rebuild
clawmem update-context Regenerate per-folder CLAUDE.md
clawmem list [-n/--limit N] [-c col] [--json] Browse recent documents
clawmem budget [--session ID] Token utilization
clawmem log [--last N] Session history
clawmem hook <name> Manual hook trigger
clawmem surface --context --stdin IO6: pre-prompt context injection
clawmem surface --bootstrap --stdin IO6: per-session bootstrap injection
clawmem reflect [N] Cross-session reflection (last N days, default 14)
clawmem consolidate [--dry-run] [N] Find and archive duplicate low-confidence docs
clawmem eval run --gold <file.jsonl> Offline eval: replay gold-labeled queries, score J_doc/recall/MRR
clawmem install-service [--enable] [--remove] Systemd watcher service
clawmem setup hooks [--remove] Install/remove Claude Code hooks
clawmem setup mcp [--remove] Register/remove MCP server
clawmem setup curator [--remove] Install/remove curator maintenance agent
clawmem mcp Start stdio MCP server
clawmem serve [--port 7438] [--host 127.0.0.1] [--no-token] Start HTTP REST API server (token required)
clawmem serve-token Print the token serve uses
clawmem path Print database path
clawmem doctor Full health check
clawmem status Quick index status
MCP Tools (31)
Registered by clawmem setup mcp. Available to any MCP-compatible client.
Internal-collection visibility (v0.21.0): the retrieval tools search, vsearch, query, query_plan, memory_retrieve, and find_similar (plus memory_rank since v0.36.0) exclude the system-internal _clawmem collection by default — pass includeInternal: true (or name _clawmem in an explicit collection filter where the tool has one) to include it. find_similar auto-includes internal neighbors when the reference document is itself internal; intent_search, find_causal_links, kg_query, session_log, and timeline are unfiltered by design. Full contract (including the degraded under-fill markers): docs/reference/mcp-tools.md.
Tool
Description
__IMPORTANT
Workflow guide: prefer memory_retrieve → match query type to tool → multi_get for full content
Core Search & Retrieval
Tool
Description
memory_retrieve
Preferred entry point. Auto-classifies query and routes to optimal backend (query, intent_search, session_log, find_similar, or query_plan). Use instead of manually choosing a search tool.
search
BM25 keyword search — for exact terms, config names, error codes, filenames. v0.24.0: non-recency queries rank by the RAW BM25 transform (scoreBasis: "fts-bm25"; judged keyword eval MRR 0.848 vs composite 0.415; metadata breaks exact ties only; minScore filters raw, no default); recency-intent queries keep composite. Collection filter supports comma-separated values. Prefer memory_retrieve for auto-routing.
vsearch
Vector semantic search — for conceptual/fuzzy matching when exact keywords are unknown. v0.22.0: non-recency queries rank by RAW cosine (scoreBasis: "vector-cosine"; metadata breaks exact ties only; minScore filters raw with no default); recency-intent queries keep composite. Collection filter supports comma-separated values. Prefer memory_retrieve for auto-routing.
query
Full hybrid pipeline (BM25 + vector + rerank) — general-purpose when query type is unclear. WRONG for "why" questions (use intent_search) or cross-session queries (use session_log). Prefer memory_retrieve for auto-routing. Intent hint, strong-signal bypass, chunk dedup, candidateLimit, MMR diversity, compact mode.
get
Retrieve single document by path or docid
multi_get
Retrieve multiple docs by glob or comma-separated list
find_similar
USE THIS for "what else relates to X", "show me similar docs". Finds k-NN vector neighbors — discovers connections beyond keyword overlap that search/query cannot find.
Intent-Aware Search
Tool
Description
intent_search
USE THIS for "why did we decide X", "what caused Y", "who worked on Z". Classifies intent (WHY/WHEN/ENTITY/WHAT), traverses causal + semantic graph edges. Returns decision chains that query() cannot find.
query_plan
USE THIS for complex multi-topic queries ("tell me about X and also Y", "compare A with B"). Decomposes into parallel typed clauses (bm25/vector/graph), executes each, merges via RRF. query() searches as one blob — this tool splits topics and routes each optimally.
query_plan pipeline: Query → LLM decomposition into 2-4 typed clauses → Parallel execution (BM25/vector/graph per clause) → RRF merge across clauses → Composite scoring. Falls back to single-query for simple inputs.
Multi-Graph & Causal
Tool
Description
build_graphs
Build temporal and/or semantic graphs from document corpus
find_causal_links
Trace decision chains: "what led to X", "how we got from A to B". Follow up intent_search with this tool on a top result to walk the full causal chain. Traverses causes / caused_by / both up to N hops with depth-annotated reasoning.
kg_query
Query the SPO knowledge graph: "what does X relate to?", "what was true about X when?". Returns temporal entity-relationship triples with validity windows. Accepts an entity name or a canonical ID in vault:type:slug form; an exact name wins over a partial match, and entities that share the name are listed separately (resolution). Triples are populated by the decision-extractor hook from observer-emitted <triples> blocks.
memory_evolution_status
Show how a document's A-MEM metadata evolved over time
timeline
Show the temporal neighborhood around a document — what was created/modified before and after it. Progressive disclosure: search → timeline (context) → get (full content). Supports same-collection scoping and session correlation.
Beads Integration
Tool
Description
beads_sync
Sync Beads issues from Dolt backend (bd CLI) into memory: syncs the full backlog (no 50-issue cap), creates docs, bridges all dep types to memory_relations, surfaces bd ≥1.1.0 claim leases, runs A-MEM enrichment
Vault Management
Tool
Description
list_vaults
Show configured vault names and paths. Empty in single-vault mode.
vault_sync
Index markdown from a directory into a named vault. Restricted-path validation rejects sensitive directories.
Agent Diary
Tool
Description
diary_write
Write a diary entry. Use for recording important events, decisions, or observations in environments without hook support. Stored as searchable memories.
diary_read
Read recent diary entries. Filter by agent name.
Memory Management & Lifecycle
Tool
Description
memory_forget
Search → deactivate closest match (with audit trail). Weak matches return a disambiguation list instead of acting (v0.23.0)
memory_pin
Pin a memory: lifecycle retention + priority among relevance-equivalent results (+0.3 composite boost on hook/query surfaces; exact-tie precedence on the raw routes — vector + search non-recency). USE PROACTIVELY when: user states a persistent constraint, makes an architecture decision, or corrects a misconception. Don't wait for curator — pin critical decisions immediately.
memory_snooze
Temporarily hide a memory from context surfacing until a date. USE PROACTIVELY when <vault-context> repeatedly surfaces irrelevant content — snooze for 30 days instead of ignoring it.
Lifecycle + ranking-metadata aggregates per collection (v0.36.0): origin×active cross-tabs, pinned, accrual, deactivation reasons, and access/confidence/quality/effective-age distributions (mean/median/min/max over active rows). Deeper than index_stats; includes system collections.
memory_rank
Ranking diagnostic (v0.36.0): real-pipeline composite breakdown per result — weights, recency, confidence blend, quality/length/frequency/canonical multipliers, signed pinΔ, co-activation — plus raw-vs-composite rank shifts; demoted raw winners stay visible. FTS-only candidates; read-only.
session_log
USE THIS for "last time", "yesterday", "what happened", "what did we do". Returns session history with handoffs and file changes. DO NOT use query() for cross-session questions — this tool has session-specific data that search cannot find.
profile
Current static + dynamic user profile
lifecycle_status
Document lifecycle statistics: active, archived, forgotten, pinned, snoozed counts, the deactivation-reason breakdown, and policy summary
lifecycle_sweep
Run lifecycle policies: archive stale docs past retention threshold. Archives only — never deletes. Defaults to dry_run (preview only)
lifecycle_restore
Restore documents that were auto-archived by lifecycle policies. Filter by query, collection, or restore all
ClawMem never physically deletes a document row (v0.30.0). Forget and archive deactivate; lifecycle_restore reverses archival; purge_after_days is inert. Through v0.29.0 a configured retention window permanently deleted archived rows from a non-dry-run sweep and from the SessionStart hook, without reporting it — see upgrading.
Compact Mode
search, vsearch, and query accept compact: true to return { id, path, title, score, snippet, content_type, fragment } instead of full content. Saves ~5x tokens for initial filtering.
Re-injects context after compaction, framed as reference data: this session's pre-compaction state + recent decisions + antipatterns + vault context (1200 token budget)
curator-nudge
SessionStart
Surfaces curator report actions, nudges when report is stale (>7 days)
precompact-extract
PreCompact
Extracts the last typed request, decisions, file paths and open questions before compaction → the vault's session-keyed compaction_state row, taken once by the same session's postcompact-inject
decision-extractor
Stop
GGUF observer extracts structured observations (decisions, preferences, milestones, problems, bugfixes, features, refactors, discoveries) from the turns after its per-transcript cursor, each turn once (v0.41.0), into the session's own decision and antipattern docs; detects contradictions with prior decisions (judge-gated — requires CLAWMEM_JUDGE_*, v0.29.0)
handoff-generator
Stop
Digests each new turn without a model, then folds the digests into an incremental, throttled observer summary → the session's handoff
handoff-generator
SessionEnd
Renders the handoff's latest turns at session end (no transcript read, no model; v0.41.0)
feedback-loop
Stop
Silently credits each surfaced note once per turn when that turn verifiably names it (path, file name or rendered title): access count, co-activation + usage relations among the notes that turn referenced, utility signals (surfaced vs referenced ratio for lifecycle automation)
Additional hooks available but not installed by default:
Hook
Event
Why Not Default
session-bootstrap
SessionStart
Injects ~2000 tokens before user types anything. context-surfacing on first prompt is more precise.
staleness-check
SessionStart
Redundant without session-bootstrap (stale notes are part of its output).
pretool-inject
PreToolUse
Disabled in HOOK_EVENT_MAP (cannot inject additionalContext via PreToolUse).
Hooks handle ~90% of retrieval automatically. For agent escalation logic (when to use MCP tools vs rely on hooks), see CLAUDE.md.
Search Pipeline
User Query + optional intent hint
→ BM25 Probe → Strong Signal Check (skip expansion if top hit ≥ 0.85 with gap ≥ 0.15; disabled when intent provided)
→ Query Expansion (intent steers LLM prompt when provided)
→ BM25 + Vector Search (parallel, original query 2× weight)
→ Reciprocal Rank Fusion → slice to candidateLimit (default 30)
→ Intent-Aware Chunk Selection (intent terms at 0.5× weight alongside query terms at 1.0×)
→ Cross-Encoder Reranking (4000 char context; intent prepended; chunk dedup; batch cap=4)
→ Rerank/RRF Blend (blendRerank: 0.9·reranker + 0.1·normalized-RRF tiebreaker; reranker can promote over RRF #1; falls back to RRF order if reranker unavailable)
→ Composite Scoring (query-tuned: (search × 0.70 + recency × 0.15 + confidence × 0.15) × qualityMultiplier × lengthNorm × coActivationBoost + pinBoost; recency-intent queries → 0.10/0.70/0.20; other tools keep the 0.50/0.25/0.25 default)
→ MMR Diversity Filter (Jaccard bigram similarity > 0.6 → demoted)
→ Ranked Results
For agent-facing query optimization (tool selection, query string quality, intent parameter, candidateLimit), see CLAUDE.md.
Multi-Graph Traversal
For WHY and ENTITY queries, the search pipeline expands results through the memory graph:
Start from top-10 baseline results as anchor nodes
For each frontier node: get neighbors via any relation type
Contradicts — LLM-analyzed document relationships. Additional contradicts edges are inserted by Phase 3 deductive synthesis when a new draft contradicts a prior deductive observation. (Phase 2's merge-time gate does not insert edges — a blocked merge under link sets the old consolidated row's invalidated_by backlink instead.)
Content Type Scoring
Type
Half-life
Baseline
Notes
decision
180d
0.85
Very slow ranking decay (§36.11) — silently-abandoned decisions stop winning ranking; attention-decay-exempt; lifecycle policy separate
deductive
∞
0.85
Never decays — cross-session derived insights with source provenance
preference
∞
0.80
Never decays — user preferences are durable facts
hub
∞
0.80
Never decays
antipattern
∞
0.75
Never decays — accumulated negative patterns persist
problem
60 days
0.75
High priority but resolves over time
research
90 days
0.70
milestone
60 days
0.70
Important at the time, fades as project moves forward
project
120 days
0.65
handoff
30 days
0.60
Fast decay — most recent matters
conversation
45 days
0.55
Imported chat exchanges
progress
45 days
0.50
note
60 days
0.50
Default
Content types are inferred from frontmatter or file path patterns. Half-lives extend up to 3× for frequently-accessed memories (access reinforcement, decays over 90 days). Non-durable types (handoff, progress, conversation, note, project) lose 5% confidence per week without access (attention decay). Decision/deductive/preference/hub/research/antipattern are exempt.
Quality scoring: Each document gets a quality_score (0.0–1.0) computed during indexing based on length, structure (headings, lists), decision/correction keywords, and frontmatter richness. Applied as qualityMultiplier = 0.7 + 0.6 × qualityScore (range: 0.7× penalty to 1.3× boost).
Length normalization:1/(1 + 0.5 × log2(max(bodyLength/500, 1))) — penalizes verbose entries that dominate via keyword density. Floor at 30% of original score.
Frequency boost: Documents with higher revision counts or duplicate counts get a durability signal: freqSignal = (revisions - 1) × 2 + (duplicates - 1), freqBoost = min(0.10, log1p(freqSignal) × 0.03). Revision count (content evolution) is weighted 2× vs duplicate count (ingest repetition). Capped at 10%.
Pin boost: Pin = lifecycle retention + priority among relevance-equivalent results. On composite surfaces pinned documents get a +0.3 additive boost (capped at 1.0); on the raw routes — the vector tools (v0.22.0) and non-recency search (v0.24.0) — pin breaks exact raw-score ties only. Use memory_pin to pin critical memories.
Snooze: Snoozed documents are filtered out of context surfacing until their snooze date. Use memory_snooze for temporary suppression.
Contradiction detection (judge-gated, v0.29.0): Contradiction analysis runs only when a judge is configured via CLAWMEM_JUDGE_* — without one it is disabled as an audited no-op, because the stock expansion model cannot meet the judge contract (details). With a judge: when decision-extractor identifies a new decision that contradicts a prior one, the old decision's confidence is automatically lowered (−0.25 for contradictions, −0.15 for updates). Superseded decisions naturally fade from context surfacing without manual intervention. When erosion reaches the 0.2 floor the hook can additionally set invalidated_at, which removes the document from FTS and vector retrieval entirely. That step applies only to content_type='observation' rows — a superseded decision is eroded but never retired — and is off by default behind CLAWMEM_CONTRADICTION_INVALIDATE and logs WOULD invalidate instead of writing, because its exposure depends on the vault's confidence distribution and content-type mix (calibration guide). Two contract defects fixed in v0.28.0 had previously prevented this path from applying any classification at all — earlier versions classified but never mutated a document.v0.7.1 adds a second layer at the consolidation boundary: before the background worker merges a new pattern into an existing consolidated observation, a deterministic heuristic (negation asymmetry, number/date mismatch) plus the configured judge detect contradictions (heuristic-only, and constrained to link, when no judge is configured). Blocked merges route to either link policy (both rows remain active; the old row gains an invalidated_by backlink, default) or supersede policy (old row marked status='inactive' — requires a configured judge, otherwise loudly constrained to link). Configurable via CLAWMEM_CONTRADICTION_POLICY and CLAWMEM_CONTRADICTION_MIN_CONFIDENCE. Mutation-authorizing evaluations commit their durable judge_runs/judge_events audit rows in the same transaction as the mutation (Phase-3 deductive checks commit a precondition audit first; non-mutating outcomes write standalone rows) — that audit is what calibration reads. Data-egress note: a cloud or subscription judge receives the new decisions and the retrieved candidate snippets.
Features
A-MEM (Adaptive Memory Evolution)
Documents are automatically enriched with structured metadata when indexed:
Keywords (3-7 specific terms)
Tags (3-5 broad categories)
Context (1-2 sentence description)
When new documents create links, neighboring documents' metadata evolves — keywords merge, context updates, and the evolution history is tracked with version numbers and reasoning.
Causal Inference
The decision-extractor hook analyzes Observer facts for causal relationships. When multiple facts exist in an observation, an LLM identifies cause→effect pairs (confidence ≥ 0.6). Causal chains can be queried via find_causal_links with multi-hop traversal using recursive CTEs.
Beads Integration
Projects using Beads (v0.58.0+, Dolt backend) issue tracking are fully integrated into the MAGMA memory graph:
Auto-sync: Watcher detects .beads/ directory changes → syncBeadsIssues() queries bd CLI for live Dolt data → creates markdown docs in beads collection
Dependency bridging: All Beads dependency types map to memory_relations edges — blocks/conditional-blocks/waits-for/caused-by→causal, discovered-from/supersedes/duplicates→supporting, relates-to/related/parent-child→semantic. Tagged {origin: "beads"} for traceability.
A-MEM enrichment: New beads docs get full postIndexEnrich() — memory note construction, semantic/entity link generation, memory evolution
Documents are split into semantic fragments (sections, lists, code blocks, frontmatter, facts) and each fragment gets its own vector embedding. Full-doc embedding is preserved for broad-match queries.
Local Observer Agent
Uses the LLM server (shared with query expansion and intent classification) to extract structured observations from session transcripts. Observation types: decision, bugfix, feature, refactor, discovery, change, preference, milestone, problem. Each observation includes title, facts, narrative, concepts, and files read/modified. Preferences, milestones, and problems get first-class content_type treatment with dedicated confidence baselines and half-lives instead of being flattened to generic "observation". Regex patterns find decisions and antipatterns beside the model. A batch the model cannot answer (unavailable, or refusing the request) is quarantined and replayed later, never committed as empty; its regex finds are committed when the replay succeeds (v0.41.0). Each prompt is fitted in tokens to the LLM server's own context, with room kept for the reply, and a turn too long for one prompt runs as checkpointed windows that resume after a timeout (v0.41.2). Only the reply <none/> means "nothing to record"; a reply that does not parse gets up to two retries whose feedback names the failing field (a batch whose replies never parse is quarantined like an unanswered one), and on llama-server the observer asks for grammar-constrained replies — a GBNF grammar that admits only well-formed ones, sent unless the server refused one in the last 24 hours; enforcement is not verified in advance, and clawmem doctor counts completed replies that break it (v0.41.4). Serve the observer with -c 8192; inference services covers the server's context size.
Recall Tracking
Empirical tracking of which documents are surfaced by retrieval, which queries surfaced them, and whether the assistant actually cited them. Provides signals beyond raw search relevance for lifecycle decisions:
Per-query diversity: docs surfaced by multiple distinct queries have proven cross-domain relevance
Multi-day spacing: docs surfaced across separate calendar days (spaced frequency) are more valuable than binge recalls in one session
Negative signals: docs surfaced frequently but rarely referenced are noise candidates for snooze
Per-turn attribution: feedback-loop pairs each transcript turn with the context-surfacing row that served it (prompt hash + the host's order of events, never position) and tests only that turn's answer against that turn's injected documents (v0.41.0)
Data feeds lifecycle_status (pin/snooze candidate reports) and lifecycle_sweep (recall-based recommendations). Adapted from OpenClaw dreaming promotion patterns.
User Profile
Two-tier auto-curated profile extracted from your decisions and hub documents:
Injected at session start for instant personalization.
Prompt Injection Filtering
Five detection layers protect injected content: legacy string patterns, role injection regex, instruction override patterns, delimiter injection, and unicode obfuscation detection. Filtered results are skipped entirely (no placeholder tokens wasted).
Consolidation Worker
Optional background process that enriches documents missing A-MEM metadata. Runs on a configurable interval, processing 3 documents per tick. Non-blocking (Timer.unref).
Per-Folder CLAUDE.md Generation
Automatically generates context sections in per-folder CLAUDE.md files from recent decisions and session activity related to that directory.
Feedback Loop
A surfaced note gets access_count + 1 when a turn it was injected into names it — once per turn, when the turn is over (v0.41.0; earlier versions counted the whole session again at every Stop). Unreferenced notes decay via recency. Over time, useful notes rise and noise fades.
Offline Eval Harness
clawmem eval run --gold <file.jsonl> replays hand-labeled queries through the real query tool handler and scores the retrieved documents against gold evidence: doc-level Jaccard (|C∩E|/|C∪E|), precision/recall@k, hit@k, MRR. Touches no retrieval, lifecycle, or telemetry state (normal inference caches may populate, as in any live query); writes run.json + report.md for A/B comparison between checkouts or DB snapshots. Gold schema, trust gates, and labeling discipline: docs/guides/eval-harness.md.
Feature Flags
Variable
Default
Effect
CLAWMEM_ENABLE_AMEM
enabled
A-MEM note construction + link generation during indexing
CLAWMEM_ENABLE_CONSOLIDATION
disabled
Background worker for backlog A-MEM enrichment
CLAWMEM_CONSOLIDATION_INTERVAL
300000
Worker interval in ms (min 15000)
CLAWMEM_EMBED_URL
http://localhost:8088
Embedding server URL. Uses llama-server (GPU or CPU) or cloud API. Falls back to in-process node-llama-cpp if unset.
CLAWMEM_EMBED_API_KEY
(none)
API key for cloud embedding. Enables cloud mode: batch embedding, provider-specific params, TPM-aware pacing.
CLAWMEM_EMBED_MODEL
embedding
Model name for embedding requests. Override for cloud providers (e.g. jina-embeddings-v5-text-small).
CLAWMEM_EMBED_TPM_LIMIT
100000
Tokens-per-minute limit for cloud embedding pacing. Match to your provider tier.
CLAWMEM_EMBED_WAIT_SEC
120
v0.43.5: how long clawmem embed waits for a self-hosted embedding server at start (URL set, no API key, CLAWMEM_NO_LOCAL_MODELS=true). Not ready in time → the embedding is skipped, exit 1. embed --wait overrides it.
CLAWMEM_EMBED_WAIT_INTERVAL_MS
5000
v0.43.5: time between that wait's probes.
CLAWMEM_EMBED_PROBE_TIMEOUT_MS
15000
v0.43.5: how long one probe of that wait may take.
CLAWMEM_EMBED_DIMENSIONS
(none)
Output dimensions for OpenAI text-embedding-3-* Matryoshka models (e.g. 512, 1024).
CLAWMEM_LLM_URL
http://localhost:8089
LLM server URL for intent/query/A-MEM and the Stop hooks' observer. Without it, falls to node-llama-cpp (if allowed).
CLAWMEM_LLM_API_KEY
(none)
Bearer token for an authenticated remote LLM endpoint. Independent of the embed and rerank keys.
CLAWMEM_LLM_MODEL
qwen3
Model name sent to the configured LLM endpoint. Override this for OpenAI-compatible proxies such as gpt-5.4-mini.
CLAWMEM_LLM_REASONING_EFFORT
(none)
Optional top-level reasoning_effort field for Chat Completions endpoints that support it (for example OpenAI reasoning models). Leave unset for llama-server/vLLM unless your serving stack explicitly accepts that field.
CLAWMEM_LLM_NO_THINK
true
Append /no_think to remote LLM prompts. Set to false for standard OpenAI models and other endpoints that reject or treat the Qwen-style suffix as literal prompt text.
CLAWMEM_LLM_CONTEXT_TOKENS
(none)
v0.41.2. The LLM server's context per request, in tokens, for a server without llama.cpp's /props (cloud gateways, vLLM, Ollama). The Stop hooks' observer and summary fit their prompts to it. With /props the server's own number wins; with neither, 4096 is assumed.
CLAWMEM_OBSERVER_GRAMMAR
auto
v0.41.4.auto: the Stop hooks' observer sends a GBNF grammar that admits only well-formed observation blocks or <none/> to llama-server (a /props naming the model, template and build) and to the in-process model; off: never. A server that refuses one (HTTP 400, or in process a grammar that does not compile) gets none for 24 hours and until a grammarless request reaches it. Enforcement is not verified in advance: clawmem doctor counts completed replies that break the grammar.
CLAWMEM_JUDGE_URL
(none)
v0.29.0. OpenAI-compatible endpoint for the contradiction judge — a task-scoped override, independent of CLAWMEM_LLM_* (query expansion stays on the stock model). Setting it activates contradiction analysis. Data-egress note: the judge receives new decisions + retrieved candidate snippets. Guide.
CLAWMEM_JUDGE_PROVIDER
openai when _URL set
v0.29.0.openai | anthropic | claude-cli. anthropic calls the Messages API directly (default model claude-haiku-4-5); claude-cli runs a sandboxed headless claude -p on your Claude Code subscription — no API key.
CLAWMEM_JUDGE_MODEL
provider-specific
v0.29.0. Wire model id. Required on openai (no universal default); defaults to claude-haiku-4-5 on anthropic/claude-cli (the suite-verified recommended default; claude-sonnet-5 is an unverified upgrade candidate — see the judge guide for its honest evaluation status).
CLAWMEM_JUDGE_API_KEY
(none)
v0.29.0. Bearer / x-api-key for the judge endpoint. On anthropic, falls back to ANTHROPIC_API_KEY.
CLAWMEM_JUDGE_NO_THINK
false
v0.29.0. Append /no_think on the judge lane (only useful for a local Qwen-family judge on the openai lane).
CLAWMEM_JUDGE_STRUCTURED
lane-specific
v0.29.0. Schema-constrained judge output. Default false on openai (endpoint support varies), true on anthropic/claude-cli. Set explicitly to override.
CLAWMEM_RERANK_URL
http://localhost:8090
Reranker server URL. Without it, falls to node-llama-cpp (if allowed).
CLAWMEM_RERANK_API_KEY
(none)
Bearer token for an authenticated remote reranker endpoint. Independent of the embed and LLM keys.
CLAWMEM_NO_LOCAL_MODELS
false
Block node-llama-cpp from auto-downloading GGUF models. Set true for remote-only setups where you want fail-fast on unreachable endpoints. Since v0.43.5 clawmem embed first waits for a self-hosted embedding server under this setting (CLAWMEM_EMBED_WAIT_SEC).
CLAWMEM_MCP_DIRECT_TUNED_WEIGHTS
(superseded)
No effect since v0.22.0 — the direct-pipeline eval this knob was gated on measured tuned weights at 1/19 hit@1; the direct vector routes rank by raw cosine instead. Still parsed for backward compatibility; setting it logs a once-per-process warning.
CLAWMEM_MERGE_SCORE_NORMAL
0.93
v0.7.1. Phase 2 consolidation merge-safety threshold when candidate and existing anchors align. Merges above this normalized 3-gram cosine score are allowed.
CLAWMEM_MERGE_SCORE_STRICT
0.98
v0.7.1. Strictest merge-safety threshold — fallback when anchor sets are ambiguous.
CLAWMEM_MERGE_GUARD_DRY_RUN
false
v0.7.1. When true, Phase 2 merge-safety rejections are logged but not enforced — use for calibration before enabling the gate.
CLAWMEM_CONTRADICTION_POLICY
link
v0.7.1, judge-gated v0.29.0. Merge-time contradiction gate policy. link inserts a new row and sets the old row's invalidated_by backlink (default). supersede marks the old row status='inactive' — requires a configured judge; without one it is loudly constrained to link and clawmem doctor reports the policy as inactive.
CLAWMEM_CONTRADICTION_MIN_CONFIDENCE
0.5
v0.7.1. Minimum confidence required before the contradiction gate blocks a merge. The judge prompt states this same threshold — the prompt never overrides your configured value.
CLAWMEM_CONTRADICTION_INVALIDATE
false
v0.28.0, judge-gated v0.29.0. A different subsystem from the two rows above — this one governs the decision-extractor hook, not the merge-time gate. Set to exactly true to let a contradiction that erodes a document to the 0.2 confidence floor also set invalidated_at, removing it from FTS and vector retrieval. Off by default: the hook logs WOULD invalidate, writes a durable audit row, and mutates nothing further. Confidence erosion runs whenever a judge is configured (without a judge, nothing runs at all). Eligible rows are content_type='observation' only. Calibration guide.
This structure separates human-curated content from auto-generated memories, and within auto-generated content, separates user memories (persist across agents, owned by the human) from agent memories (operational, generated from sessions). Static knowledge lives in resources/ with no recency decay, distinct from ephemeral session logs. The layout works with any MCP-compatible client (Claude Code, OpenClaw, custom agents).
Workspace Collection
The primary workspace where the agent operates. Path varies by client (e.g., ~/workspace/, ~/.openclaw/workspace/, or any directory you choose).
User memories (preferences, entities, profile) are owned by the human and persist indefinitely. Agent memories (observations, handoffs) are operational artifacts with lifecycle management.
_clawmem/user/ vs _clawmem/agent/ — different decay rules per content type
Resources are first-class
Static knowledge (runbooks, architecture docs, API refs) should never lose relevance due to recency decay.
resources/ indexed with content_type: hub → ∞ half-life in composite scoring
Progressive disclosure
Hook injection (2000 token budget) benefits from tiered loading: compact snippets first, full content on demand.
compact=true (L1) → multi_get (L2) at query time. Pre-computed abstracts not yet implemented — candidate for future L0 tier.
Beads as memory edges
Issue tracker data bridges into the knowledge graph via typed relations, not just as flat documents.
Session-derived memory must neither repeat itself at every response nor overwrite another session's.
Transcript cursors for extraction and handoffs, a once-per-turn feedback verdict, items rendered into per-session decision/antipattern/handoff docs (v0.41.0; the cross-session merge policies and hash-window dedup they replaced are gone)
Beads issues synced from Dolt, relations in memory graph
Manual layers benefit from periodic re-indexing — a cron job running clawmem update --embed keeps the index fresh for content edited outside of watched directories.
# Install the OpenClaw plugin
# v0.10.4+: delegates to `openclaw plugins install --force` when the CLI is on PATH (auto-enables;
# honors OPENCLAW_STATE_DIR / OPENCLAW_CONFIG_PATH / --profile). Falls back to recursive copy
# honoring OPENCLAW_STATE_DIR when the CLI is absent.
# v0.10.0–v0.10.3: hardcoded recursive copy into ~/.openclaw/extensions/clawmem (issue #11).
clawmem setup openclaw
# Then follow the printed next steps. The exact list depends on which path ran:
# Path 1 (delegated): plugin already auto-enabled — just `openclaw gateway restart` + GPU config
# Path 3 (CLI absent): manually `openclaw plugins en
C
ClawMem
yoloshii·211 स्टार·
On-device memory layer for AI agents. Claude Code, OpenClaw and Hermes. Hooks + MCP server + hybrid RAG search.
अभी टूल सूची नहीं है। रिमोट सर्वर को पहले हेल्थ चेक के बाद सूची मिलती है।
FAQ
सवाल
ClawMem कैसे इंस्टॉल करें?
इस पेज पर Cursor, Claude Desktop, Claude Code या VS Code के लिए stdio कॉन्फ़िग कॉपी करें। यह पब्लिशर का इंस्टॉल इस्तेमाल करता है, PlugMCP प्रॉक्सी नहीं।
क्या ClawMem के लिए API key चाहिए?
इस रिकॉर्ड में कोई ज़रूरी एनवायरनमेंट वेरिएबल दर्ज नहीं है।
ClawMem कौन सा ट्रांसपोर्ट इस्तेमाल करता है?
ClawMem stdio पर लोकल चलता है।
ClawMem की पिछली जाँच कब हुई थी?
पिछली जाँच 2026-11-08 को हुई। On-device memory layer for AI agents. Claude Code, OpenClaw and Hermes. Hooks + MCP server + hybrid RAG search.