{"id":47046252,"url":"https://github.com/sdsrss/claude-mem-lite","last_synced_at":"2026-04-29T22:06:00.612Z","repository":{"id":338286390,"uuid":"1152635306","full_name":"sdsrss/claude-mem-lite","owner":"sdsrss","description":"Lightweight persistent memory system for Claude Code — FTS5 search, episode batching, error-triggered recall","archived":false,"fork":false,"pushed_at":"2026-04-23T00:20:25.000Z","size":2084,"stargazers_count":37,"open_issues_count":0,"forks_count":1,"subscribers_count":0,"default_branch":"main","last_synced_at":"2026-04-23T00:29:40.745Z","etag":null,"topics":["claude-code","fts5","hooks","mcp","memory","persistence","sqlite"],"latest_commit_sha":null,"homepage":null,"language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/sdsrss.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2026-02-08T07:10:37.000Z","updated_at":"2026-04-23T00:20:22.000Z","dependencies_parsed_at":"2026-03-12T02:02:20.804Z","dependency_job_id":null,"html_url":"https://github.com/sdsrss/claude-mem-lite","commit_stats":null,"previous_names":["sdsrss/claude-mem-lite"],"tags_count":104,"template":false,"template_full_name":null,"purl":"pkg:github/sdsrss/claude-mem-lite","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sdsrss%2Fclaude-mem-lite","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sdsrss%2Fclaude-mem-lite/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sdsrss%2Fclaude-mem-lite/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sdsrss%2Fclaude-mem-lite/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/sdsrss","download_url":"https://codeload.github.com/sdsrss/claude-mem-lite/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sdsrss%2Fclaude-mem-lite/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":32392618,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-04-28T14:34:11.604Z","status":"ssl_error","status_checked_at":"2026-04-28T14:32:37.009Z","response_time":56,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["claude-code","fts5","hooks","mcp","memory","persistence","sqlite"],"created_at":"2026-03-12T01:58:17.306Z","updated_at":"2026-04-29T22:06:00.591Z","avatar_url":"https://github.com/sdsrss.png","language":"JavaScript","readme":"[English](README.md) | [中文](README.zh-CN.md)\n\n# claude-mem-lite\n\nLightweight persistent memory system for [Claude Code](https://docs.anthropic.com/en/docs/claude-code). Automatically captures coding observations, decisions, and bug fixes during sessions, then provides full-text search to recall them later.\n\nBuilt as an [MCP server](https://modelcontextprotocol.io/) + Claude Code hooks. Zero external services, single SQLite database, minimal overhead.\n\n## Why claude-mem-lite?\n\nA ground-up redesign of [claude-mem](https://github.com/thedotmack/claude-mem), replacing its heavyweight architecture with a smarter, leaner approach.\n\n### Architecture comparison\n\n| | claude-mem (original) | claude-mem-lite |\n|---|---|---|\n| **LLM calls** | Every tool use triggers a Sonnet call | Only on episode flush (5-10 ops batched) |\n| **LLM input** | Raw `tool_input` + `tool_output` JSON | Pre-processed action summaries |\n| **Conversation** | Multi-turn, accumulates full history | Stateless single-turn extraction |\n| **Noise filtering** | LLM decides via \"WHEN TO SKIP\" prompt | Deterministic code-level Tier 1 filter |\n| **Runtime** | Long-running worker process (1.8MB .cjs) | On-demand spawn, exits immediately |\n| **Dependencies** | Bun + Python/uv + Chroma vector DB | Node.js only (3 npm packages) |\n| **Source size** | ~2.3MB compiled bundles | ~50KB readable source |\n| **Data directory** | `~/.claude-mem/` | `~/.claude-mem-lite/` (hidden, auto-migrates) |\n\n### Token \u0026 cost efficiency\n\nFor a typical 50-tool-call session:\n\n| | claude-mem | claude-mem-lite | Ratio |\n|---|---|---|---|\n| LLM calls | ~50 (every tool use) | ~5-8 (per episode) | **7-10x fewer** |\n| Tokens per call | 1,000-5,000 (raw JSON + history) | 200-500 (summaries only) | **5-10x smaller** |\n| Total tokens | ~100K-250K | ~1K-4K | **50-100x less** |\n| Model cost | Sonnet ($3/$15 per M) | Haiku ($0.25/$1.25 per M) | **12x cheaper** |\n| Combined savings | | | **600x+ lower cost** |\n\n### Quality comparison\n\n| Dimension | Winner | Why |\n|---|---|---|\n| **Classification accuracy** | Tie | Both produce correct type/title/narrative |\n| **Noise filtering** | **lite** | Code-level filtering is deterministic; LLM \"WHEN TO SKIP\" is unreliable |\n| **Observation coherence** | **lite** | Episode batching groups related edits into one coherent observation |\n| **Code-level detail** | original | Sees full diffs, but rarely useful for memory search |\n| **Search recall** | Tie | Users search semantic concepts (\"auth bug\"), not code lines |\n| **Hook latency** | **lite** | Async background workers; original blocks 2-5s per hook |\n\n### Design philosophy\n\nThe original sends **everything to the LLM and hopes it filters well**. claude-mem-lite **filters first with code, then sends only what matters** to a smaller model. This is not a downgrade; it's a smarter architecture that produces equivalent search quality at a fraction of the cost.\n\n## Features\n\n- **Automatic capture** -- Hooks into Claude Code lifecycle (PostToolUse, SessionStart, Stop, UserPromptSubmit) to record observations without manual effort\n- **Hybrid search** -- FTS5 BM25 + TF-IDF vector cosine similarity, merged via Reciprocal Rank Fusion (RRF). FTS5 handles keyword matching; 512-dim TF-IDF vectors capture semantic similarity for recall beyond exact terms\n- **Timeline browsing** -- Navigate observations chronologically with anchor-based context windows\n- **Episode batching** -- Groups related file operations into coherent episodes before LLM encoding\n- **Error-triggered recall** -- Automatically searches memory when Bash errors occur, surfacing relevant past fixes\n- **Proactive file history** -- When editing a file, automatically shows relevant past observations for that file\n- **Session summaries** -- LLM-generated summaries at session end (via background workers using `claude -p`)\n- **Project-scoped context** -- Injects recent memory into `CLAUDE.md` and session startup for immediate context\n- **Observation types** -- Categorized as `decision`, `bugfix`, `feature`, `refactor`, `discovery`, or `change`\n- **Importance grading** -- LLM assigns 1-3 importance levels (routine / notable / critical) to each observation\n- **Observation relations** -- Bidirectional links between related observations based on file overlap\n- **User prompt capture** -- Records user prompts via UserPromptSubmit hook for intent tracking\n- **Read file tracking** -- Tracks files read during sessions for richer episode context\n- **Zero data loss** -- If LLM fails, observations are saved with degraded (inferred) metadata instead of being discarded\n- **Two-tier dedup** -- Jaccard similarity (5-minute window) + MinHash signatures (7-day cross-session window) prevent duplicates\n- **Synonym expansion** -- Abbreviations like `K8s`, `DB`, `auth` automatically expand to full forms in FTS5 search (100+ pairs including CJK↔EN cross-language mappings)\n- **CJK synonym extraction** -- Unsegmented Chinese text is scanned for known vocabulary words (数据库→database, 搜索→search, etc.) enabling cross-language memory recall\n- **Stop-word filtering** -- English stop words filtered from both TF-IDF vocabulary (reclaiming ~18% of vector dimensions) and FTS queries (preventing false negatives from noise terms like \"how\", \"the\", \"does\")\n- **Persisted vocabulary** -- TF-IDF vocabulary persisted to `vocab_state` table, preventing vector staleness when document frequencies shift. Vectors stay valid until explicit rebuild\n- **Pseudo-relevance feedback (PRF)** -- Top results seed expansion queries for broader recall\n- **Concept co-occurrence** -- Shared concepts across observations expand search to related topics\n- **Context-aware re-ranking** -- Active file overlap boosts relevance (exact match + directory-level half-weight)\n- **Superseded detection** -- Marks older observations as outdated when newer ones cover the same files with higher importance\n- **Adaptive time windows** -- Session startup recall uses velocity-based time windows (high/medium/low activity tiers)\n- **Token-budgeted context** -- Greedy knapsack algorithm selects session-start context within a 2,000-token budget, prioritizing by recency and importance\n- **Observation compression** -- Old low-value observations can be compressed into weekly summaries to reduce noise\n- **Secret scrubbing** -- Automatic redaction of API keys, tokens, PEM blocks, connection strings, and 15+ credential patterns\n- **Atomic writes** -- All file writes (episodes, CLAUDE.md) use write-to-tmp + rename to prevent corruption on crash\n- **Robust locking** -- PID-aware lock files with automatic stale/orphan cleanup (\u003e30s timeout or dead PID)\n- **Stale session cleanup** -- Sessions active for \u003e24h are automatically marked as abandoned on next start\n- **Resource registry** -- Indexes installed skills and agents with FTS5 search, composite scoring, and invocation tracking; searchable via `mem_registry` MCP tool\n- **Unified resource discovery** -- Shared filesystem traversal layer (`resource-discovery.mjs`) used by both runtime scanner and offline indexer, supporting flat directories, plugin nesting, and loose `.md` files\n- **Domain synonym expansion** -- Registry search queries expand to domain synonyms (e.g., \"fix\" → debug, bugfix, troubleshoot, diagnose, repair)\n- **Dual LLM mode** -- Auto-detects `ANTHROPIC_API_KEY` for direct API calls; falls back to `claude -p` CLI when no key is available\n- **Lesson-learned indexing** -- `lesson_learned` field indexed in FTS5 with weight 8, making past debugging insights directly searchable\n- **Cross-source normalization** -- `mem_search` normalizes scores across observations, sessions, and prompts before merging, preventing any source from dominating results\n- **Exponential recency decay** -- Type-differentiated half-lives (decisions: 90d, discoveries: 60d, bugfixes: 14d, changes: 7d) consistently applied in all ranking paths\n- **Prompt-time memory injection** -- UserPromptSubmit hook automatically searches and injects relevant past observations with recency and importance weighting\n- **Smart skill invocation** -- Auto-loaded and searched managed skills/agents include portable `~` paths with `Read()` guidance; native plugin skills recommend `Skill(\"full:name\")`; prevents `Skill()` misuse for managed resources that aren't registered with Claude Code's native handler\n- **Dual injection dedup** -- `user-prompt-search.js` and `handleUserPrompt` coordinate via temp file to prevent duplicate memory injection\n- **Plugin cache hook self-heal** -- Claude Code runtime reads plugin hooks from `~/.claude/plugins/cache/\u003cmp\u003e/\u003cplugin\u003e/\u003cver\u003e/hooks/hooks.json`, not from the marketplace source. When `install.mjs`-managed `settings.json` hooks coexist with a stale cache `hooks.json` (e.g. from a previous marketplace install or a plugin auto-update), the runtime registers hooks twice → every session start / user prompt fires twice. `install.mjs` and `hook-update.mjs` now clear cache `hooks.json` in every version dir, and `hook.mjs session-start` self-heals on every session (gated by `hasInstallManagedHooks` so plugin-only users are not affected). `install.mjs status` reports cache pollution state (since v2.31.1/2.31.2).\n- **Result-dedup cooldown** -- User-prompt memory injection uses result-overlap detection (\u003e80% ID overlap → skip) instead of time-based cooldown, allowing topic switches within seconds while preventing redundant injections\n- **OR query fallback** -- When AND-joined FTS5 queries return zero results, automatically relaxes to OR-joined queries for broader recall (applied in both user-prompt-search and hook-memory paths)\n- **Configurable LLM model** -- Switch between Haiku (fast/cheap) and Sonnet (deeper analysis) via `CLAUDE_MEM_MODEL` env var\n- **DB auto-recovery** -- Detects and cleans corrupted WAL/SHM files on startup; periodic WAL checkpoints prevent unbounded growth\n- **Schema auto-migration** -- Idempotent `ALTER TABLE` migrations run on every startup, safely adding new columns and indexes without data loss\n- **Exploration bonus** -- New resources in the registry get a fair chance in composite ranking; zombie resources (high recommend, zero adopt) are penalized in scoring\n- **LLM concurrency control** -- File-based semaphore limits background workers to 2 concurrent LLM calls, preventing resource contention\n- **stdin overflow protection** -- Hook input truncated at 256KB with regex-based action salvage for oversized tool outputs\n- **Cross-session handoff** -- Captures session state (request, completed work, next steps, key files) on `/clear` or `/exit`, then injects context when the next session detects continuation intent via explicit keywords or FTS5 term overlap\n- **Git-SHA continuation anchor** (v2.31.0) -- Handoff rows include `git_sha_at_handoff`; any handoff matching the current `HEAD` counts as continuation regardless of TTL. Code state is a stronger continuation signal than wall-clock time\n- **Startup dashboard** (v2.31.0) -- SessionStart hook aggregates `git status` + `~/.claude/tasks/*.json` + `~/.claude/plans/*.md` + most-recent exit handoff + recent event count into a single structured block injected via `hookSpecificOutput.additionalContext`\n- **Activity namespace** (v2.31.0) -- Dedicated `events` table + FTS5 for non-memdir types (`bugfix`, `lesson`, `bug`, `discovery`, `refactor`, `feature`, `observation`, `decision`) that don't compete with `WHAT_NOT_TO_SAVE` semantics on the observations table. CLI: `claude-mem-lite activity save|search|recent|show`. Slash commands: `/lesson`, `/bug`. `hook-llm` routes non-memdir summary types through `persistHaikuSummary` so upgrades from observations→events are atomic\n- **In-place observation updates** -- `mem_update` tool modifies existing observations atomically (field update + FTS text rebuild + vector re-computation in one transaction), preserving original IDs and references\n- **Bulk export** -- `mem_export` tool exports observations as JSON or JSONL, with project/type/date filtering and 1000-row pagination cap with batch guidance\n- **FTS integrity management** -- `mem_fts_check` tool verifies FTS5 index health or rebuilds indexes on demand, useful after database recovery or when search results seem wrong\n- **Atomic multi-table writes** -- `saveObservation` wraps observations + observation_files + observation_vectors INSERTs in a single `db.transaction()`, preventing orphaned rows on crash\n- **Modular NLP pipeline** -- Synonym maps, stop words, scoring constants, and query building extracted into focused modules (`synonyms.mjs`, `stop-words.mjs`, `scoring-sql.mjs`, `nlp.mjs`) for independent testing and maintenance\n- **Porter-aligned PRF** -- Pseudo-relevance feedback terms are now stemmed with the same Porter algorithm used by FTS5, ensuring PRF expansion terms match the search index\n\n## Platform Support\n\n| Platform | Status | Notes |\n|----------|--------|-------|\n| **Linux** | Supported | Primary development and testing platform |\n| **macOS** | Supported | Fully compatible (Intel and Apple Silicon) |\n| **Windows** | Not supported | Uses POSIX shell scripts (`post-tool-use.sh`, `setup.sh`) and Unix file locking; WSL2 may work but is untested |\n\n## Requirements\n\n- **Node.js** \u003e= 18\n- **Claude Code** CLI installed and configured (`claude` command available)\n- **SQLite3** support (provided by `better-sqlite3`, compiled on install)\n- **Platform**: Linux or macOS (see [Platform Support](#platform-support))\n\n## Installation\n\n### Method 1: Plugin Marketplace (recommended)\n\n```bash\n/plugin marketplace add sdsrss/claude-mem-lite\n/plugin install claude-mem-lite\n```\n\nPlugin mode manages its own hooks/runtime. On session start it only **checks and reports** new claude-mem-lite versions; it does **not** self-overwrite plugin files in place. Update plugin-mode installs through Claude's plugin workflow.\n\n### Method 2: npx (one-liner)\n\n```bash\nnpx github:sdsrss/claude-mem-lite\n```\n\nSource files are automatically copied to `~/.claude-mem-lite/` for persistence.\n\n### Method 3: git clone\n\n```bash\ngit clone https://github.com/sdsrss/claude-mem-lite.git\ncd claude-mem-lite\nnode install.mjs install\n```\n\nSource files stay in the cloned repo. Update via `git pull \u0026\u0026 node install.mjs install`.\n\n### What happens during installation\n\n1. **Install dependencies** -- `npm install --omit=dev` (compiles native `better-sqlite3`)\n2. **Register MCP server** -- `mem` server with 16 tools (search, recent, recall, timeline, get, save, update, stats, delete, compress, maintain, export, fts_check, browse, registry, use)\n3. **Configure hooks** -- `PostToolUse`, `SessionStart`, `Stop`, `UserPromptSubmit` lifecycle hooks\n4. **Create data directory** -- `~/.claude-mem-lite/` (hidden) for database, runtime, and managed resource files\n5. **Auto-migrate** -- If `~/.claude-mem/` (original claude-mem) or `~/claude-mem-lite/` (pre-v0.5 unhidden) exists, migrates database and runtime files to `~/.claude-mem-lite/`, preserving the original untouched\n6. **Initialize database** -- SQLite with WAL mode, FTS5 indexes created on first server start\n\nRestart Claude Code after installation to activate.\n\n### Migration\n\nAll installation methods auto-detect and migrate from previous versions:\n\n**From claude-mem (original `~/.claude-mem/`):**\n- Copy `claude-mem.db` → `~/.claude-mem-lite/claude-mem-lite.db` (renamed)\n- Copy the `runtime/` directory\n- **Original `~/.claude-mem/` is preserved** (no deletion, no overwrite)\n\n**From pre-v0.5 unhidden directory (`~/claude-mem-lite/`):**\n- Entire directory is moved to `~/.claude-mem-lite/` (hidden)\n\n**In-place rename:**\n- Existing `claude-mem.db` in `~/.claude-mem-lite/` is automatically renamed to `claude-mem-lite.db`\n\nRemove old directories manually after confirming:\n```bash\nrm -rf ~/.claude-mem/       # original claude-mem\nrm -rf ~/claude-mem-lite/   # pre-v0.5 unhidden (if not auto-moved)\n```\n\n### Directory Structure\n\n```\n~/.claude-mem-lite/\n  claude-mem-lite.db       # SQLite database — memory (WAL mode)\n  resource-registry.db     # SQLite database — skill/agent registry\n  runtime/\n    session-\u003cproject\u003e    # Active session state\n    ep-\u003cproject\u003e.json    # Episode buffer\n    ep-flush-*.json      # Flushed episodes awaiting processing\n    reads-\u003cproject\u003e.txt  # Read file paths (collected on flush)\n  managed/\n    skills/              # Standalone skills: {name}/SKILL.md\n    agents/              # Agent plugins: {group}/agents/{name}.md + skills/*/SKILL.md\n    repos/               # Shallow-cloned source repos\n```\n\n## Usage\n\n### MCP Tools (used automatically by Claude)\n\nAs of v2.34.0, the server registers 17 tools in total but only the 6 **core**\ntools appear in `tools/list`. The 11 **hidden** tools remain callable at the\nprotocol layer (`tools/call` by exact name still routes normally); they're\nomitted from the list response so Claude Code sessions don't load 11 extra\ntool schemas at startup. Hidden tools are the maintenance / admin / browser\nsurface — reach them through the CLI column in the second table.\n\n**Core (6, exposed to Claude Code)**\n\n| Tool | Description |\n|------|-------------|\n| `mem_search` | FTS5 full-text search with BM25 ranking. Filters by type, project, date range, importance level. |\n| `mem_recent` | Show most recent observations, ordered by time. Quick snapshot of latest activity. |\n| `mem_recall` | Recall observations related to a file. Use before editing to surface past bugfixes and context. |\n| `mem_timeline` | Browse observations chronologically around an anchor point. |\n| `mem_get` | Retrieve full details for specific observation IDs (includes importance and related_ids). |\n| `mem_save` | Manually save a memory/observation. |\n\n**Hidden-but-callable (11, CLI-routed)**\n\n| Tool | CLI equivalent | Notes |\n|------|----------------|-------|\n| `mem_update` | `claude-mem-lite update \u003cid\u003e` | Edit an observation in place. |\n| `mem_stats` | `claude-mem-lite stats` | Counts, type distribution, daily activity. |\n| `mem_delete` | `claude-mem-lite delete \u003cid\u003e` | Preview / confirm workflow, FTS5 cleanup. |\n| `mem_compress` | `claude-mem-lite compress --preview` | Roll up old low-value observations. |\n| `mem_maintain` | `claude-mem-lite maintain --action scan` | dedup / decay / cleanup / rebuild_vectors. |\n| `mem_optimize` | `claude-mem-lite optimize --action preview` | LLM-powered re-enrich / normalize / cluster-merge. |\n| `mem_export` | `claude-mem-lite export` | JSON / JSONL dump, filters by project, type, date. |\n| `mem_fts_check` | `claude-mem-lite fts-check [--rebuild]` | FTS5 integrity + rebuild. |\n| `mem_browse` | `claude-mem-lite browse` | Tier-grouped dashboard (working / active / archive). |\n| `mem_registry` | `claude-mem-lite registry \u003caction\u003e` | List / search / import / remove skills + agents. |\n| `mem_use` | _MCP only_ | Load a skill / agent from the registry by name. |\n\n### Skill Commands (in Claude Code chat)\n\n```\n/mem search \u003cquery\u003e        # Full-text search across all memories\n/mem recent [n]            # Show recent N observations (default 10)\n/mem recall \u003cfile\u003e         # Show past observations for a file\n/mem save \u003ctext\u003e           # Save a manual memory/note\n/mem stats                 # Show memory statistics\n/mem timeline \u003cquery\u003e      # Browse timeline around a match\n/mem browse                # Tier-grouped memory dashboard\n/mem \u003cquery\u003e               # Shorthand for search\n/lesson \u003ctext\u003e             # Save a non-obvious lesson to the events table (v2.31.0)\n/bug \u003ctext\u003e                # Log a known bug + repro steps to the events table (v2.31.0)\n```\n\n### Efficient Search Workflow\n\n```\n1. mem_search(query=\"auth bug\")     -\u003e compact ID index\n2. mem_timeline(anchor=12345)       -\u003e surrounding context\n3. mem_get(ids=[12345, 12346])      -\u003e full details\n```\n\n### Invited Memory (v2.32+)\n\nOpt-in mechanism that installs a single sentinel-wrapped line into the project's\nmemdir (`~/.claude/projects/\u003cencoded\u003e/memory/MEMORY.md`) so Claude Code loads\nthe plugin's MCP-tool triggers as **user-memory** — a higher instruction-following\nauthority than MCP server instructions (which are framed as tool metadata).\n\n```bash\nclaude-mem-lite adopt              # install for current project\nclaude-mem-lite adopt --all        # install for every project under ~/.claude/projects/\nclaude-mem-lite adopt --status     # list adopted projects + sentinel versions\nclaude-mem-lite adopt --dry-run    # preview without writing\nclaude-mem-lite unadopt            # remove cleanly\n```\n\nSlash commands `/adopt` and `/unadopt` wrap the same CLI.\n\n**What adoption changes:**\n- A `\u003c!-- claude-mem-lite:begin v1 --\u003e…\u003c!-- claude-mem-lite:end --\u003e` block is\n  added to `MEMORY.md` under a `## 插件契约` header, containing one ≤150-char\n  line pointing at `mem_recall` / `mem_save` with their key arguments.\n- A `plugin_claude_mem_lite.md` detail file is written (not auto-loaded; read\n  on demand when the MEMORY.md pointer surfaces in context).\n- Post-adopt the conservative hook layer auto-trims: MCP server instructions\n  drop the `WHEN TO USE` section, SessionStart injection drops the `File Lessons`\n  / `Key Context` sections. `#ID` references and the `Recent` table still fire\n  so `mem_get` remains reachable.\n\n**When does it take effect?**\n- The MEMORY.md sentinel and the hook-layer trim (`File Lessons` / `Key Context` /\n  lesson suffix) apply on the **next SessionStart** (any new Claude Code session\n  in the adopted project).\n- The MCP server instructions are built once at server boot and MCP has no\n  \"push\" protocol — the `WHEN TO USE` / `Decision rules` trim only applies\n  after Claude Code restarts and re-spawns the mem MCP server. A single\n  `/exit` + fresh session is enough. Same caveat applies to `unadopt`.\n\n**Safety:**\n- Hash-guarded: editing the sentinel body yourself blocks automatic rewrites\n  unless you pass `--force`.\n- Budget-gated: refuses to insert when MEMORY.md is already \u003e180 lines, so\n  Claude Code's 200-line MEMORY.md cap won't truncate the block.\n- `install` only auto-adopts when run from the claude-mem-lite source repo\n  itself (detected via git remote match); other users must opt in explicitly.\n- The fallback hook layer is never removed from source — conditional trim is\n  runtime-gated on sentinel presence, so projects without adoption get the\n  full verbose output.\n\nSee `docs/plans/2026-04-16-invited-memory-pattern.md` for the full design\n(including the reusable template other plugins can follow).\n\n## Database Schema\n\nFive core tables with FTS5 virtual tables for search:\n\n**observations** -- Individual coding observations (decisions, bugfixes, features, etc.)\n```\nid, memory_session_id, project, type, title, subtitle,\ntext, narrative, concepts, facts, files_read, files_modified,\nimportance, related_ids, created_at, created_at_epoch,\nlesson_learned, minhash_sig, access_count, compressed_into, search_aliases,\nbranch, superseded_at, superseded_by, last_accessed_at\n```\n\n**session_summaries** -- LLM-generated session summaries\n```\nid, memory_session_id, project, request, investigated,\nlearned, completed, next_steps, files_read, files_edited, notes,\nremaining_items, lessons, key_decisions\n```\n\n**sdk_sessions** -- Session tracking\n```\nid, content_session_id, memory_session_id, project,\nstarted_at, completed_at, status, prompt_counter\n```\n\n**user_prompts** -- User prompts captured via UserPromptSubmit hook\n```\nid, content_session_id, prompt_text, prompt_number\n```\n\n**session_handoffs** -- Cross-session handoff snapshots (UPSERT, max 2 per project)\n```\nproject, type, session_id, working_on, completed, unfinished,\nkey_files, key_decisions, match_keywords, created_at_epoch\n```\n\n**observation_files** -- Normalized file membership for efficient file-based recall\n```\nobs_id, filename\n```\n\n**observation_vectors** -- TF-IDF vector embeddings for hybrid search\n```\nobservation_id, vector (BLOB Float32Array), vocab_version, created_at_epoch\n```\n\n**vocab_state** -- Persisted TF-IDF vocabulary for stable vector indexing\n```\nterm, term_index, idf, version, created_at_epoch\n```\n\nFTS5 indexes: `observations_fts` (title, subtitle, narrative, text, facts, concepts, lesson_learned), `session_summaries_fts`, `user_prompts_fts`\n\n## How It Works\n\n### Hook Pipeline\n\n```\nSessionStart\n  -\u003e Generate session ID (or save handoff snapshot on /clear)\n  -\u003e Mark stale sessions (\u003e24h active) as abandoned\n  -\u003e Clean orphaned/stale lock files\n  -\u003e Query recent observations (24h)\n  -\u003e Inject context into CLAUDE.md + stdout\n\nPostToolUse (every tool execution)\n  -\u003e Bash pre-filter skips noise in ~5ms (Read paths tracked to reads file)\n  -\u003e Detect Bash significance (errors, tests, builds, git, deploys)\n  -\u003e Accumulate into episode buffer\n  -\u003e Proactive file history: show past observations for edited files\n  -\u003e Flush when: buffer full (10 entries) | 5min gap | context change\n  -\u003e Collect Read file paths into episode on flush\n  -\u003e Spawn LLM episode worker for significant episodes\n  -\u003e Error-triggered recall: search memory for related past fixes\n\nUserPromptSubmit (two parallel paths)\n  -\u003e [user-prompt-search.js] Auto-search memory via FTS5 + active file context\n  -\u003e [user-prompt-search.js] Inject relevant past observations with recency/importance weighting\n  -\u003e [user-prompt-search.js] Write injected IDs to temp file for dedup\n  -\u003e [user-prompt-search.js] L1 skill auto-load: match managed skill names in prompt\n     -\u003e Load content with portable ~ path + Read() guidance\n     -\u003e source=\"managed-skill|managed-agent\", path=\"~/.claude-mem-lite/managed/...\"\n  -\u003e [hook.mjs handleUserPrompt] Capture user prompt text to user_prompts table\n  -\u003e [hook.mjs handleUserPrompt] Increment session prompt counter\n  -\u003e [hook.mjs handleUserPrompt] Handoff: detect continuation intent → inject previous session context\n  -\u003e [hook.mjs handleUserPrompt] Semantic memory injection (hook-memory.mjs), deduped via temp file\n\nStop\n  -\u003e Flush final episode buffer\n  -\u003e Save handoff snapshot (on /exit)\n  -\u003e Mark session completed\n  -\u003e Spawn LLM summary worker (poll-based wait)\n```\n\n### Resource Registry\n\nThe resource registry (`registry.mjs`, `registry-retriever.mjs`) indexes installed skills and agents into a searchable FTS5 database. Unlike the previous proactive dispatch system, the registry is now on-demand — it's reachable via the `claude-mem-lite registry` CLI (primary path for Claude Code since v2.34.0 hides the `mem_registry` MCP tool from `tools/list`) or by direct `tools/call mem_registry` for MCP clients that know the name.\n\n```\nRegistry pipeline:\n  -\u003e registry-scanner.mjs discovers skills/agents on filesystem\n  -\u003e resource-discovery.mjs handles flat dirs, plugin nesting, loose .md files\n  -\u003e registry-indexer.mjs indexes content into FTS5 with metadata\n  -\u003e registry-retriever.mjs provides BM25-ranked search with synonym expansion\n  -\u003e mem_registry MCP tool exposes search/list/stats/import/remove/reindex actions\n\nSmart invocation (three layers):\n  L1 auto-load: UserPromptSubmit matches managed skill name in prompt\n     -\u003e Loads content with path=\"~/.claude-mem-lite/managed/.../SKILL.md\"\n     -\u003e Guides: Read(\"path\") or mem_use(name=\"...\"), never Skill()\n  L2 bridge: PreToolUse hook intercepts Skill(\"name\") for managed resources\n     -\u003e Outputs content, prevents native handler failure\n  L3 explicit: mem_use(name=\"...\") loads full content with reload path\n  Search: managed resources → Read(path), native plugins → Skill(\"full:name\")\n```\n\nComposite scoring for search results: BM25 relevance (40%) + repo stars (15%) + success rate (15%) + adoption rate (10%) + freshness (10%) + exploration bonus (10%). Domain filtering ensures platform-specific resources (iOS, Go, Rust) only surface for matching projects.\n\n### Episode Encoding\n\nEpisodes are batched related operations (edits to the same file group) that get processed by a background LLM worker:\n\n```\nEpisode buffer -\u003e Flush to JSON -\u003e claude -p --model haiku -\u003e Structured observation -\u003e SQLite\n```\n\nEach observation includes type, title, narrative, concepts, facts, importance (1-3), and is automatically deduplicated via two tiers: Jaccard similarity (\u003e70% within 5 minutes) and MinHash signatures (\u003e80% within 7 days across sessions). If the LLM call fails, a degraded observation is saved with inferred metadata (zero data loss). Related observations are linked via `related_ids` based on FTS5 title similarity and file overlap.\n\n## Management Commands\n\n```bash\n# Plugin install:\n/plugin install claude-mem-lite       # Install / update\n/plugin uninstall claude-mem-lite     # Uninstall\n\n# git clone install:\nnode install.mjs install              # Install and configure\nnode install.mjs uninstall            # Remove (keep data)\nnode install.mjs uninstall --purge    # Remove and delete all data\nnode install.mjs status               # Show current status\nnode install.mjs doctor               # Diagnose issues\nnode install.mjs cleanup-hooks        # Remove only stale claude-mem-lite hooks from settings.json\nnode install.mjs update               # Force-check for updates and install them (direct install / npx mode)\n\n# npx install:\nnpx claude-mem-lite                   # Install / reinstall\nnpx claude-mem-lite uninstall         # Remove (keep data)\nnpx claude-mem-lite doctor            # Diagnose issues\n```\n\nNotes:\n- Plugin mode only reports available updates; it does not self-update plugin files.\n  To upgrade an installed plugin to the latest published version, run **inside Claude Code**:\n  ```\n  /plugin marketplace update sdsrss\n  /plugin install claude-mem-lite@sdsrss\n  ```\n  (The first command refreshes the local marketplace clone; the second reinstalls from it. Without the first command, `/plugin install` reuses the stale local clone and you stay on whichever version you originally pulled.)\n- Direct install / npx mode keeps auto-update enabled and uses staged replacement with rollback on install failure.\n- If you disabled the plugin but still have old mem hooks in `~/.claude/settings.json`, run `node install.mjs cleanup-hooks`.\n\n### doctor\n\nChecks Node.js version, dependencies, server/hook files, database integrity, FTS5 indexes, and stale processes.\n\n### status\n\nShows MCP registration, hook configuration, plugin disabled state, and database stats (observation/session counts).\n\n## Uninstall\n\n```bash\n# Plugin:\n/plugin uninstall claude-mem-lite\n\n# git clone:\ncd claude-mem-lite\nnode install.mjs uninstall            # Keeps ~/.claude-mem-lite/ data\nnode install.mjs uninstall --purge    # Deletes ~/.claude-mem-lite/ and all data\n\n# npx:\nnpx claude-mem-lite uninstall\nnpx claude-mem-lite uninstall --purge\n```\n\nData in `~/.claude-mem-lite/` is preserved by default. Delete manually if needed:\n```bash\nrm -rf ~/.claude-mem-lite/\n```\n\n## Project Structure\n\n```\nclaude-mem-lite/\n  .claude-plugin/\n    plugin.json      # Plugin manifest\n    marketplace.json # Marketplace catalog\n  .mcp.json          # MCP server definition (plugin root)\n  hooks/\n    hooks.json       # Hook definitions (plugin mode)\n  commands/\n    mem.md           # /mem command definition\n  server.mjs           # MCP server: tool definitions, FTS5 search, database init\n  server-internals.mjs # Extracted search helpers: re-ranking, PRF, concept expansion\n  hook.mjs             # Claude Code hooks: episode capture, error recall, session management\n  hook-llm.mjs         # Background LLM workers: episode extraction, session summaries\n  hook-shared.mjs      # Shared hook infrastructure: session management, DB access, LLM calls\n  hook-handoff.mjs     # Cross-session handoff: state extraction, intent detection, injection\n  hook-context.mjs     # CLAUDE.md context injection and token budgeting\n  hook-episode.mjs     # Episode buffer management: atomic writes, pending entry merging\n  hook-memory.mjs      # Semantic memory injection on user prompt\n  hook-semaphore.mjs   # LLM concurrency control: file-based semaphore for background workers\n  schema.mjs           # Database schema: single source of truth for tables, migrations, FTS5\n  tool-schemas.mjs     # Shared Zod schemas for MCP tool validation\n  tfidf.mjs            # TF-IDF vector engine: tokenization, vocabulary building, vector computation, cosine similarity, RRF merge\n  tier.mjs             # Temporal tier system: activity-based time window classification\n  utils.mjs            # Re-export hub: backward-compatible surface for all utility modules\n  nlp.mjs              # FTS5 query building: synonym expansion, CJK bigrams, sanitization\n  scoring-sql.mjs      # BM25 weight constants and type-differentiated decay half-lives\n  stop-words.mjs       # Shared base stop-word set for all NLP/search modules\n  synonyms.mjs         # Unified synonym source: SYNONYM_MAP (bidirectional) + DISPATCH_SYNONYMS\n  project-utils.mjs    # Shared project name resolution with in-process cache\n  secret-scrub.mjs     # API key, token, PEM, and credential pattern redaction\n  format-utils.mjs     # String formatting: truncate, typeIcon, date/time/week formatting\n  hash-utils.mjs       # MinHash signatures, Jaccard similarity for dedup\n  bash-utils.mjs       # Bash output significance detection: errors, tests, builds, deploys\n  # Resource registry\n  registry.mjs         # Resource registry DB: schema, CRUD, FTS5, invocation tracking\n  registry-retriever.mjs # FTS5 retrieval with synonym expansion and composite scoring\n  registry-indexer.mjs # Resource indexing pipeline\n  registry-scanner.mjs # Filesystem scanner: reads content + hashes, delegates discovery\n  resource-discovery.mjs # Shared discovery layer: flat dirs, plugin nesting, loose .md files\n  haiku-client.mjs     # Unified Haiku LLM wrapper: direct API or CLI fallback\n  # Install \u0026 config\n  install.mjs          # CLI installer: setup, uninstall, status, doctor (npx/git clone mode)\n  skill.md             # MCP skill definition (npx/git clone mode)\n  package.json         # Dependencies and metadata\n  scripts/\n    setup.sh           # Setup hook: npm install + migration (hidden dir + old dir)\n    post-tool-use.sh   # Bash pre-filter: skips noise in ~5ms, tracks Read paths\n    user-prompt-search.js # UserPromptSubmit hook: auto-search memory + L1 skill auto-load\n    pre-skill-bridge.js  # PreToolUse hook: L2 skill bridge for managed resources\n    pre-tool-recall.js   # PreToolUse hook: file lesson recall before Edit/Write\n    prompt-search-utils.mjs # Shared logic: skip patterns, intent detection, name matching\n    convert-commands.mjs # Converts command .md → SKILL.md in managed plugins\n    index-managed.mjs  # Offline indexer for managed resources\n  # Test \u0026 benchmark (dev only)\n  tests/               # Unit, property, integration, contract, E2E, pipeline tests\n  benchmark/           # BM25 search quality benchmarks + CI gate\n```\n\n## Search Quality\n\nBenchmarked on 200 observations across 30 queries (standard + hard-negative categories):\n\n| Metric | Score |\n|--------|-------|\n| Recall@10 | 0.88 |\n| Precision@10 | 0.96 |\n| nDCG@10 | 0.95 |\n| MRR@10 | 0.95 |\n| P95 search latency | 0.15ms |\n\nThe benchmark suite runs as a CI gate (`npm run benchmark:gate`) to prevent search quality regressions.\n\n## Development\n\n```bash\nnpm run lint              # ESLint static analysis\nnpm test                  # Run full test suite (vitest)\nnpm run test:smoke        # Run 5 core smoke tests\nnpm run test:coverage     # Run tests with V8 coverage (≥75% lines/functions, ≥65% branches)\nnpm run benchmark         # Run full search quality benchmark\nnpm run benchmark:gate    # CI gate: fails if metrics regress beyond 5% tolerance\n```\n\n## Environment Variables\n\n| Variable | Description | Default |\n|----------|-------------|---------|\n| `CLAUDE_MEM_DIR` | Custom data directory. All databases, runtime files, and managed resources are stored here. | `~/.claude-mem-lite/` |\n| `CLAUDE_MEM_MODEL` | LLM model for background calls (episode extraction, session summaries). Accepts `haiku` or `sonnet`. | `haiku` |\n| `CLAUDE_MEM_DEBUG` | Enable debug logging (`1` to enable). | _(disabled)_ |\n| `MEM_QUIET_HOOKS` | Low-noise hooks. `1` drops the `File Lessons` / `Key Context` sections from SessionStart injection, the lesson suffix from `[mem] Related memories`, and the `WHEN TO USE` / `Decision rules` blocks from MCP server instructions. IDs and the `Recent` table still surface so `mem_get(ids=[…])` remains reachable. Intended for users running the invited-memory adopt path or who otherwise want minimal auto-injection. | _(disabled)_ |\n| `MEM_NO_ADOPT_HINT` | Silences the one-line \"Invited-memory 未启用：`claude-mem-lite adopt`…\" hint that SessionStart appends when the current project hasn't been adopted. The hint self-clears once `adopt` runs; set this env to suppress it without adopting. | _(disabled)_ |\n\n## License\n\nMIT\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsdsrss%2Fclaude-mem-lite","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fsdsrss%2Fclaude-mem-lite","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsdsrss%2Fclaude-mem-lite/lists"}