Skip to main content
Glama
Second Brain Engine

Second Brain Engine

by npcmaul
README.md
<div align="center">

<img src="docs/assets/hero-memory-highway.svg" alt="Memory highway: read-only sources flow through scrubbing connectors into the private Obsidian vault, served by the guarded FTS5 engine to the local agent" width="100%">

# Second Brain Engine

**Bi-temporal Obsidian Markdown MCP memory engine - guarded SQLite FTS5 retrieval, bilingual YAML indexing, read-only connectors, deterministic vault linting, and 5-class golden evaluation.**

[![License: Apache-2.0](https://img.shields.io/badge/License-Apache--2.0-blue.svg)](LICENSE)
[![Python >=3.12](https://img.shields.io/badge/Python-%3E%3D3.12-3776AB.svg)](pyproject.toml)
[![Storage: SQLite FTS5](https://img.shields.io/badge/Index-SQLite%20FTS5-003B57.svg)](ARCHITECTURE.md)
[![Writing Standard: ASD-STE100](https://img.shields.io/badge/Docs-ASD--STE100-0A66C2.svg)](ARCHITECTURE.md)

[Principles](#2-core-engineering-principles) · [Architecture](#3-system-architecture-and-trust-boundaries) · [Workflow](#4-end-to-end-operational-lifecycle-s0-s5) · [Benchmarks](#5-empirical-validation-summary) · [Quickstart](#6-quickstart-and-daily-operations) · [Documentation](#7-engineering-documentation-reading-order) · [References](#9-references-and-upstream-provenance)

</div>

This repository implements a local, zero-billing memory and decision engine for AI coding agents working over a decoupled Obsidian Markdown vault.
It is an Apache-2.0 fork and extension of [COvert96/obsidian-memory-mcp](https://github.com/COvert96/obsidian-memory-mcp) designed to run cleanly on constrained single-workstation Linux hardware (`15 GiB` RAM ceiling, `0` external API billing, `0` required embedding model downloads).

---

## 1. System Purpose and Scope

### 1.1 Purpose

The engine gives local CLI agents (such as Antigravity CLI `agy`, with optional opt-in support for other MCP clients) deterministic, sub-millisecond access to curated project decisions, architecture specs, and engineering atoms across multiple domains (`swe`, `agent`, `ds`).
It keeps all durable knowledge as plain, human-editable Markdown files inside a separate private vault while treating SQLite FTS5 and structural graphs strictly as disposable derived caches.

### 1.2 Engineering Problems Addressed

1. **Session Amnesia and Repeated Context Loading:** Agents start new sessions blind or burn thousands of tokens reading raw folders. The engine serves token-budgeted context packs and ranked FTS5 snippets (`~73x` payload reduction vs full vault reads).
2. **Stale Decision Pollution:** Standard keyword search surfaces outdated architecture notes alongside active ones. Migration `003_bitemporal_metadata` filters `status: superseded` and `archived` notes out of default retrieval while preserving full history for audit (`include_superseded=True`).
3. **Cross-Language Lexical Blind Spots Without Heavy Vectors:** Pure body-only FTS5 misses bilingual Indonesian/English queries, while heavy local vector stacks exhaust laptop RAM/VRAM. The parser indexes structured YAML fields (`summary_id`, `summary_en`, `search_queries`, `aliases`) at BM25 weight `6.0`.
4. **Prompt Injection and Secret Leakage From Automated Ingestion:** Copying raw logs or untrusted inbox files directly into agent prompts risks secret exposure and instruction hijacking. `00-inbox/**` is read-denied by guardrails, `sync_connectors.py` scrubs credentials before writing, and `agentsview` ingestion filters `secret_leak_count = 0`.
5. **Unmeasured Retrieval Quality:** Most personal knowledge setups rely on anecdote. `scripts/run_golden_eval.py` enforces deterministic launch-blocking thresholds across five query classes (`exact-id`, `paraphrase`, `multi-hop`, `superseded`, `abstention`).

### 1.3 Scope and System Boundaries

- **Inside System Boundary:** Public MCP server package (`src/obsidian_memory_mcp/`), Alembic schema migrations (`001` through `003`), read-only incremental connectors (`scripts/sync_connectors.py`), deterministic vault linter (`scripts/vault_lint.py`), 5-class golden eval harness (`scripts/run_golden_eval.py`), local MCP registrar (`scripts/connect_local_mcp.py`), and release quality gates.
- **Outside System Boundary:** Private Obsidian vault contents (kept in a separate local/private directory), workstation dotfiles / agent development environment, calendars and schedulers, cloud vector databases, and paid inference APIs.

---

## 2. Core Engineering Principles

1. **Markdown Single Source of Truth:** Plain Markdown + YAML inside a decoupled private vault owns all durable state; `.mcp/` SQLite indexes and `graphify-out/` graphs are disposable caches rebuildable in `< 2 s`.
2. **Bi-Temporal Supersession Over Deletion:** Outdated decisions are marked `status: superseded` with `superseded_by: "[[replacement]]"` instead of deleted, keeping default retrieval clean and audit trails intact.
3. **Zero-Billing, Lightweight Local Footprint:** Retrieval uses deterministic SQLite FTS5 (`< 1 ms` median, `~82 MB` peak RSS) with `$0` API spend and `0` mandatory local model downloads.
4. **Read-Only In-Place Ingestion:** External sources (`~/Projects/`, `~/.agentsview/sessions.db`, `~/Zotero/zotero.sqlite`) are never moved or mutated; connectors open SQLite with `?mode=ro`, scrub secrets, and report status loudly in `40-ops/health.md`.
5. **Fail-Closed Guardrails and Optimistic Locking:** Deny rules override allow rules (`00-inbox/**` read-denied, `99-system/**` write-denied); updates require `expected_hash` and write every mutation to an append-only `write_audit` table.
6. **Evidence Before Claims:** Every release gate, lint check, secret scan, and 5-class benchmark runs deterministically and reports real failures honestly without hiding trade-offs.

<img src="docs/assets/design-principles.svg" alt="Six core principles orbiting the vault core: Markdown SSoT, supersession over deletion, zero-billing local footprint, read-only ingestion, fail-closed guardrails, evidence before claims" width="100%">

---

## 3. System Architecture and Trust Boundaries

<img src="docs/assets/system-architecture.svg" alt="System architecture and trust boundaries: read-only sources, public engine, private vault with denied zones and disposable caches, local MCP client" width="100%">

### Major Architectural Units

| Architectural Unit | Primary Responsibility | Canonical Reference |
|---|---|---|
| **Bi-Temporal Parser & FTS5 Indexer** | Extracts YAML `status`, `updated`, `summary_id`, `summary_en`, `search_queries`, `aliases` into `blocks_fts.metadata_text` (weight `6.0`) | [ARCHITECTURE.md](ARCHITECTURE.md#2-bi-temporal-indexing-and-retrieval-engine) |
| **Temporal & Recency Retrieval Service** | Filters `superseded`/`archived` by default (`include_superseded=False`) and applies hyperbolic recency decay | [docs/retrieval-guide.md](docs/retrieval-guide.md) |
| **Guarded FastMCP Server (9 Tools)** | Serves `read_note`, `read_section`, `search_notes`, `get_context_pack`, `list_context_packs`, `write_memory`, `update_memory`, `write_note`, `update_note` | [docs/tool-reference.md](docs/tool-reference.md) |
| **Read-Only Incremental Connectors (`sync_connectors.py`)** | Scans Git repos, clean `agentsview` sessions, and Zotero in-place with secret scrubbing, slug disambiguation, and `40-ops/health.md` reporting | [docs/SECOND-BRAIN-WORKFLOW.md](docs/SECOND-BRAIN-WORKFLOW.md#stage-s2-read-only-incremental-connector-sync) |
| **Deterministic Vault Linter (`vault_lint.py`)** | Enforces YAML schema, `superseded_by` links, zero broken wikilinks, zero stale refs to superseded notes, and line budgets (`10-me <= 100`, notes `<= 400`) | [ARCHITECTURE.md](ARCHITECTURE.md#3-component-and-script-interface-contracts) |
| **5-Class Golden Eval Harness (`run_golden_eval.py`)** | Measures Hit@K across `exact-id`, `paraphrase`, `multi-hop`, `superseded`, `abstention` plus latency, peak RSS, and token reduction | [docs/SECOND-BRAIN-WORKFLOW.md](docs/SECOND-BRAIN-WORKFLOW.md#4-five-class-golden-evaluation-methodology) |
| **Local MCP Registrar (`connect_local_mcp.py`)** | Wires local `memory-mcp-server.yaml` and registers `second-brain` in `agy` (`--with-codex` opt-in) without leaking paths into Git | [scripts/connect_local_mcp.py](scripts/connect_local_mcp.py) |

---

## 4. End-to-End Operational Lifecycle (`S0-S5`)

| Stage | Activity | Primary Tool / Command | Exit Gate |
|---|---|---|---|
| **S0 - Bootstrap** | Initialize private vault layout, validate `memory-mcp.yaml`, register local MCP | `mcp-memory config validate` + `scripts/connect_local_mcp.py` | Config valid; MCP reachable by client |
| **S1 - Qualify** | Formulate measurable targets per project (Wang Step 1 Memo + Health Scorecard Gates `A-H`) | Vault template `40-ops/templates/project-health-scorecard.md` | Explicit baseline, target, kill criterion |
| **S2 - Ingest** | Pull incremental updates from Git repos, `agentsview`, and Zotero in-place | `scripts/sync_connectors.py --vault <vault>` | Secrets scrubbed; 2x run = `0` writes; `40-ops/health.md` updated |
| **S3 - Index & Graph** | Rebuild incremental FTS5 index and optional zero-token structural graph | `mcp-memory index <vault>` + optional `graphify update .` | `0` indexing errors (`< 1 s`) |
| **S4 - Retrieve & Mutate** | Agent loads bounded context pack, searches active notes, writes atoms with `expected_hash` | MCP tools (`get_context_pack`, `search_notes`, `write_memory`, `update_memory`) | `0` stale overwrites; `write_audit` logged |
| **S5 - Verify & Commit** | Lint vault integrity, run 5-class golden eval, scan secrets, commit vault locally | `vault_lint.py` + `run_golden_eval.py` + `gitleaks` | `0` lint issues, eval `PASS`, `0` secret leaks |

<img src="docs/assets/lifecycle-s0-s5.svg" alt="End-to-end operational lifecycle S0 to S5: bootstrap, qualify, ingest, index, retrieve and mutate, verify and commit - every stage has an exit gate" width="100%">

Detailed stage-by-stage procedures and troubleshooting live in [docs/SECOND-BRAIN-WORKFLOW.md](docs/SECOND-BRAIN-WORKFLOW.md).

---

## 5. Empirical Validation Summary

### 5.1 Engine Quality Gates (`VERIFIED`)

| Gate | Command | Measured Result | Status |
|---|---|---|---|
| **Static Lint & Strict Types** | `uv run ruff check && uv run mypy --strict src` | `0` issues across `94` source files | **PASS** |
| **Architectural Boundaries** | `uv run lint-imports && uv run python scripts/radon_gate.py` | `6/6` import contracts kept; `0` CC grade `C+` / MI `< 20` | **PASS** |
| **Unit & Integration Suite** | `uv run pytest --cov=obsidian_memory_mcp --cov-fail-under=80 -q tests` | `367 passed` (`5.80 s`), `91.54%` line coverage | **PASS** |
| **Secret & Path Hygiene** | `gitleaks detect` + `rg "/home/<user>" src scripts alembic tests` | `0` leaks across full Git history (`77` commits); `0` personal path leaks | **PASS** |

<img src="docs/assets/quality-gates.svg" alt="Release quality gates: static lint and strict types, architectural boundaries, 367-test suite at 91.54 percent coverage, secret and path hygiene - all passing" width="100%">

### 5.2 Live 5-Class Golden Eval Reference Benchmark (`24` Queries, `VERIFIED`)

Measured on a live private Second Brain vault (`31` curated Markdown notes, `84` sections, `67` blocks; full index build `415 ms`, optional `graphify` build `145` nodes / `118` edges at `0` LLM tokens):

| Query Class | Measured Hit@5 / Pass | Launch-Blocking Threshold | Status |
|---|---|---|---|
| `exact-id` | `6 / 6` (`100.0%`) | `>= 90%` | **PASS** |
| `paraphrase` (bilingual ID/EN, non-verbatim) | `5 / 6` (`83.3%`) | `>= 70%` | **PASS** |
| `multi-hop` (all related notes in top-5) | `4 / 4` (`100.0%`) | `>= 70%` | **PASS** |
| `superseded` (suppressed by default + preserved in history) | `3 / 3` (`100.0%`) | `>= 85%` | **PASS** |
| `abstention` (`0` false positives on out-of-vault queries) | `5 / 5` (`100.0%`) | `>= 85%` | **PASS** |

<img src="docs/assets/golden-eval-scoreboard.svg" alt="Golden eval scoreboard: exact-id 100 percent, paraphrase 83.3 percent, multi-hop 100 percent, superseded 100 percent, abstention 100 percent, with launch-blocking thresholds and the single honest paraphrase miss" width="100%">

- **Latency:** median `0.637 ms`, p95 `0.866 ms`, max `1.201 ms`.
- **Memory:** peak RSS `81.86 MB` (`< 100 MB` target).
- **Token Payload Reduction:** `185.7` avg search payload tokens vs `13,615` curated vault tokens (**`73.32x`** reduction).

> **Honest Trade-Off Record:** The single `paraphrase` miss (`1 / 24`) occurred when querying an Indonesian word (`ditolak`) against a note containing only the English term (`Rejected`). Because SQLite FTS5 uses strict lexical `AND` without an embedding model, cross-language recall depends on populating concise bilingual `summary_id`, `summary_en`, and `search_queries` frontmatter on key notes.

> **Buy-vs-Build Rejection Record:** Before forking `COvert96/obsidian-memory-mcp`, heavier alternatives were audited and rejected for a `15 GiB` RAM / `4 GiB` VRAM workstation: Hindsight (`2.2-3.3 GB` idle RAM and `pg0` OOM issue `#1572`), Basic Memory (reported frontmatter rewrite hazard `#2125`), QMD full (`2.1 GB` mandatory model download), and SpencerBrain (`32 GB` RAM / `16 GB` VRAM target).

---

## 6. Quickstart and Daily Operations

### 6.1 Requirements

- Python `>= 3.12` and `uv`
- Linux or macOS (Windows paths also supported by `mcp-memory`)
- A separate local Obsidian Markdown vault directory
- Optional: `gitleaks` (secret scanning) and `graphify` (zero-token structural graph)

### 6.2 Initial Setup

```bash
# 1. Clone and install dependencies
git clone https://github.com/npcmaul/second-brain-engine.git
cd second-brain-engine
uv sync --group dev

# 2. Configure your separate private vault (copy config-example.yaml -> <vault>/memory-mcp.yaml)
uv run mcp-memory config validate ~/Projects/my-second-brain
uv run mcp-memory index --full --yes ~/Projects/my-second-brain

# 3. Register the vault locally (writes gitignored memory-mcp-server.yaml and wires agy MCP)
uv run python scripts/connect_local_mcp.py \
  --vault ~/Projects/my-second-brain \
  --project-name second-brain
```

### 6.3 Daily Wrap-Up Loop

```bash
cd ~/Projects/second-brain-engine
uv run python scripts/sync_connectors.py --vault ~/Projects/my-second-brain
uv run mcp-memory index ~/Projects/my-second-brain
uv run python scripts/vault_lint.py ~/Projects/my-second-brain

# Optional: run your vault golden benchmark and refresh structural graph
uv run python scripts/run_golden_eval.py \
  --vault ~/Projects/my-second-brain \
  --golden ~/Projects/my-second-brain/99-system/golden-eval.yaml
cd ~/Projects/my-second-brain && graphify update .
```

### 6.4 Release Verification Gates

```bash
uv run ruff check
uv run mypy --strict src
uv run lint-imports
uv run python scripts/radon_gate.py
uv run pytest --cov=obsidian_memory_mcp --cov-fail-under=80 -q tests
gitleaks detect --source . --no-git --no-banner
```

---

## 7. Engineering Documentation Reading Order

Read these documents in sequence for complete architectural and operational context:

1. **System Overview (This Document):** Purpose, principles, trust boundaries, benchmarks, and quickstart.
2. **[Architecture and Control Flow](ARCHITECTURE.md):** Trust zones, bi-temporal SQLite FTS5 schema, ranking math, component contracts, and security invariants.
3. **[Second Brain End-to-End Workflow](docs/SECOND-BRAIN-WORKFLOW.md):** Vault contract, `S0-S5` lifecycle, connector idempotency, 5-class golden eval methodology, and troubleshooting.
4. **[Upstream System Architecture](docs/system-architecture.md):** Core package layout and module dependency boundaries.
5. **[Vault Setup](docs/vault-setup.md) & [Indexing Guide](docs/indexing-guide.md):** Vault configuration and parser internals.
6. **[Retrieval Guide](docs/retrieval-guide.md) & [Context Packs Guide](docs/context-packs-guide.md):** Query filters, ranking, and strict/soft token budgets.
7. **[Write Tools Guide](docs/write-tools-guide.md) & [Tool Reference](docs/tool-reference.md):** All 9 MCP tool contracts, `expected_hash` locking, and `write_audit`.
8. **[Error Codes](docs/error-codes.md), [Python API](docs/python-api.md), & [Release Checklist](docs/release-checklist.md):** Structured errors, public API boundaries, and release process.

---

## 8. Governance, Security, and Licensing

- **Security Policy:** [SECURITY.md](SECURITY.md) - never commit private vault data, credentials, or `memory-mcp-server.yaml`.
- **Contribution Guidelines:** [CONTRIBUTING.md](CONTRIBUTING.md)
- **Changelog:** [CHANGELOG.md](CHANGELOG.md)
- **License:** [Apache License 2.0](LICENSE) (preserving upstream copyright and license terms).

---

## 9. References and Upstream Provenance

| Source | Author / Organization | What This Repository Adopted | Provenance | License |
|---|---|---|---|---|
| [COvert96/obsidian-memory-mcp](https://github.com/COvert96/obsidian-memory-mcp) | `COvert96` & contributors | Core FastMCP server, SQLite FTS5 index, token-budgeted context packs, guarded direct-write tools, `write_audit`, and 350+ test baseline | FORKED BASE | Apache-2.0 |
| `graphify` (`0.9.122`) | Graphify contributors | Optional zero-token structural graph layer (`graphify-out/graph.json`) for multi-hop Markdown neighborhood inspection | INTEGRATED | - |
| [kenn-io/agentsview](https://github.com/kenn-io/agentsview) | Wes McKinney / Kenn (`kenn-io`) | Read-only local session telemetry source (`~/.agentsview/sessions.db`) consumed by `sync_connectors.py` | INTEGRATED | MIT |
| [gitleaks/gitleaks](https://github.com/gitleaks/gitleaks) | Zachary Rice (`gitleaks`) | Pre-commit and repository secret-leak gate across engine and private vaults | INTEGRATED | MIT |
| Alexandr Wang 4-Step Framework & AI Project Health Scorecard v2 | Alexandr Wang / Dr. Andrey Holz | Project qualification workflow (One-Line Sanity Check, 1-page Memo, Mandatory Gates `A-H`, Harden thresholds) | METHODOLOGY | - |
| [ASD-STE100](https://www.asd-ste100.org/) | ASD | Controlled technical documentation clarity standard | ADAPTED | - |

The bi-temporal migration (`003_bitemporal_metadata`), bilingual YAML metadata indexer, hyperbolic recency + supersession retrieval defaults, `sync_connectors.py`, `vault_lint.py`, `run_golden_eval.py`, and `connect_local_mcp.py` were built in this repository on top of the Apache-2.0 upstream base.