# Open Brain — Personal Semantic Memory MCP Server — Complete AI & LLM Reference Corpus (`llms-full.txt`) - Repository: https://github.com/mohan-n-swamy/open-brain-public - Web Discovery URL: https://mohan-n-swamy.github.io/repos/open-brain-public/ - License: MIT - Keywords: mcp-server, model-context-protocol, pgvector, semantic-search, hybrid-search, second-brain, obsidian, long-term-memory, rag, personal-ai, postgresql, python --- ## File: `AI-README.md` — AI-README.md --- repo: "mohan-n-swamy/open-brain-public" title: "Open Brain — Personal Semantic Memory MCP Server" license: "MIT" keywords: [mcp-server, model-context-protocol, pgvector, semantic-search, hybrid-search, second-brain, obsidian, long-term-memory, rag, personal-ai, postgresql, python] capabilities: - "Hybrid retrieval (`search_chunks`, `search_summaries`) supporting both calibrated weighted scoring (0.55 cosine + 0.20 BM25 + 0.15 recency + 0.20 canonical) and Reciprocal Rank Fusion (`RRF k=60`)." - "Instant zero-database CLI demo (`python3 bin/ob-demo.py ./sample-vault`) to test chunking, secret scrubbing, and cited retrieval in under one second." - "Citation-enforced payloads: every result header carries `[chunk:]` plus similarity, keyword score, and age metadata." - "One-way Obsidian importer (`import-obsidian.py`) with pre-embedding secret redaction, SHA-256 fingerprint short-circuiting, revision supersession, and 50% mount-guard orphan circuit breakers." - "Zero-egress local embeddings by default via Ollama `bge-m3` (1024 dimensions), with `.env` overrides for any OpenAI-compatible embedding API." - "Constant-time SHA-256 `x-brain-key` header authentication, `failed_queries` knowledge-gap telemetry, and `mcp/vault_save_mcp.py` stdio push tool." when_to_use: - "Open Brain is a self-hosted Model Context Protocol (MCP) server backed by PostgreSQL 16 and pgvector that gives Claude Code, Cursor, Codex, and desktop AI clients shared hybrid semantic-and-keyword memory over your Obsidian Markdown vaults." - "Standard RAG setups over personal notes fail in three predictable ways: pure vector similarity misses exact identifiers and error codes, edited or moved notes leave duplicate zombie chunks in the index, and LLMs invent dates or owners when retrieved snippets lack stable chunk IDs. Open Brain solves all three with hybrid BM25 + pgvector + recency/RRF ranking, hash-based revision supersession, and mandatory `[chunk:ID]` citation headers." inputs_required: - "DB_HOST: PostgreSQL 16 + pgvector host address" - "DB_PORT: PostgreSQL port" - "DB_NAME: Database name initialized by compose/init.sql" - "DB_USER: Database user" - "DB_PASSWORD: Database password" - "OPENBRAIN_API_KEY: Shared secret verified via x-brain-key HTTP header" - "OPENBRAIN_FUSION_MODE: Ranking fusion strategy: weighted or rrf" - "EMBEDDING_API_BASE: Ollama or OpenAI-compatible /v1 embeddings base URL" - "EMBEDDING_MODEL: Embedding model name (1024-dim default matches compose/init.sql)" - "VAULT_PATH: Path to your local Markdown/Obsidian vault" quickstart: - "python3 bin/ob-demo.py ./sample-vault "hybrid search" --mode rrf # instant zero-DB local demo" - "cp compose/.env.example compose/.env && docker compose -f compose/docker-compose.yml up -d" - "ollama pull bge-m3 && python3 vendor/obsidian-vault-import/import-obsidian.py --vault main --vault-path ./sample-vault" --- # Open Brain — Personal Semantic Memory MCP Server — Machine-Readable Agent Guide Open Brain is a self-hosted Model Context Protocol (MCP) server backed by PostgreSQL 16 and pgvector that gives Claude Code, Cursor, Codex, and desktop AI clients shared hybrid semantic-and-keyword memory over your Obsidian Markdown vaults. Standard RAG setups over personal notes fail in three predictable ways: pure vector similarity misses exact identifiers and error codes, edited or moved notes leave duplicate zombie chunks in the index, and LLMs invent dates or owners when retrieved snippets lack stable chunk IDs. Open Brain solves all three with hybrid BM25 + pgvector + recency/RRF ranking, hash-based revision supersession, and mandatory `[chunk:ID]` citation headers. Key modules and entry points in this repository: - `bin/ob-demo.py`: Zero-database local demo CLI indexing `./sample-vault` and running Weighted/RRF cited queries - `sync/hybrid_ranker.py`: Reference Weighted-Hybrid and Reciprocal Rank Fusion (`k=60`) ranker + `[chunk:ID]` formatter - `compose/docker-compose.yml`: PostgreSQL 16 (`pgvector/pgvector:pg16`) + Deno MCP server container stack - `compose/init.sql`: Schema definition: `thoughts` table, `vector(1024)` index, generated `content_tsv` GIN index, fingerprint unique index, and `query_log` - `vendor/k8s-deployment/index.ts`: Deno HTTP MCP server implementing the 7 retrieval, capture, marking, and gap-detection tools - `vendor/obsidian-vault-import/import-obsidian.py`: Markdown chunker, secret scrubber, fingerprint pre-checker, revision superseder, and `--stale-orphaned` sweeper - `sync/capture_closure.py`: Deterministic operator workflow to promote a reviewed fleeting capture into a target vault page with receipt verification - `mcp/vault_save_mcp.py`: Lightweight Python stdio MCP tool (`save_to_vault`) for Claude Desktop / CLI note creation - `tests/`: 104-test suite covering search contracts, secret redaction, revision supersession, orphan circuit breakers, RRF ranking, and capture closure Every organization-specific value enters through `.env` (copied from `.env.example`) or external adapter files. No source edit is needed to change organization names, endpoints, database URLs, webhook secrets, or thresholds. When a human asks an AI coding agent to deploy or adapt `open-brain-public` into their stack: 1. Run `python3 bin/ob-demo.py ./sample-vault` right after cloning to verify chunking, secret scrubbing, and cited retrieval locally. 2. Copy `.env.example` to `.env` and `compose/.env.example` to `compose/.env`, setting a strong `DB_PASSWORD` and `OPENBRAIN_API_KEY`. 3. If using a 1536-dim cloud embedding model instead of local 1024-dim `bge-m3`, update `EMBEDDING_DIMS` in `.env` and `vector(1024)` in `compose/init.sql` before first boot. 4. Point `VAULT_PATH` at your Obsidian vault directory and schedule `import-obsidian.py` every 15-30 minutes via cron, systemd timer, or launchd. 5. Register `http://127.0.0.1:8080/mcp` with header `x-brain-key: ` in Claude Code (`~/.claude.json`), Cursor, or Codex. - Product Requirements: `docs/PRD.md` - Working-Backwards PR-FAQ: `docs/PR-FAQ.md` - High-Level Architecture: `docs/HLD.md` - Low-Level Interfaces & Runbook: `docs/LLD.md` - Coding Agent Rules: `AGENTS.md` --- ## File: `.env.example` — Environment Contract (.env.example) ```ini # open-brain-public — Unified Environment Contract # Copy to .env (and compose/.env for Docker Compose) before starting. # PostgreSQL + pgvector connection DB_HOST=127.0.0.1 DB_PORT=5432 DB_NAME=openbrain DB_USER=openbrain DB_PASSWORD=change-me-local-dev-password # MCP HTTP Server Authentication (timing-safe x-brain-key header) MCP_PORT=8080 OPENBRAIN_API_KEY=generate-a-32-byte-random-hex-token # Fusion Mode: weighted (default: 0.55 sem + 0.20 bm25 + 0.15 recency + 0.20 canonical) or rrf (Reciprocal Rank Fusion k=60) OPENBRAIN_FUSION_MODE=weighted # Local or OpenAI-compatible Embedding & Distillation Endpoint (defaults to local Ollama) EMBEDDING_API_BASE=http://127.0.0.1:11434/v1 EMBEDDING_API_KEY=ollama EMBEDDING_MODEL=bge-m3 EMBEDDING_DIMS=1024 CHAT_API_BASE=http://127.0.0.1:11434/v1 CHAT_API_KEY=ollama CHAT_MODEL=llama3.2:3b # Obsidian Vault Roots (colon-separated for orphan sweeps and sync) VAULT_PATH=./sample-vault OPENBRAIN_VAULT_ROOTS=./sample-vault # Open Brain -- Docker Compose env template # Copy to .env (which is gitignored) and fill in the CHANGE-ME values. # Never commit the real .env. # ----------------------------------------------------------------------------- # PostgreSQL # ----------------------------------------------------------------------------- POSTGRES_USER=postgres POSTGRES_DB=openbrain POSTGRES_PASSWORD=CHANGE-ME-postgres-password # ----------------------------------------------------------------------------- # MCP server auth # ----------------------------------------------------------------------------- # Every MCP client (Claude Desktop Mac/iOS, iOS Shortcut, any future client) # sends this in the x-brain-key header. Generate with: # openssl rand -hex 32 MCP_ACCESS_KEY=CHANGE-ME-random-64-char-hex # ----------------------------------------------------------------------------- # Embedding (VPS-local Ollama container -- do not change to cloud) # ----------------------------------------------------------------------------- # Post-2026-06-07 SPOF-kill: embedding runs in the `openbrain-embed` container # next to Postgres (it was on the Mac mini via Tailscale 2026-05-07..06-07). # Reason for self-host: KnowledgeGarden vault has medical / finance / family content. # No OpenRouter / OpenAI fallback -- an embed failure must abort the insert, # never silently egress. This is the whole point of self-host. EMBEDDING_API_BASE=http://openbrain-embed:11434/v1 EMBEDDING_API_KEY=not-needed EMBEDDING_MODEL=bge-m3 # ----------------------------------------------------------------------------- # Chat cascade: primary -> fallback1 -> fallback2 (metadata extraction) # ----------------------------------------------------------------------------- # These are what docker-compose.yml actually consumes (the old single # CHAT_API_BASE/KEY/MODEL trio is dead -- removed 2026-06-10, spec 001 T-003). # Tiers may be left empty; the server cascades past unconfigured tiers. CHAT_PRIMARY_API_BASE=http://openbrain-embed:11434/v1 CHAT_PRIMARY_API_KEY=not-needed CHAT_PRIMARY_MODEL=CHANGE-ME-primary-model CHAT_FALLBACK1_API_BASE= CHAT_FALLBACK1_API_KEY= CHAT_FALLBACK1_MODEL= CHAT_FALLBACK2_API_BASE= CHAT_FALLBACK2_API_KEY= CHAT_FALLBACK2_MODEL= # ----------------------------------------------------------------------------- # Advertised port (the MCP server binds here; nginx-proxy fronts it) # ----------------------------------------------------------------------------- PORT=8000 ``` --- ## File: `AGENTS.md` — AGENTS.md # AGENTS.md — Open Brain — Personal Semantic Memory MCP Server Read this file first before modifying `open-brain-public`. ## Purpose Open Brain is a self-hosted Model Context Protocol (MCP) server backed by PostgreSQL 16 and pgvector that gives Claude Code, Cursor, Codex, and desktop AI clients shared hybrid semantic-and-keyword memory over your Obsidian Markdown vaults. ## Commands ```bash python3 bin/ob-demo.py ./sample-vault "hybrid search" --mode rrf # instant zero-DB local demo cp compose/.env.example compose/.env && docker compose -f compose/docker-compose.yml up -d ollama pull bge-m3 && python3 vendor/obsidian-vault-import/import-obsidian.py --vault main --vault-path ./sample-vault ``` ## Module Map - `bin/ob-demo.py`: Zero-database local demo CLI indexing `./sample-vault` and running Weighted/RRF cited queries - `sync/hybrid_ranker.py`: Reference Weighted-Hybrid and Reciprocal Rank Fusion (`k=60`) ranker + `[chunk:ID]` formatter - `compose/docker-compose.yml`: PostgreSQL 16 (`pgvector/pgvector:pg16`) + Deno MCP server container stack - `compose/init.sql`: Schema definition: `thoughts` table, `vector(1024)` index, generated `content_tsv` GIN index, fingerprint unique index, and `query_log` - `vendor/k8s-deployment/index.ts`: Deno HTTP MCP server implementing the 7 retrieval, capture, marking, and gap-detection tools - `vendor/obsidian-vault-import/import-obsidian.py`: Markdown chunker, secret scrubber, fingerprint pre-checker, revision superseder, and `--stale-orphaned` sweeper - `sync/capture_closure.py`: Deterministic operator workflow to promote a reviewed fleeting capture into a target vault page with receipt verification - `mcp/vault_save_mcp.py`: Lightweight Python stdio MCP tool (`save_to_vault`) for Claude Desktop / CLI note creation - `tests/`: 104-test suite covering search contracts, secret redaction, revision supersession, orphan circuit breakers, RRF ranking, and capture closure ## Invariants 1. Keep all organization names, credentials, domains, and thresholds in `.env` or external config files. Never hardcode company names, host IPs, or secrets in source files. 2. Deterministic business logic belongs in code and lookup tables, not inside LLM prompts. 3. Update `docs/HLD.md`, `docs/LLD.md`, and `.env.example` in the same commit whenever an interface or environment variable changes. 4. Run the repository smoke check and secret scan before opening a pull request. --- ## File: `docs/PRD.md` — Product Requirements Document (docs/PRD.md) # Product Requirements Document — Open Brain — Personal Semantic Memory MCP Server Open Brain is a self-hosted Model Context Protocol (MCP) server backed by PostgreSQL 16 and pgvector that gives Claude Code, Cursor, Codex, and desktop AI clients shared hybrid semantic-and-keyword memory over your Obsidian Markdown vaults. ## 1. Problem Standard RAG setups over personal notes fail in three predictable ways: pure vector similarity misses exact identifiers and error codes, edited or moved notes leave duplicate zombie chunks in the index, and LLMs invent dates or owners when retrieved snippets lack stable chunk IDs. Open Brain solves all three with hybrid BM25 + pgvector + recency/RRF ranking, hash-based revision supersession, and mandatory `[chunk:ID]` citation headers. ## 2. Users and Jobs-to-be-Done | Persona | Job-to-be-Done | |---|---| | AI-Native Operator / Engineer | Give every CLI and desktop AI session instant, cited recall across thousands of Markdown notes without sending private vaults to third-party SaaS indexes. | | PKM / Obsidian Maintainer | Keep Markdown files as the single editable source of truth while automatically staling moved or rewritten note chunks. | | Autonomous Agent / Bot | Query scoped project memory (`vault`, `folder`, `after`) and log zero-hit searches via `failed_queries` without write access to authored notes. | ## 3. Core Capabilities - Hybrid retrieval (`search_chunks`, `search_summaries`) supporting both calibrated weighted scoring (0.55 cosine + 0.20 BM25 + 0.15 recency + 0.20 canonical) and Reciprocal Rank Fusion (`RRF k=60`). - Instant zero-database CLI demo (`python3 bin/ob-demo.py ./sample-vault`) to test chunking, secret scrubbing, and cited retrieval in under one second. - Citation-enforced payloads: every result header carries `[chunk:]` plus similarity, keyword score, and age metadata. - One-way Obsidian importer (`import-obsidian.py`) with pre-embedding secret redaction, SHA-256 fingerprint short-circuiting, revision supersession, and 50% mount-guard orphan circuit breakers. - Zero-egress local embeddings by default via Ollama `bge-m3` (1024 dimensions), with `.env` overrides for any OpenAI-compatible embedding API. - Constant-time SHA-256 `x-brain-key` header authentication, `failed_queries` knowledge-gap telemetry, and `mcp/vault_save_mcp.py` stdio push tool. ## 4. Configurable Inputs Adopters configure the system for their own organization without editing core application logic: | Variable | Default / Example | Purpose | |---|---|---| | `DB_HOST` | `127.0.0.1` | PostgreSQL 16 + pgvector host address | | `DB_PORT` | `5432` | PostgreSQL port | | `DB_NAME` | `openbrain` | Database name initialized by compose/init.sql | | `DB_USER` | `openbrain` | Database user | | `DB_PASSWORD` | `change-me-local-dev-password` | Database password | | `OPENBRAIN_API_KEY` | `generate-a-32-byte-random-hex-token` | Shared secret verified via x-brain-key HTTP header | | `OPENBRAIN_FUSION_MODE` | `weighted` | Ranking fusion strategy: weighted or rrf | | `EMBEDDING_API_BASE` | `http://127.0.0.1:11434/v1` | Ollama or OpenAI-compatible /v1 embeddings base URL | | `EMBEDDING_MODEL` | `bge-m3` | Embedding model name (1024-dim default matches compose/init.sql) | | `VAULT_PATH` | `./sample-vault` | Path to your local Markdown/Obsidian vault | ## 5. Phasing and Stability Exit Criteria 1. **Phase 1 (Local Synthetic Run):** Clone the repository, copy `.env.example` to `.env`, and run the quickstart commands against synthetic seed data. Exit criterion: smoke checks pass with zero external credentials. 2. **Phase 2 (Read-Only Shadow Wiring):** Connect read-only credentials or webhook listeners in shadow/dry-run mode. Exit criterion: 100 consecutive events or queries reconcile cleanly against source records. 3. **Phase 3 (Production Cutover):** Enable live writes, alerts, or routing behind bounded retry and idempotency guards. ## 6. Non-Goals - Shipping organization-specific business rules hardcoded in application source. - Storing credentials, personal customer records, or tenant URLs inside version control. - Replacing deterministic validation or arithmetic with unconstrained model prompts. --- ## File: `docs/PR-FAQ.md` — Working-Backwards PR-FAQ (docs/PR-FAQ.md) # Working-Backwards PR-FAQ — Open Brain — Personal Semantic Memory MCP Server **Release Summary:** `open-brain-public` gives engineering and operations teams a self-hosted, open-source implementation of Open Brain — Personal Semantic Memory MCP Server that configures via `.env` and runs on standard infrastructure in minutes. ## Press Release Operations and engineering teams often rebuild the same internal workflows behind closed doors or pay per-seat SaaS markups for rigid tools that cannot match their field reality. `open-brain-public` open-sources a battle-tested implementation of Open Brain — Personal Semantic Memory MCP Server, stripped of all single-company assumptions and packaged with clear adapter boundaries, synthetic demo data, and machine-readable agent documentation. Any team can fork `open-brain-public`, supply their own `.env` inputs and taxonomy config, and deploy locally or in production with Docker, Python, or Node. AI coding assistants such as Claude Code, Codex, and Cursor can read `AI-README.md` and `llms.txt` to wire custom ERP, CRM, or warehouse adapters in a single session. ## External Adopter FAQ **Q1: How long does it take to run locally after cloning?** Under five minutes. Copy `.env.example` to `.env` and run the quickstart commands in `README.md`. Synthetic fixtures let you inspect the workflow before connecting live credentials. **Q2: Do I need to rewrite source files to use my own company name, channels, or rules?** No. Organization names, endpoints, thresholds, and credentials sit in `.env` and declarative config files. External system specifics live behind narrow adapter modules documented in `docs/LLD.md`. **Q3: What license governs this repository?** MIT License. You can fork, modify, self-host, and use it commercially without restriction. ## Internal Engineering & Security FAQ **Q4: How do we prevent tenant or employer data from ever entering a public fork?** The repository starts from a clean git history, excludes raw exports and binary dumps, validates every commit through `gitleaks`, and ships only synthetic fixtures. **Q5: What happens when an upstream API or model provider is slow or unavailable?** Inbound webhooks persist raw payloads before processing, outbound writes carry idempotency keys with bounded exponential backoff, and model-backed paths fail open to deterministic rules or explicit human queues. --- ## File: `docs/HLD.md` — High-Level Design (docs/HLD.md) # High-Level Design (HLD) — Open Brain — Personal Semantic Memory MCP Server Open Brain is a self-hosted Model Context Protocol (MCP) server backed by PostgreSQL 16 and pgvector that gives Claude Code, Cursor, Codex, and desktop AI clients shared hybrid semantic-and-keyword memory over your Obsidian Markdown vaults. ## 1. System Topology ```mermaid flowchart LR Vault["Obsidian Vault (.md)"] -->|"one-way sync + secret scrub"| Importer["import-obsidian.py"] Importer -->|"embed via bge-m3"| Ollama["Ollama / OpenAI-Compatible API"] Importer -->|"upsert + supersede stale"| PG[("PostgreSQL 16 + pgvector + GIN tsvector")] Capture["Mobile / CLI capture_thought"] --> MCP["Deno MCP Server (x-brain-key)"] MCP <-->|"Weighted Hybrid / RRF + query_log"| PG Agents["Claude Code · Cursor · Codex"] <-->|"HTTPS / HTTP MCP"| MCP Agents -->|"stdio push"| SaveMCP["mcp/vault_save_mcp.py"] SaveMCP -->|"append inbox .md"| Vault ``` ## 2. Architectural Decisions and Rejected Alternatives | Decision | Why It Holds | Rejected Alternative | |---|---|---| | Obsidian -> Postgres is strictly one-way | Prevents split-brain edits between vector rows and Markdown files; Postgres index is always rebuildable from disk. | Two-way sync mutating Markdown from DB triggers | | Hybrid SQL + RRF fusion in Postgres | Catches exact acronyms, ticket IDs, and recent notes that pure cosine similarity ranks poorly, with zero external reranker service. | Separate Pinecone + Elasticsearch dual stack | | Stale flag (`metadata.stale='true'`) instead of hard DELETE on edit/move | Preserves historical provenance for `include_stale=true` queries and prevents accidental mass deletion if a vault is unmounted (50% orphan circuit breaker). | Immediate row deletion on missing file | | Header-only `x-brain-key` with SHA-256 constant-time compare | Eliminates reverse-proxy access-log token leaks from `?key=` URL params and prevents timing side channels. | Query-string API token check | ## 3. Data Flow and Failure Boundaries 1. **Configuration Boundary:** Startup validates `.env` variables and declarative config schemas before accepting traffic or running scheduled jobs. 2. **Adapter Boundary:** External services (databases, chat channels, HRMS, warehouses, or LLM providers) sit behind explicit adapter modules so failures stay isolated and testable with local mocks. 3. **Observability and Audit:** State transitions and job executions emit structured logs and deterministic status records rather than mutating state silently. ## 4. Scaling Notes - **1x to 10x load:** Single-node Docker Compose or process supervisor handles standard team workloads with indexed database queries and bounded worker concurrency. - **First bottleneck at 10x+:** High-frequency webhook or batch ingestion queues; mitigate by separating the stateless HTTP receiver from background worker processes sharing Redis or PostgreSQL locks. --- ## File: `docs/LLD.md` — Low-Level Design & Runbook (docs/LLD.md) # Low-Level Design (LLD) & Operations Runbook — Open Brain — Personal Semantic Memory MCP Server This document defines the module responsibilities, environment contract, and operational procedures for `open-brain-public`. ## 1. Module and File Inventory | Path | Responsibility | |---|---| | `bin/ob-demo.py` | Zero-database local demo CLI indexing `./sample-vault` and running Weighted/RRF cited queries | | `sync/hybrid_ranker.py` | Reference Weighted-Hybrid and Reciprocal Rank Fusion (`k=60`) ranker + `[chunk:ID]` formatter | | `compose/docker-compose.yml` | PostgreSQL 16 (`pgvector/pgvector:pg16`) + Deno MCP server container stack | | `compose/init.sql` | Schema definition: `thoughts` table, `vector(1024)` index, generated `content_tsv` GIN index, fingerprint unique index, and `query_log` | | `vendor/k8s-deployment/index.ts` | Deno HTTP MCP server implementing the 7 retrieval, capture, marking, and gap-detection tools | | `vendor/obsidian-vault-import/import-obsidian.py` | Markdown chunker, secret scrubber, fingerprint pre-checker, revision superseder, and `--stale-orphaned` sweeper | | `sync/capture_closure.py` | Deterministic operator workflow to promote a reviewed fleeting capture into a target vault page with receipt verification | | `mcp/vault_save_mcp.py` | Lightweight Python stdio MCP tool (`save_to_vault`) for Claude Desktop / CLI note creation | | `tests/` | 104-test suite covering search contracts, secret redaction, revision supersession, orphan circuit breakers, RRF ranking, and capture closure | ## 2. Environment Variable Contract | Variable | Default / Example | Required | Description | |---|---|---|---| | `DB_HOST` | `127.0.0.1` | Yes | PostgreSQL 16 + pgvector host address | | `DB_PORT` | `5432` | Yes | PostgreSQL port | | `DB_NAME` | `openbrain` | Yes | Database name initialized by compose/init.sql | | `DB_USER` | `openbrain` | Yes | Database user | | `DB_PASSWORD` | `change-me-local-dev-password` | Yes | Database password | | `OPENBRAIN_API_KEY` | `generate-a-32-byte-random-hex-token` | Yes | Shared secret verified via x-brain-key HTTP header | | `OPENBRAIN_FUSION_MODE` | `weighted` | Yes | Ranking fusion strategy: weighted or rrf | | `EMBEDDING_API_BASE` | `http://127.0.0.1:11434/v1` | Yes | Ollama or OpenAI-compatible /v1 embeddings base URL | | `EMBEDDING_MODEL` | `bge-m3` | Yes | Embedding model name (1024-dim default matches compose/init.sql) | | `VAULT_PATH` | `./sample-vault` | Yes | Path to your local Markdown/Obsidian vault | ## 3. Extension Recipe 1. Run `python3 bin/ob-demo.py ./sample-vault` right after cloning to verify chunking, secret scrubbing, and cited retrieval locally. 2. Copy `.env.example` to `.env` and `compose/.env.example` to `compose/.env`, setting a strong `DB_PASSWORD` and `OPENBRAIN_API_KEY`. 3. If using a 1536-dim cloud embedding model instead of local 1024-dim `bge-m3`, update `EMBEDDING_DIMS` in `.env` and `vector(1024)` in `compose/init.sql` before first boot. 4. Point `VAULT_PATH` at your Obsidian vault directory and schedule `import-obsidian.py` every 15-30 minutes via cron, systemd timer, or launchd. 5. Register `http://127.0.0.1:8080/mcp` with header `x-brain-key: ` in Claude Code (`~/.claude.json`), Cursor, or Codex. ## 4. Operations Runbook ### 1. Run zero-DB local verification demo ```bash python3 bin/ob-demo.py ./sample-vault "hybrid search" --mode rrf ``` ### 2. Start or restart the database and MCP stack ```bash docker compose -f compose/docker-compose.yml up -d --build docker compose -f compose/docker-compose.yml ps ``` ### 3. Run incremental vault import and safe orphan dry-run ```bash python3 vendor/obsidian-vault-import/import-obsidian.py --vault primary --vault-path "$VAULT_PATH" python3 vendor/obsidian-vault-import/import-obsidian.py --vault primary --vault-path "$VAULT_PATH" --stale-orphaned ``` ### 4. Repair any rows missing embeddings after an interrupted run ```bash python3 vendor/obsidian-vault-import/import-obsidian.py --repair-missing-embeddings ``` ### 5. Backup PostgreSQL database & rotate API key ```bash bash sync/backup-pg.sh openssl rand -hex 32 # update OPENBRAIN_API_KEY in compose/.env and restart openbrain-mcp ``` --- ## File: `docs/RESEARCH-2026.md` — 2026 Research & Landscape Notes (docs/RESEARCH-2026.md) # 2026 MCP Memory Ecosystem Research & Architecture Notes — Open Brain Open Brain gives AI coding agents and desktop assistants persistent, cited recall over local Markdown vaults using PostgreSQL 16, `pgvector`, and native full-text search. ## 1. 2026 MCP Memory Landscape Comparison Four architectures dominate open-source MCP memory servers in 2026: | System | Storage Substrate | Retrieval Strategy | Temporal Fact Evolution | Tradeoff vs. Open Brain | |---|---|---|---|---| | **Open Brain (This Repo)** | Local Obsidian Markdown (authoritative) + PostgreSQL 16 (`pgvector` + `tsvector`) | Weighted Hybrid (`0.55 sem + 0.20 BM25 + 0.15 recency + 0.20 canonical`) and Reciprocal Rank Fusion (`RRF k=60`) | Automatic `note_hash` revision staling (`stale=true`), `mark_chunk` tool, and 50% orphan circuit breaker | Requires one Postgres container for full multi-host HTTP MCP; includes `bin/ob-demo.py` for zero-DB local runs. | | **Basic Memory** | Local Markdown files via `stdio` | Wikilink traversal + local text search | Manual edits and git history | Zero DB setup, but AGPL-3.0 licensed and lacks hybrid vector+BM25 ranking or cross-host HTTP MCP. | | **Mem0** | Qdrant / Chroma / Managed Cloud | LLM fact distillation + hybrid search | Appends/updates extracted facts | Strong conversational fact extraction, but detached from human-edited Obsidian vaults. | | **Graphiti (Zep)** | Neo4j / FalkorDB temporal graph | Bi-temporal graph edge traversal | Explicit edge validity windows | Strongest entity-relationship timeline modeling, at the cost of operating a graph database. | ## 2. Upgrades Applied from 2026 Research 1. **Dual Fusion Modes (`Weighted` + `RRF`):** Added `sync/hybrid_ranker.py` supporting both calibrated linear combination and parameter-free Reciprocal Rank Fusion (`k=60`) when combining dense cosine rankings with sparse BM25 rankings. 2. **Zero-Database Instant Evaluation (`bin/ob-demo.py`):** New adopters can run `python3 bin/ob-demo.py ./sample-vault "hybrid search"` immediately after cloning — exercising secret redaction, SHA-256 chunk fingerprinting, stale/index exclusion, and `[chunk:ID]` citation formatting before spinning up Docker. 3. **Citation-First Anti-Hallucination Framing:** Retrieval payloads expose `chunk_id`, similarity score, keyword score, and age in every header while naming items `chunks` rather than `thoughts` so consuming models treat results as grounded evidence rather than unverified opinion.