ctx-memory
ctx-memory
Постоянная память для LLM-агентов по программированию — Claude Code, Codex, Gemini CLI, OpenCode.
Когда вы начинаете новую сессию, агент уже знает, над чем вы работали в прошлый раз: принятые решения, измененные файлы, возникшие ошибки, изученные соглашения. Никакого облака. Никакой телеметрии. Все хранится в локальной базе данных SQLite по адресу ~/.ctx-memory/store.db.
Как это работает
Session starts
│
Shell wrapper intercepts 'claude' (or codex/gemini/opencode)
│
MCP server starts alongside — injects prior context, exposes memory tools
│
During session: hooks fire on every tool call, messages buffered
│
Session ends (clean exit / Ctrl-C / crash)
│
Layer 1 → Layer 2 → Layer 3 pipeline runs
│
├── Layer 1: extract weighted messages, events, decisions, errors, keywords
├── Layer 2: compress to ≤500-token digest, store in DB
└── Layer 3: merge digest into project memory doc (markdown)
Next session: agent reads prior context automaticallyRelated MCP server: remem
Установка
npm install -g ctx-memory
ctx-memory setupМастер настройки:
Определяет, какие инструменты установлены (
claude,codex,gemini,opencode)Спрашивает, какие из них интегрировать
Записывает конфигурации хуков для каждого инструмента
Создает символические ссылки-обертки в
~/.ctx-memory/bin/Добавляет
~/.ctx-memory/binв ваш PATH через~/.bashrc/~/.zshrc
Перезапустите оболочку (или выполните source ~/.bashrc), затем используйте свои инструменты как обычно — память работает автоматически.
Команды
ctx-memory setup # interactive setup wizard
ctx-memory status # show configuration and stats
ctx-memory projects list # list all projects
ctx-memory projects show <name> # print full memory doc for a project
ctx-memory projects forget <name> # reset memory (keeps sessions)
ctx-memory projects forget <name> --hard # delete all sessions + dataMCP-сервер
MCP-сервер работает как sidecar-процесс вместе с каждой сессией инструмента и предоставляет шесть инструментов:
Инструмент | Описание |
| Буферизация сообщения диалога для обработки по завершении сессии |
| Запись события вызова инструмента (редактирование файла, bash-команда и т.д.) |
| Поиск по прошлым сессиям по семантическому сходству или ключевым словам |
| Возврат полного документа памяти проекта |
| Список недавних сессий с целями и результатами |
| Завершение сессии и запуск конвейера Уровень 1 → Уровень 2 → Уровень 3 |
Чтобы использовать MCP-сервер автономно с Claude Code, добавьте в ~/.claude/settings.json:
{
"mcpServers": {
"ctx-memory": {
"command": "node",
"args": ["/path/to/ctx-memory/dist/src/mcp/index.js"]
}
}
}Архитектура
src/
cli/ — setup wizard, status, projects commands
db/ — SQLite schema + CRUD (projects, sessions, events, digests, memory)
layer1/ — pure message/event processing → weighted Layer1Output
layer2/ — digest compression to ≤500 tokens → Layer2Digest
layer3/ — merge digest into ProjectMemory markdown
mcp/ — MCP server (handlers + stdio entry point)
wrapper/ — shell wrapper (intercepts tool invocation, manages session lifecycle)
hooks/ — hook config writers for Claude / Gemini / OpenCodeКлючевые ограничения:
Все функции Уровня 1/2/3 являются чистыми — никакого ввода-вывода, никогда не вызывают исключений
Дайджесты остаются в пределах 500 токенов
Векторный поиск использует эмбеддинги all-MiniLM-L6-v2 через
sqlite-vec(384 измерения)Единая БД SQLite, режим WAL, внешние ключи включены
Разработка
npm run build # tsc → dist/
npm run dev # tsc --watch
npm run test:run # vitest (single-shot, 476+ tests)
npm test # vitest (watch mode)Путь к БД по умолчанию: ~/.ctx-memory/store.db. Переопределите с помощью CTX_MEMORY_DB_PATH.
Лицензия
MIT
Available Tools
6 toolsend_sessionC
Signal session end — runs Layer 1→2→3 pipeline, stores digest, updates project memory.
Inputs: outcome (required), project_id (required), session_id (required), exit_code.
get_project_memoryC
Return the full project memory document (architecture, conventions, recent work, known issues).
Inputs: project_id.
list_sessionsC
List recent sessions for a project with their goals and outcomes.
Inputs: limit, project_id.
search_contextB
Search past sessions for context relevant to a query. Uses embedding similarity, falls back to keyword search.
Inputs: query (required), limit, project_id.
store_eventC
Record a tool call event (file edit, bash command, etc.) for the current session.
Inputs: tool (required), session_id (required), args, result, +1 more.
store_messageC
Buffer a conversation message for session-end processing.
Inputs: role (required), index (required), content (required), session_id (required).
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 6 tools
Each tool has a clearly distinct purpose: session lifecycle (end_session), memory retrieval (get_project_memory, list_sessions, search_context), and data recording (store_event, store_message). No overlap in functionality.
All tool names follow a consistent verb_noun pattern using snake_case, e.g., end_session, get_project_memory, store_event. The naming is predictable and uniform.
With 6 tools, the server covers core memory management operations without bloat. The count is well-scoped for the domain of session context and project memory.
The tool surface covers the full typical lifecycle: recording events/messages, searching and retrieving context, listing sessions, and finalizing sessions with memory updates. No obvious gaps.
Maintenance
Related MCP Connectors
Persistent cross-session memory shared by Codex, Claude Code, ChatGPT, and other AI agents.
Shared memory for coding agents. Stop re-explaining your codebase every session.
Persistent memory for AI agents — shared .brain across Claude Code, Cursor & Codex
Persistent memory for AI agents: one brain shared across Claude, Cursor, Codex and more.
Related MCP Servers
- AlicenseBqualityBmaintenancePersistent, local memory for AI coding agents that learns how you work, not just what you said. Supports Claude Code, Codex CLI, Cursor, and any MCP client.79115 PyPI75MIT
- AlicenseAqualityAmaintenanceLocal-first persistent memory for Claude Code and OpenAI Codex CLI. A single Rust binary captures, distills, searches, and injects project memory across sessions via hooks, MCP, CLI, and localhost REST.1533MIT
- FlicenseNot gradedqualityCmaintenancePersistent, self-curating memory for coding agents. It enables local, zero-cost context recall through MCP tools with hybrid retrieval and autonomous consolidation.-
- FlicenseNot gradedqualityBmaintenancePersistent memory for AI coding agents: local-first semantic search, dependency graphs, git history.1-