Skip to main content
Glama
Second Brain Engine

Second Brain Engine

by npcmaul

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 Python >=3.12 Storage: SQLite FTS5 Writing Standard: ASD-STE100

Principles · Architecture · Workflow · Benchmarks · Quickstart · Documentation · References

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 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.


Related MCP server: exomem

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.


3. System Architecture and Trust Boundaries

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

Temporal & Recency Retrieval Service

Filters superseded/archived by default (include_superseded=False) and applies hyperbolic recency decay

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

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

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

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

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


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

Detailed stage-by-stage procedures and troubleshooting live in 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

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

  • 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

# 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

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

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: Trust zones, bi-temporal SQLite FTS5 schema, ranking math, component contracts, and security invariants.

  3. Second Brain End-to-End Workflow: Vault contract, S0-S5 lifecycle, connector idempotency, 5-class golden eval methodology, and troubleshooting.

  4. Upstream System Architecture: Core package layout and module dependency boundaries.

  5. Vault Setup & Indexing Guide: Vault configuration and parser internals.

  6. Retrieval Guide & Context Packs Guide: Query filters, ranking, and strict/soft token budgets.

  7. Write Tools Guide & Tool Reference: All 9 MCP tool contracts, expected_hash locking, and write_audit.

  8. Error Codes, Python API, & Release Checklist: Structured errors, public API boundaries, and release process.


8. Governance, Security, and Licensing


9. References and Upstream Provenance

Source

Author / Organization

What This Repository Adopted

Provenance

License

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

Wes McKinney / Kenn (kenn-io)

Read-only local session telemetry source (~/.agentsview/sessions.db) consumed by sync_connectors.py

INTEGRATED

MIT

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

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.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    Related MCP Connectors

    Related MCP Servers

    • F
      license
      Not graded
      quality
      A
      maintenance
      Durable memory with sources, proof, history, and review for MCP-capable agents. It turns a Markdown/Obsidian vault into a local knowledge substrate, enabling agents to store, search, and retrieve governed knowledge.
      2,221 PyPI
      9
      -
    • A
      license
      A
      quality
      C
      maintenance
      Enables AI agents to access a local-first personal context and memory layer through MCP tools for bootstrapping user context, semantically searching Markdown vault knowledge, reading files, listing topics, and adding controlled memories. It provides deterministic context retrieval, provenance-cited vector search, and secure vault operations while keeping data local and model-independent.
      6
      MIT
    • A
      license
      Not graded
      quality
      B
      maintenance
      A local MCP server that gives coding agents shared long-term memory stored as plain Markdown in your Obsidian vault, enabling hybrid recall of past project context, verified write-back of confirmed results with receipts, and automatic capture of conversations plus optional daily summaries. It runs entirely offline on CPU with no cloud calls or telemetry.
      43 PyPI
      1
      MIT