Skip to main content
Glama
README.md
# AI Second Brain

A private, local-first context system for Claude. Markdown notes (Obsidian-style vault)
are chunked, embedded with a local Ollama model, and stored in PostgreSQL + pgvector.
Claude retrieves relevant context through MCP instead of you re-explaining in every chat.

This is a working, real-time system: one long-lived `BrainService` owns a pooled DB
connection, cached query embeddings, a debounced embedded watcher, and an SSE event
stream. Notes you change on disk are searchable within ~0.3s without a manual reindex.

## One-command setup

```powershell
.\setup.ps1    # Windows: checks prerequisites, generates .env, installs deps,
               #          starts pgvector, pulls the model, indexes notes, tests
.\start.ps1    # serve on 127.0.0.1:8012 with the live watcher
.\doctor.ps1   # health check
```

```bash
./setup.sh     # macOS / Linux
./start.sh
./doctor.sh
```

Setup is safe to re-run and never overwrites your key. See
[TESTER_GUIDE.md](TESTER_GUIDE.md) for a guided walkthrough.

## Architecture

```
markdown vault (Obsidian)
        |  watchdog, debounced 300ms, per-file
        v
   BrainService  <----- MCP stdio (Claude Desktop)
        |  |  \         <----- FastAPI HTTP :8012
        |  |   \               /search  /notes  /health  /events(SSE)
        |  |    \
        |  |     +-- query embedding LRU cache (256 keys, 5 min TTL)
        |  +-------- stat + content-hash gates (skip unchanged files)
        v
   Ollama (nomic-embed-text)
        v
   PostgreSQL + pgvector (HNSW cosine index, pooled connections)
```

## Efficiency design

| Concern | How it's handled |
|---|---|
| Change detection | `size` + `mtime` checked first — unchanged files are never even read |
| Same content, new timestamp | SHA-256 gate — metadata refreshed, **no re-embedding** |
| Changed file | Only that file is re-chunked, embedded in **one batch call**, replaced |
| Repeated queries | Embedding cached in an LRU (256 keys, 5-min TTL) — zero Ollama calls on hits |
| Concurrent requests | `ThreadedConnectionPool` — no new TCP connection per query |
| Cache invalidation | Query cache cleared automatically when any note is indexed/deleted |
| Full rescans | Only at startup; the watcher calls `index_path()` on the single changed file |
| Availability | Watcher runs in a daemon thread embedded in the service — no second process needed |

## Quick start

```bash
python -m pip install -r requirements.txt
docker compose up -d                       # pgvector on localhost:5435
ollama pull nomic-embed-text

python -m second_brain.cli init-db         # create schema, detect embedding dimension
python -m second_brain.cli index           # initial reconciliation
python -m second_brain.cli search "what is lead-radar?"
python -m second_brain.cli status          # watcher, counts, cache size, errors

# Real-time service (watcher starts automatically with the server)
python -m second_brain.cli serve           # HTTP API + SSE on 127.0.0.1:8012
python -m second_brain.cli watch           # watcher-only mode
python -m second_brain.cli mcp             # MCP stdio (also starts watcher)
```

Point `SB_VAULT` at your own vault. All processing stays local — no cloud API keys or
external embedding provider. The `LOCAL_AI_API_KEY` in `.env` is a random local token,
not a cloud credential.

## HTTP API

| Endpoint | Purpose |
|---|---|
| `GET /health` | Status, watcher state, note/chunk counts, cache size, last error |
| `GET /search?q=...&k=5` | Semantic search |
| `GET /notes` | Indexed note list |
| `POST /reindex` | Force full reconciliation |
| `GET /events` | Server-Sent Events — pushes an event the moment a note is indexed/deleted |

Example event:

```
data: {"version":3,"type":"index","path":"projects/new-note.md","status":"indexed","chunks":2}
```

## Claude Desktop configuration

```json
{
  "mcpServers": {
    "second-brain": {
      "command": "python",
      "args": ["-m", "second_brain.cli", "mcp"],
      "cwd": "C:\\path\\to\\your\\cloned\\ai-second-brain",
      "env": {
        "SB_VAULT": "C:\\path\\to\\your\\obsidian\\vault"
      }
    }
  }
}
```

Tools: `search_notes`, `list_notes`, `get_note`, `reindex`, `status`.

Note: if you run both the HTTP server and the MCP server at once, each starts its own
watcher. This is safe — the stat/content-hash gates make them idempotent, so only one
actually embeds a given change.

## Authentication

The service binds to `127.0.0.1`. For defence in depth, set `LOCAL_AI_API_KEY` to a
shared secret:

```bash
export LOCAL_AI_API_KEY="your-random-key"
```

With the key set, `/search`, `/notes`, `/reindex`, and `/events` require
`Authorization: Bearer <key>`. `/health` stays open for monitoring. The companion
Local LLM Stack reads the same variable and forwards it automatically.

Without the key, the API runs open (local-dev mode) — fine for a single machine,
not for anything reachable from another host.

## Tests

```bash
python -m pytest -q     # 18 tests, no DB/Ollama needed
```