conversation-rag
by batteryphil
README.md
# conversation-rag (`gbrain` + Cross-Conversation Hybrid RAG)
[](https://github.com/batteryphil/conversation-rag/actions/workflows/ci.yml)
[](LICENSE)
A **zero-VRAM, single-SQLite, zero-daemon** dual-tier persistent memory engine and stdio MCP server for AI coding agents (Antigravity, Claude Code, Cursor, or any MCP client).
No Docker, no Neo4j, no Postgres, no SurrealDB, no Ollama required — just **Python + 3 runtime packages** (`numpy`, `onnxruntime`, `tokenizers`) and one WAL SQLite database (`rag.sqlite`).
---
## Architecture
```mermaid
flowchart TB
A["Coding Agent (MCP stdio / CLI / Hooks)"] -->|"PreInvocation (<15 ms, stdlib SQLite)"| B["Above the Line: gbrain Living Memory"]
A -->|"Stop Hook (non-blocking incremental sync)"| C["Below the Line: Hybrid RAG Archive"]
A -->|"12 MCP Tools (read + write)"| D["conv_rag/mcp_server.py"]
subgraph SQLite["Single WAL SQLite DB (rag.sqlite — 0 MB GPU VRAM)"]
B["gbrain_entities + gbrain_facts (ONNX + FTS5)<br/>gbrain_links (multi-hop graph)<br/>gbrain_fact_history (append-only audit log)"]
C["conversations + chunks (turns, artifacts, checkpoints, scratch)<br/>FTS5 BM25 + CPU ONNX MiniLM + Reciprocal Rank Fusion"]
end
S["Write-Time Secret Guard (conv_rag/security.py)"] --> B
J["Git-Diffable JSONL Canon (export / validate / import)"] <--> B
D --> B
D --> C
D -.->|"Optional rag_ask synthesis"| L["Any OpenAI-Compatible Local/Remote LLM"]
U["Optional Read-Only Local Graph Explorer (conv-rag ui)"] --> SQLite
```
### Why Dual-Tier?
- **Above the Line (`gbrain`):** Current, conflict-free living truth per `(entity, key)` — decisions, verified benchmarks, repo paths, architectures, preferences, pitfalls — backed by:
- **Append-only temporal history (`gbrain_fact_history`):** Every update or soft-forget archives the prior value with `valid_from`/`valid_to` timestamps and reason. Nothing is silently overwritten.
- **Trust-tier ranking:** `user_stated` > `verified` > `agent_inferred`.
- **Write-time secret-leak guard (`conv_rag/security.py`):** Automatically blocks API keys, private keys, URL credentials, high-entropy opaque tokens, and optional `secret-deny.txt` literals before anything touches SQLite.
- **Multi-hop entity graph (`gbrain_links`):** Traverse 1–3 hop neighborhoods (`gbrain_neighbors` / `conv-rag neighbors`) directly in SQLite — no graph database server needed.
- **Git-diffable JSONL canon (`conv_rag/canon.py`):** Export, schema+secret validate, and idempotently import living memory as plain UTF-8 JSONL (`entities.jsonl`, `facts.jsonl`, `links.jsonl`).
- **Model-aware embedding fingerprints (`embedding_sha`):** Stores `sha256(model_id + "\n" + text)` so swapping ONNX embedders re-embeds only stale rows via `conv-rag reembed`.
- **Below the Line (Hybrid RAG):** Automatic incremental indexing of past agent sessions (turns, markdown artifacts, compaction checkpoints, scratch files) searched via CPU ONNX `all-MiniLM-L6-v2` + SQLite FTS5 BM25 + Reciprocal Rank Fusion (`1/(60+rank)`).
- **Strict Token-Budgeted `gbrain_context_pack`:** Packs Above-the-Line current truth **first** and Below-the-Line supporting excerpts **second** inside a configurable token cap (`~20 ms`, `0 MB` VRAM).
---
## Quickstart (30 seconds)
### 1. Install
```bash
git clone https://github.com/batteryphil/conversation-rag.git
cd conversation-rag
python3 -m venv .venv
source .venv/bin/activate
pip install -e ".[dev]"
```
### 2. Try the included demo knowledge graph (no transcripts or GPU required)
```bash
# Validate schema, entity references, and secret-leak gates
conv-rag validate examples/demo_canon
# Import the demo canon into your local SQLite DB
conv-rag import examples/demo_canon
# Inspect living entities, multi-hop neighbors, and context pack
conv-rag entity
conv-rag entity orbital-cache
conv-rag neighbors edge-gateway --depth 2
conv-rag pack "SQLite WAL checkpoint pitfall" --facts-only
# Optional: launch the read-only localhost graph explorer (never auto-opens a browser)
conv-rag ui --port 8321
```
### 3. Enable CPU ONNX Semantic Embeddings (optional, 0 MB VRAM)
FTS5 BM25 works out of the box with zero downloads. To enable hybrid semantic + BM25 search on CPU (`all-MiniLM-L6-v2`, ~90 MB ONNX):
```bash
pip install -e ".[onnx-export]"
python scripts/export_minilm_onnx.py --download
conv-rag reembed
```
Once exported, `torch` and `transformers` are never imported at runtime — the MCP server and hooks run strictly on `onnxruntime` CPU + `tokenizers` + `numpy`.
---
## 12 MCP Tools (Stdio JSON-RPC 2.0)
| Tool | Tier | Description |
|---|---|---|
| `gbrain_context_pack` | Above + Below | Compact, strict token-budgeted living truth + supporting RAG excerpts (`0 MB` VRAM) |
| `gbrain_remember` | Above | Record or supersede a living fact (write-time secret guard + automatic history archive) |
| `gbrain_forget` | Above | Soft-deprecate an outdated fact while keeping its Below-the-Line audit entry |
| `gbrain_entity` | Above | Inspect a compiled living entity card, links, and history (or list all entities) |
| `gbrain_link` | Above | Connect two entities with a directional relationship |
| `gbrain_neighbors` | Above | Multi-hop SQLite BFS graph traversal (`depth=1..3`, incoming + outgoing links) |
| `rag_search` | Below | CPU hybrid (ONNX semantic + FTS5 BM25 + RRF) search across indexed sessions |
| `rag_ask` | Above + Below | Grounded Q&A synthesized via any OpenAI-compatible LLM (`CONV_RAG_LLM_URL`) with excerpt fallback |
| `rag_conversation` | Below | Drill into a session's overview, step range, markdown artifact, or indexed chunks |
| `rag_list_conversations` | Below | Chronological catalog & filter across indexed sessions |
| `rag_sync` | Below | Lock-guarded incremental (or `--force` full) CPU re-index |
| `rag_stats` | System | Combined RAG + `gbrain` + ONNX + optional LLM health telemetry |
---
## Connecting to Your Coding Agent
### Generic MCP (`Claude Code`, `Cursor`, `Windsurf`, etc.)
Generate a ready-to-paste `mcpServers` block pointing at your virtualenv:
```bash
python scripts/install_plugin.py --print-mcp-json
```
Example:
```json
{
"mcpServers": {
"conversation-rag": {
"command": "/path/to/.venv/bin/python",
"args": ["-m", "conv_rag.mcp_server"],
"env": {
"HIP_VISIBLE_DEVICES": "",
"CUDA_VISIBLE_DEVICES": "",
"TOKENIZERS_PARALLELISM": "false",
"CONV_RAG_ONNX_THREADS": "8"
}
}
}
}
```
### Antigravity Plugin + Auto-Recall / Auto-Sync Hooks
Install the bundled portable plugin (includes `<15 ms` `PreInvocation` living-truth auto-recall and non-blocking `Stop` incremental sync):
```bash
python scripts/install_plugin.py
```
---
## Optional LLM Synthesis (`rag_ask`)
`rag_ask` works with **any** OpenAI-compatible `/v1/chat/completions` server (local or remote) using stdlib `urllib` only. If unreachable, it gracefully falls back to returning structured cited excerpts.
| Backend | `CONV_RAG_LLM_URL` | `CONV_RAG_LLM_MODEL` |
|---|---|---|
| **Ollama** | `http://127.0.0.1:11434` | `qwen2.5-coder:7b` (or any local tag) |
| **llama.cpp / vLLM / LM Studio** | `http://127.0.0.1:8000` | your served model ID |
| **PRIME-Quant** | `http://127.0.0.1:8088` | `prime-quant/inkling-2-mini` |
| **OpenAI-compatible cloud API** | `https://api.openai.com` | set `CONV_RAG_LLM_API_KEY` too |
---
## CLI Reference
```bash
# Living Memory (Above the Line)
conv-rag remember <entity> <key> "<content>" [--category decision] [--trust-tier verified]
conv-rag forget --entity <entity> --key <key> --reason "superseded"
conv-rag entity [name] [--no-history] [--json]
conv-rag link <source> <relationship> <target> [--note "..."]
conv-rag neighbors <entity> [--depth 2] [--json]
conv-rag pack "<query>" [--budget 600] [--facts-only]
conv-rag delta 2026-12-01
# Git-Diffable JSONL Canon & Maintenance
conv-rag export ./my-canon [--include-history]
conv-rag validate ./my-canon [--deny-file ~/.config/secret-deny.txt]
conv-rag import ./my-canon [--dry-run]
conv-rag reembed
# Cross-Conversation RAG (Below the Line)
conv-rag sync [--force] [--conversation-id <id>]
conv-rag search "<query>" [-k 8] [--mode hybrid|semantic|keyword]
conv-rag ask "<question>"
conv-rag list [-q "<filter>"]
conv-rag show <conversation_id> [--section overview|steps|artifact|chunks]
conv-rag stats
# Optional Read-Only Local Graph Explorer (127.0.0.1 only, never auto-opens browser)
conv-rag ui [--host 127.0.0.1] [--port 8321]
```
### Environment Variables
- `CONV_RAG_DATA_DIR` — directory for `rag.sqlite`, ONNX model, and `secret-deny.txt` (default: `~/.gemini/antigravity/plugin_data/conversation-rag`)
- `CONV_RAG_ROOTS` — `os.pathsep`-delimited list of conversation root directories to auto-index
- `CONV_RAG_EMBED_MODEL_ID` — model identifier hashed into `embedding_sha` (default: `sentence-transformers/all-MiniLM-L6-v2`)
- `CONV_RAG_ONNX_THREADS` — CPU threads for ONNXRuntime (default: `8`)
- `CONV_RAG_SECRET_GUARD` — set to `0` to disable write-time secret scanning (default: `1`)
- `CONV_RAG_SECRET_DENY_FILE` — path to optional line-delimited literal secret deny-list (never commit!)
- `CONV_RAG_LLM_URL` / `CONV_RAG_LLM_MODEL` / `CONV_RAG_LLM_API_KEY` — optional OpenAI-compatible synthesizer
---
## Running Tests
```bash
HIP_VISIBLE_DEVICES="" CUDA_VISIBLE_DEVICES="" pytest -v
```
All tests run 100% offline on CPU in ~1 second (no Docker, no GPU, no external databases).
---
## Credits & License
- Licensed under the **MIT License** — see [LICENSE](LICENSE).
- The write-time secret-leak scanner (`conv_rag/security.py`), git-diffable JSONL canon validation workflow (`conv_rag/canon.py`), model-aware `embedding_sha` invalidation (`conv_rag/embedder.py`), and stdlib-only read-only local graph explorer (`conv_rag/ui_server.py`) were inspired by [Keutonim/Synapse](https://github.com/Keutonim/Synapse) (MIT License), re-engineered natively for zero-daemon SQLite.