brain-v42
brain-v42
Постоянная память для агентов кодирования, доступная через MCP.
brain-v42 предоставляет Claude Code, Codex и любому другому MCP-клиенту долговечный второй мозг: решения, наработки, фрагменты кода, runbook'и, ADR, тикеты и дорожные карты проектов — хранятся в PostgreSQL, находятся через полнотекстовый + семантический поиск с реранжированием и консолидируются каждую ночь конвейером агентов.
Типизированные знания, а не свалка заметок — решение записывает своё «почему» и альтернативы; фрагмент записывает своё назначение; runbook записывает исполнимые шаги. Каждый тип имеет свой жизненный цикл (цепочки замены, принятие ADR, валидация наработок).
Явный жизненный цикл сессии — пользователь владеет каждой границей сессии. Сессии захватывают созданные ими артефакты, и закрытие работает по принципу fail-closed: сессия завершается либо с захваченными знаниями, либо с явной причиной «нечего захватывать», но никогда молча.
Поиск с ранжированием — семантический поиск pgvector + FTS PostgreSQL, объединяемые и переранжируемые кросс-энкодером.
Ночная консолидация («dream») — конвейер агентов очищает осиротевшие ссылки, объединяет дубликаты, синтезирует наработки и предлагает продвижения, за пофазовыми killswitch, которые все поставляются выключенными.
Мультипроектность — фокус на проекте с ревизиями compare-and-swap, дорожными картами, кросс-проектными тикетами.
Архитектура
Claude Code / Codex (MCP client)
│ HTTP loopback :8765/mcp (production) · stdio (dev/fallback)
brain-v42 (FastMCP)
├── SQLAlchemy async ─▶ PostgreSQL 16 + pgvector (source of truth)
├── HTTP ─────────────▶ embedding endpoint :8003 (optional, pluggable)
├── HTTP ─────────────▶ :8003/rerank (optional reranker)
└── bolt ─────────────▶ Neo4j 5 Community (relationship index, optional)MCP-транспорт: продакшен = HTTP loopback http://127.0.0.1:8765/mcp; конфигурация по умолчанию и dev/fallback = stdio.
PostgreSQL — единственный источник истины. Neo4j — одноразовая проекция, питаемая
реляционным журналом/outbox — её всегда можно пересобрать из PostgreSQL, но не наоборот.
Канонический путь активен в продакшене с 22 июля 2026 года; дизайн и обоснование находятся
в docs/ARCHITECTURE.md и runbook по графическому журналу.
Эмбеддинги опциональны и подключаемы. Сам сервер не зависит от модели: он говорит
только на трёхмаршрутном HTTP-контракте (POST /embed, POST /embed/query,
POST /rerank) и корректно деградирует, когда эндпоинт недоступен — brain_search
переключается на полнотекстовый поиск, записи сохраняются с NULL-эмбеддингом и
позже заполняются. Любой сервер, реализующий этот контракт, подходит. В комплекте
эталонный стек (services/) обслуживает Qodo-Embed-1-1.5B в формате GGUF через llama.cpp
на локальном GPU. EMBEDDING_DIMENSION выбирается при установке; смена модели позже означает
пересоздание эмбеддингов корпуса (scripts/regen_embeddings.py).
Related MCP server: Cortex MCP Server
Быстрый старт
git clone https://github.com/hawkixs/brain-v42 && cd brain-v42
python -m venv .venv && source .venv/bin/activate
pip install -e ".[dev]"
# 1. Local Neo4j secret (skip if you run without the graph)
install -d -m 0700 .secrets
read -rsp "Neo4j password (same value as NEO4J_PASSWORD in .env): " PW
(umask 0022; printf 'neo4j/%s\n' "$PW" > .secrets/neo4j-auth); unset PW
# 2. Databases (PostgreSQL 16 + pgvector, Neo4j)
docker compose up -d
# 3. Migrations
export POSTGRES_URL="postgresql+asyncpg://brain:REPLACE_WITH_PASSWORD@localhost:5433/brain"
BRAIN_ALEMBIC_ALLOW_PROD=1 alembic upgrade head
# 4. Run the MCP server (stdio)
python -m brain_v42.mcp.serverПодключите его к Claude Code — .mcp.json в корне репозитория уже указывает на продакшен-HTTP-loopback
эндпоинт; для простой stdio-настройки разработки:
claude mcp add brain-v42 -- python -m brain_v42.mcp.serverBRAIN_ALEMBIC_ALLOW_PROD требуется только когда имя базы данных — ровно brain;
оставьте его одноразовым явным согласием в команде, никогда не экспортируйте постоянно. Alembic
отвергает параметры запроса DSN; используйте простую форму выше, где присутствуют хост, порт, имя пользователя и пароль.
MCP-инструменты
Домен | Инструменты |
Поиск и список |
|
Обход графа |
|
Жизненный цикл сессии |
|
Контекст проекта |
|
Решения |
|
Наработки |
|
Фрагменты |
|
Инструкции |
|
ADR |
|
Координация |
|
Dream / граф |
|
Дорожная карта и устаревание |
|
Руководство по рабочим процессам |
|
Полный каталог с сигнатурами: docs/MCP_TOOLS.md.
Профиль каталога по умолчанию — compact: семь инструментов жизненного цикла сессии остаются
видимыми, а все остальные инструменты доступны через два шлюза — brain_find_tool
для поиска и brain_call_tool для вызова. Установите BRAIN_MCP_PROFILE=native, чтобы раскрыть
все инструменты напрямую.
Сессии
Пользователь управляет каждой границей сессии: start, resume, end и abandon — это
явные команды, никогда не выводятся из поведения хука, агента или клиента. Сессии захватывают
созданные ими долговечные артефакты в эксклюзивный журнал, и закрытие работает по принципу
fail-closed: либо захваченные знания, либо явная причина «нечего захватывать», но никогда
молчание.
Через 24 часа без heartbeat открытая сессия показывает is_stale=true; маркер
вычисляется, постоянный статус остаётся open, и только серверная очистка через 7 дней
может завершить сессию без явной команды пользователя.
Полный контракт жизненного цикла (правила захвата, семантика фокуса, бриф) находится в
docs/MCP_TOOLS.md; контракт имеет версию v4 и всё ещё развивается.
Конфигурация (.env)
# Required
POSTGRES_URL=postgresql+asyncpg://brain:REPLACE_WITH_PASSWORD@localhost:5433/brain
# Optional — semantic search and reranking
EMBEDDING_SERVICE_URL=http://localhost:8003
EMBEDDING_DIMENSION=1536
RERANKER_URL=http://localhost:8003
# Optional — relationship graph (safe defaults for a fresh environment)
GRAPH_ENABLED=false
GRAPH_LEDGER_WRITE_ENABLED=false
# Tool catalog profile
BRAIN_MCP_PROFILE=compact # compact (default) or native
LOG_LEVEL=INFOНикогда не помещайте MCP_HTTP_TOKEN или MCP_HTTP_DREAM_TOKENS в общий .env: bearer-токены
хранятся в приватном файле с правами 0600 (~/.config/brain-v42/mcp-token.env), а
учётные данные проектора графа — в отдельном (~/.config/brain-v42/graph-projector.env).
Полная справка — все переменные, приватные секретные файлы, проверки перед запуском и
контрольные точки развёртывания: docs/OPERATIONS.md.
Модель доверия в сети
Развёртывание предназначено для персональных агентов в доверенной локальной сети. MCP, PostgreSQL и Neo4j привязываются к loopback; метрики и автоматизация по умолчанию работают на loopback.
Топология эмбеддингов: продакшен/по умолчанию = локальный единый эндпоинт http://localhost:8003; deploy/dev-pc — устаревший путь отката/эталонный путь.
Реранкер использует единый эндпоинт эмбеддингов :8003/rerank. Считайте :8003 доступным
из LAN, пока вы сами не подтвердите актуальную привязку, и никогда не открывайте его — или
MCP-порт — в Интернет. Код репозитория сам по себе не доказывает реальное состояние
межсетевого экрана.
Режим Dream
Ночной конвейер агентов (scripts/dream.sh: scan → clean → connect → synth → promote →
reorg) плюс серверные задачи извлечения тикетов, курирования дорожных карт и очистки сессий.
Каждая изменяющая фаза находится за killswitch, и все killswitch поставляются выключенными;
dry-run — поставляемый по умолчанию режим. Каждая фаза выполняется с точным разрешённым списком MCP-инструментов.
Подробности: docs/ARCHITECTURE.md и
docs/OPERATIONS.md.
Состояние продакшена
Целевая миграция репозитория — миграция 045. Ни одна страница этого репозитория не доказывает актуальную голову схемы — измерьте это, а не читайте здесь:
docker exec brain_v42_postgres psql -U brain -d brain -Atc "select version_num from alembic_version;"Работающая сборка называет себя сама: GET /health возвращает version (установленный
дистрибутив) и alembic_head (ревизию, поставляемую с ним), оба значения измеряются, никогда
не записываются вручную.
Разработка
pytest tests/unit -v # no PostgreSQL required
pytest --cov=brain_v42 --cov-report=term-missing
ruff check src/ tests/ && ruff format --check src/ tests/
mypy src/Стек: Python 3.12+, FastMCP 3.x, SQLAlchemy 2.0 async + asyncpg, Alembic, Pydantic 2, structlog.
TDD обязателен — красный, зелёный, рефакторинг; тесты никогда не редактируются, чтобы заставить код проходить.
Минимальный порог покрытия: 60% (CI блокирует ниже).
Инструментарий разработки зафиксирован точно (
pip install -e ".[dev]"), поэтому локально всегда совпадает с CI.
Структура проекта
brain-v42/
├── src/brain_v42/
│ ├── config.py # pydantic-settings — single config surface
│ ├── db/ # SQLAlchemy engine + tables
│ ├── models/ # Pydantic models
│ ├── repositories/ # CRUD + FTS + pgvector + graph adapters
│ ├── services/ # business logic, embedding, reranker, dream, dedup
│ ├── metrics/ # sidecar + collector + cockpit endpoint
│ ├── automation/ # independent webhook/dedup runtime (:9201)
│ └── mcp/ # FastMCP server + brain_*/dream_* tool handlers
├── tests/{unit,integration}
├── alembic/versions/ # migrations (shipped inside the wheel)
├── scripts/ # operational CLIs (dream.sh, canaries, repair)
├── services/ # GPU embedding service + shim + supervisor
├── deploy/ # systemd units, per-host compose, install.sh
└── docs/ # ARCHITECTURE, SCHEMA, MCP_TOOLS, OPERATIONS, runbooksГраф модулей верхнего уровня принудительно ацикличен в CI
(scripts/check_module_layering.py): любой модуль всё ещё можно выделить в отдельный
сервис, не таская за собой цикл.
CI/CD
Этапы: lint → test → security → build. Защитные контрольные точки: pip-audit, bandit, gitleaks,
проверки закрепления образов контейнеров. Docker-образы собираются и публикуются в main; стадии
деплоя нет — развёртывание на хосте всегда выполняется вручную, как внешний этап. Релизы
управляются тегами: сборочная линия релиза собирает wheel + sdist, проверяет, что wheel содержит
миграции, и прикрепляет оба артефакта к релизу на GitHub.
Версионирование
Поставляемая версия — 0.2.0, и она намеренно остаётся
0.x:1.0.0обещала бы стабильный интерфейс и путь назад, а у этого проекта пока нет ни того, ни другого.Без потерь даунгрейд не обещается ни в какой версии. Две миграции отказываются от собственного
downgrade: 037 вызывает SQLEXCEPTION, как только может быть потерян захват сессии, а 039 вызывает исключение, пока оператор не передаст явное согласие-x.Поэтому откат схемы — это процедура оператора с инструкцией, а не гарантия версионирования — вместо этого восстанавливайтесь из снимка.
Лицензия
Исходный код: Apache-2.0.
Веса моделей не покрываются этой лицензией, и это не формальность. Продакшн-модель эмбеддингов, Qodo/Qodo-Embed-1-1.5B, опубликована под QodoAI-Open-RAIL-M — лицензией с ограничениями на использование, а не пермиссивной. Никакие веса не хранятся и не распространяются этим репозиторием: каждая модель загружается с вышестоящего хоста во время сборки оператором, который принимает условия каждой модели напрямую от её издателя. См. NOTICE перед распространением чего-либо.
Available Tools
11 toolsbrain_call_toolA
Call a tool by name with the given arguments.
Use this to execute tools discovered via search_tools.
Inputs: name (required), arguments.
brain_find_toolA
Search for tools using natural language.
Returns up to 5 matching tools ranked by relevance, each as a summary: name, one-line description, required parameters with types, optional parameter names. Pass an exact tool name to get that tool's full input schema.
Inputs: query (required). Returns: result
brain_session_abandonBDestructiveIdempotent
Abandon a session only from an explicit user command.
An agent tracer is the only session the server opens or closes on its own; no hook and no auto-close may invoke this lifecycle boundary.
Inputs: reason (required), session_id (required), expected_client_key (required).
brain_session_bindAIdempotent
Bind an open operator session to one focus slot, from an explicit user command.
Once per session; binding the same slot again is a replay. From then on the
session's end writes that slot only, never the project base:
expected_focus_revision is the slot revision returned here. Refusals:
session_not_open, session_is_agent_trace, session_already_bound,
slot_not_found, slot_closed, slot_project_mismatch, slot_busy.
An agent tracer is the only session the server opens or closes on its own; no hook and no auto-close may invoke this lifecycle boundary.
Inputs: slot_id (required), session_id (required), expected_client_key (required). Returns: `brain_session_bind`: the slot revision an end or relay must send next.
brain_session_captureAIdempotent
Attach durable artifacts from an explicit user command — to repair or refine.
No longer a compulsory ritual. With derived capture armed, artifacts
created during the session are attributed without this call, and end
no longer demands a receipt. What this tool is for now: attaching
something the derivation could not see — created outside the window,
on another connection, or in another project — and saying so on the
record.
It never steals: an artifact already attributed stays where it is.
An agent tracer is the only session the server opens or closes on its own; no hook and no auto-close may invoke this lifecycle boundary.
Inputs: session_id (required), knowledge_ids (required), expected_client_key (required).
brain_session_endADestructiveIdempotent
End a session from an explicit user command, on judgement alone.
nothing_to_capture_reason is now OPTIONAL. The old rule — a non-empty
ledger XOR a written reason — measured whether the client had DECLARED
its work. Derived capture feeds that signal from the server, and a check
is hollow the moment the thing it checks can influence its own signal;
worse, it made a session whose ledger the server had filled impossible
to close. Give a reason if you have one to give; a blank one is still
refused, because saying nothing and saying " " are not the same act.
What end still requires is what the server cannot produce for you:
a summary and a next focus. It REPORTS unattributed_in_window —
artifacts of this project created during the session that belong to no
ledger — as a measure, never a gate. It cannot refuse a close, and a
session cannot improve it by doing nothing.
For a bound session, expected_focus_revision is the SLOT revision (from
bind, resume, or relay's slot.revision), never started_focus_revision.
For an UNBOUND session, next_focus REPLACES the project's whole base focus
under a compare-and-swap on expected_focus_revision. SHRINK GUARD: a
next_focus under 70% of the current base focus is refused before any write
(base_focus_shrink, current, proposed and floor in the message) and the
session stays open, so carry the durable content over and call again. A bound
end REPLACES the whole slot body and meets the same 70% guard
(slot_focus_shrink). allow_focus_shrink = true requires an active
/brain-admin elevation for this credential and MCP connection; otherwise
focus_shrink_override_refused is raised before any mutation. Shared-token
and stdio callers cannot override; an operator relay can. A stale revision is still
recorded as a conflict and closes the session, since nothing is written.
An agent tracer is the only session the server opens or closes on its own; no hook and no auto-close may invoke this lifecycle boundary.
Inputs: summary (required), next_focus (required), session_id (required), expected_client_key (required), +3 more. Returns: Outcome of ending a session and conditionally updating shared focus.
brain_session_heartbeatA
Refresh an open session from an explicit user command.
An agent tracer is the only session the server opens or closes on its own; no hook and no auto-close may invoke this lifecycle boundary.
Inputs: session_id (required), expected_client_key (required).
brain_session_listARead-onlyIdempotent
List sessions only in response to an explicit user command.
An agent tracer is the only session the server opens or closes on its own; no hook and no auto-close may invoke this lifecycle boundary.
Inputs: limit, offset, status, project_key.
brain_session_relayADestructiveIdempotent
Relay an open session onto its slot, or its project base: capture, end, restart.
One transaction: the named knowledge_ids are captured into the old session,
the handover is written under a compare-and-swap, the old session ends, and
a successor opens under new_client_key; its briefing follows. Two forms,
and exactly one revision per call.
briefing defaults to full detail; compact returns counts and IDs in at
most 4,000 characters. Focus text appears only in session.started_focus.
Bound session: send expected_slot_revision; the handover (at most 4,000
characters) REPLACES the whole slot body and the successor stays on the slot. A
closed slot or a stale revision changes nothing and leaves the session open.
Unbound session: send expected_focus_revision, the BASE revision; the
handover becomes the project's whole base focus and the successor is
unbound. A stale revision (focus_revision_conflict) changes nothing and
leaves the session open, unlike end, which closes anyway. SHRINK GUARD: a
handover under 70% of the current base focus is refused (base_focus_shrink,
both lengths in the message), because it REPLACES the whole base: carry the
durable content over. An operator relay may pass allow_focus_shrink = true
only with an active /brain-admin elevation for this credential and MCP
connection; a guard mod never can.
The same 70% guard applies to a bound slot body (slot_focus_shrink).
The override is enforced before mutation: only initiator='operator' can
pass it, and only with an active /brain-admin elevation for this credential
and MCP connection. A guard_mod relay is refused even if elevated.
An equal replay returns the same successor with replayed = true; any other
payload on an ended session is terminal_conflict. The successor's next end
or relay sends result.slot.revision (bound: the SLOT revision, from bind,
resume, or relay) or result.focus_revision (unbound: the new BASE revision),
never started_focus_revision for a bound one.
A guard mod the operator explicitly enabled may make this call as a standing
user command, and only this one (Amendment — slot relay (ADR #34)); with
initiator = 'guard_mod' it is refused while
BRAIN_SESSION_RELAY_GUARD_MOD_ENABLED is false.
An agent tracer is the only session the server opens or closes on its own; no hook and no auto-close may invoke this lifecycle boundary.
Inputs: summary (required), handover (required), initiator (required), session_id (required), +8 more. Returns: `brain_session_relay`: the ended session, its successor, what the CAS wrote. A…
brain_session_resumeBRead-onlyIdempotent
Resume an open session from an explicit user command.
An agent tracer is the only session the server opens or closes on its own; no hook and no auto-close may invoke this lifecycle boundary.
Inputs: session_id (required), expected_client_key (required). Returns: Current context returned when attaching to an open session.
brain_session_startAIdempotent
Start or replay a concurrent session from an explicit user command.
briefing defaults to full detail; compact returns counts and IDs in at
most 4,000 characters. Focus text appears only in session.started_focus.
An agent tracer is the only session the server opens or closes on its own; no hook and no auto-close may invoke this lifecycle boundary.
Inputs: client_key (required), project_key (required), briefing. Returns: Outcome of an idempotent session start.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 11 tools
The nine brain_session_* tools each nominally target a distinct lifecycle action, and the verbose descriptions clarify nuances, but several boundaries overlap heavily — relay internally performs capture+end+start, making it confusable with end/start, and start vs resume vs bind blur together. An agent could plausibly pick the wrong lifecycle tool for a given situation.
All names are snake_case with a consistent brain_ prefix, so the set is readable. There is a minor structural deviation: session tools use brain_<noun>_<verb> (brain_session_start) while the meta tools use brain_<verb>_<noun> (brain_call_tool, brain_find_tool), but the pattern is still predictable.
11 tools is within the well-scoped 3-15 range. The session lifecycle legitimately needs many operations, though nine session tools plus two meta tools is on the heavier side for what is essentially one domain.
The session lifecycle is thoroughly covered — start, heartbeat, capture, resume, bind, relay, end, abandon, list — plus meta tools for discovery and invocation. The only notable gap is that slots/focus are referenced extensively in relay/end but no tool here creates or manages slots, leaving a potential dead end for that sub-resource.
Maintenance
Related MCP Connectors
Persistent memory, knowledge graph, task management and more for AI agents via MCP.
Team memory for AI coding agents and code reviews, reviewed by humans and served over MCP.
Persistent memory and cross-session learning for AI coding assistants (hosted remote MCP).
Hosted MCP memory for coding agents: persistent across sessions, editable markdown, team sharing.
Related MCP Servers
- AlicenseAqualityDmaintenanceProvides persistent memory for AI coding agents via MCP, enabling teams to share and recall facts across sessions. Automatically captures, classifies, and curates knowledge from supported transcript sources.1834 npm1AGPL 3.0
- AlicenseNot gradedqualityCmaintenanceProvides persistent memory and task management for coding agents via MCP tools, enabling mid-session recall and capture of durable knowledge.12MIT
- AlicenseNot gradedqualityBmaintenanceProvides persistent, searchable memory across coding projects and machines, letting agents record and retrieve projects, reusable assets, sessions, decisions, commits, and handoffs via MCP.3Apache 2.0
- FlicenseNot gradedqualityCmaintenanceEnables AI coding agents and IDEs to capture conversations, extract structured knowledge into a queryable graph database, and recall past decisions, patterns, files, and errors across all projects and workspaces. Provides persistent memory tools for saving, searching, and cleaning up knowledge via MCP.2-