Skip to content

About

BlackHoleMemory: local self-hosted long-term memory platform for agent workflows

Resources

Security policy

Stars

5 stars

Watchers

0 watching

Forks

Repository files navigation

BlackHoleMemory

Local, verifiable long-term memory and code intelligence for AI agents.

BHM CI CodeQL Release Python 3.12+ MCP License: 0BSD

English · Русский

English

Graph coverage and architecture calls default to detail="compact". Use detail="full" for detailed reference data; offset and limit page layers, dependencies, hotspots, index delta lists and full parser languages. Each list has pagination metadata with total and next_offset.

What it is

BlackHoleMemory (BHM) is a local-first, self-hosted memory contour for AI coding agents. It connects facts, decisions, tasks, errors, files, and dependencies into bounded, provenance-bearing context that can be searched and checked after a session ends. BHM exposes the same core through a FastAPI REST surface and a local Streamable HTTP MCP endpoint.

Design at a glance

AI agent / IDE
      │
      ├── REST API       http://127.0.0.1:8000/bhm/
      └── MCP            http://127.0.0.1:8000/mcp
                           │
                    FastAPI + LangGraph
                           │
             SQLite (authoritative lifecycle store)
                           │
                 transactional memory_outbox
                    ┌──────┴──────┐
                    │             │
          Mem0 semantic/      Qdrant rebuildable
          logical layer       vector projection
                    │             │
                    └──────┬──────┘
                           │
          candidate IDs / ranking hints only
                           │
         SQLite revalidation → canonical context

The authority boundary is deliberate:

  • SQLite is authoritative for memory lifecycle, metadata, provenance, and recovery.
  • Mem0 is the semantic/logical layer used to consolidate and retrieve context.
  • Qdrant is a rebuildable projection, never a second source of truth.
  • In the default SQLite-authoritative launcher, a Docker/Qdrant outage degrades semantic projection and SLO without taking the core API or MCP offline.
  • API and MCP readiness validate the required embedding capability, not an arbitrary chat model currently loaded by the local provider.
  • LangGraph orchestrates stateful agent workflows.
  • Destructive or proposal-only operations stay behind explicit operator controls; BHM does not silently edit code or data.

Capabilities

  • Project-scoped memory, search, context compilation, tasks, sessions, and checkpoints.
  • Repository indexing, bounded code search, code-graph and architecture queries, and change-impact previews.
  • Provenance-aware MCP tools with caller/project authorization, bounded outputs, and fail-closed transport checks.
  • Optional Galaxy/workbench views for local operators. The browser UI is launcher-bound: direct anonymous navigation intentionally requires a trusted local bootstrap token.
  • Rebuildable Qdrant projection with SQLite parity and read-only lifecycle/telemetry reports.

Quick start (Windows)

Requirements: Windows 10/11, Python 3.12+, uv, and Docker Desktop with Compose for Qdrant.

git clone https://github.com/Efidripy/BlackHoleMemory.git
cd BlackHoleMemory
uv sync --locked
powershell -NoProfile -ExecutionPolicy Bypass -File .\scripts\start-bhm-authoritative.ps1
Invoke-RestMethod http://127.0.0.1:8000/health/ready

Canonical local endpoints:

Surface URL
BHM API http://127.0.0.1:8000/bhm/
MCP http://127.0.0.1:8000/mcp
Galaxy UI (Atlas) http://127.0.0.1:8000/bhm/galaxy (open through the trusted launcher)
Readiness http://127.0.0.1:8000/health/ready
Qdrant dashboard http://127.0.0.1:6333/dashboard/

For the packaged Windows launcher, use scripts/build-release.ps1. Release archives and detached verification sidecars are produced outside the source tree.

MCP integration

The canonical server id is bhm and the transport is local Streamable HTTP. Keep caller credentials in environment/configuration outside Git:

[mcp_servers.bhm]
url = "http://127.0.0.1:8000/mcp"
bearer_token_env_var = "BHM_CALLER_TOKEN"

See docs/mcp-caller-token-runbook.md for token handling and docs/architecture-authority.md for the authority model. Configured MCP inventory is informational until the current client has verified an attached native session.

For a complex coding task, an attached agent should first call the public, read-only bhm_agent_playbook MCP tool. It returns a versioned task-specific sequence of relevant read-only BHM tools, freshness rules, evidence fields and write boundaries. It does not inspect project data or modify BHM, the runtime, or client files. If MCP is unavailable, the agent continues with Git, source, tests and canonical documentation instead of trying to repair local BHM setup.

Evidence and benchmark boundaries

The checked-in BHM Value Benchmark is a deterministic frozen-fixture study: 1,000 unique cases replayed 10 times (10,000 case evaluations) across controlled no-memory, file-only, vector, and BHM modes. It demonstrates retrieval, provenance, context-budget, and leakage behavior on that fixture; it is not universal model quality or real-user telemetry.

The separate local-model replay uses 111 cases × 3 repetitions for file-only and bhm-full (666 calls) with frozen prompts and temperature=0. Its receipt is local operational evidence, not a hosted-service benchmark.

The separate local-model quality gate checks one already-loaded exact LM Studio model against a frozen synthetic answer contract. A passing 100% score is scoped to that model, prompt, fixture and local invocation; it is not a claim of universal model accuracy.

The semantic assurance contract separately evaluates bounded factuality, entailment, evidence relevance and hidden-conflict routing. Its finite corpus and confidence intervals are evidence for a declared scope, never proof of universal correctness or admission for automatic semantic apply.

An operator may run the offline LoCoMo retrieval smoke only against a separately admitted local corpus. It caps a run at 50 cases and uses disposable in-memory lexical retrieval; it neither fetches data nor calls a model or judge, and it does not mutate SQLite, Qdrant, Mem0, or the runtime. Its receipt contains only IDs, digests, and aggregate metrics, so it is retrieval-boundary evidence rather than a production-quality claim.

Security and data boundaries

BHM is designed for an authorized local development environment. Keep .runtime, .docs, .src, credentials, databases, logs, and release signing keys local. SQLite remains the recovery anchor; Qdrant may be rebuilt from it. Review the security policy, error taxonomy, and troubleshooting guide before enabling operator workflows.

Documentation, contributing, and license

  • Start with docs/getting-started.md, docs/usage.md, and docs/configuration.md.
  • Read docs/README.md for the documentation map.
  • Run the project gates before submitting changes: uv sync --locked --extra dev, uv run pytest -q, uv run ruff check src tests scripts, uv run python -m compileall -q src scripts tests, and the documented release/public-tree validators. The dev extra includes the offscreen PyQt6 UI contract and httpx2 TestClient implementation.
  • Contributions are welcome through issues and pull requests. Preserve the SQLite-authoritative boundary and do not commit secrets or runtime artifacts.

BHM-authored code and documentation are released under the 0BSD license. Third-party components retain their own licenses and provenance records.

Русский

BlackHoleMemory (BHM) — локальная self-hosted память и контур code intelligence для AI-агентов. Он сохраняет факты, решения, задачи, ошибки, файлы и зависимости с областью проекта и provenance, а затем возвращает проверяемый контекст через REST и локальный MCP Streamable HTTP.

Архитектурное правило неизменно: SQLite — единственный authoritative store, Mem0 — семантический слой, Qdrant — восстанавливаемая projection, LangGraph — оркестрация. В штатном SQLite-authoritative launcher сбой Docker/Qdrant ухудшает semantic projection и SLO, но не отключает core API/MCP; readiness API/MCP проверяет требуемую embedding capability, а не произвольно загруженную chat model локального provider. Разрушительные и proposal-only действия требуют явного operator control. Galaxy/workbench — локальная launcher-bound UI-поверхность; прямой anonymous URL намеренно требует доверенный bootstrap.

Быстрый запуск:

uv sync --locked
powershell -NoProfile -ExecutionPolicy Bypass -File .\scripts\start-bhm-authoritative.ps1
Invoke-RestMethod http://127.0.0.1:8000/health/ready

Точки доступа: API — http://127.0.0.1:8000/bhm/, MCP — http://127.0.0.1:8000/mcp, Galaxy (Atlas) — http://127.0.0.1:8000/bhm/galaxy через доверенный launcher. Atlas — read-only 3D-карта всей памяти: каждая запись — светящаяся точка, расставленная по реальным эмбеддингам (kNN, скелет связей и сохранённые relations), с материнским узлом у каждого проекта, свободным вращением и «тягой». Раскладка строится в фоне и кешируется; прежний Night Sky остаётся на /bhm/galaxy/classic и открывается кнопкой «Инструменты». Подробности: docs/getting-started.md, docs/usage.md, docs/mcp-caller-token-runbook.md.

Benchmark в репозитории — frozen-fixture evidence, а не telemetry реальных пользователей. Основной прогон: 1,000 кейсов × 10 повторов; отдельный local-model replay: 111 × 3 для двух режимов, всего 666 вызовов. Отдельный local-model quality gate проверяет только уже загруженную точную модель на синтетическом answer-contract; 100% в нём не является утверждением о всеобщей точности. Секреты, базы, .runtime, .docs, .src и ключи подписи не публикуются.

Отдельный контракт semantic assurance измеряет в ограниченной области factuality, entailment, relevance доказательств и маршрутизацию hidden conflicts. Конечный корпус и интервалы доверия — это evidence только объявленного scope, а не доказательство универсальной корректности или допуск к automatic semantic apply.

Операторский LoCoMo smoke запускается только по отдельно принятому локальному корпусу: максимум 50 кейсов, disposable in-memory lexical retrieval. Он не скачивает данные, не вызывает модель или judge и не меняет SQLite, Qdrant, Mem0 либо runtime. В receipt сохраняются только IDs, digests и агрегированные метрики: это evidence границы retrieval, а не заявление о production-качестве.

Лицензия материалов BHM — 0BSD; зависимости сохраняют собственные лицензии.

About

BlackHoleMemory: local self-hosted long-term memory platform for agent workflows

Resources

Security policy

Stars

5 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages