Metadata-Version: 2.4
Name: episteme-mcp
Version: 0.5.1
Summary: Zero-infrastructure epistemic memory and living knowledge MCP server (SQLite+FTS5, EvoSCM belief revision, Dual-Layer Epistemic PPR).
Author: Gabriel Moreira de Oliveira
License-Expression: MIT
Project-URL: Homepage, https://github.com/Dhekki/episteme-mcp
Project-URL: Repository, https://github.com/Dhekki/episteme-mcp
Project-URL: Issues, https://github.com/Dhekki/episteme-mcp/issues
Keywords: mcp,epistemic-memory,knowledge-graph,rag,sqlite,fts5,belief-revision,ai-agents
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy>=1.24
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == "dev"
Dynamic: license-file

# Episteme MCP (`episteme-mcp`)

**Local memory for AI agents that knows when facts become obsolete.**  
Zero Docker, zero Neo4j, zero vector database — runs 100% on CPU using **Python stdlib + NumPy + Lazy SQLite WAL & FTS5** over a pure-stdlib **MCP `stdio` server**.

[![PyPI version](https://img.shields.io/pypi/v/episteme-mcp.svg)](https://pypi.org/project/episteme-mcp/)
[![Python 3.10+](https://img.shields.io/badge/python-3.10+-blue.svg)](https://www.python.org/downloads/)
[![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)

---

## Why? Flat RAG suffers from "Memory Rot"

When a spec, ADR, or policy changes from **`v1`** to **`v2`**, standard RAG and vector memory stores treat both chunks as equally valid. Your AI agent retrieves the deprecated rule alongside the new one and hallucinates outdated behavior.

```text
📄 docs/auth.md (2023)       → "Production tokens use HS256 with 3600 s TTL"
✏️ docs/auth.md (edited 2026) → "Production tokens use EdDSA + DPoP with 300 s TTL"

❌ Flat RAG / Vector DB:
   #1 [auth_v1 | score=0.84] "Production tokens use HS256 with 3600 s TTL"  ← stale rule wins!
   #2 [auth_v2 | score=0.71] "Production tokens use EdDSA + DPoP with 300 s TTL"

✅ Episteme MCP (episteme-mcp):
   [ACTIVE]     EdDSA + DPoP · 300 s TTL (production)  ← rank #1 verbatim excerpt
   [SUPERSEDED] HS256 · 3600 s TTL (gated weight=0.02, preserved in audit log only)
```

```mermaid
flowchart LR
  A["Edited docs / ADRs / Notes"] --> B["ColdStore (SQLite WAL + FTS5)"]
  B --> C["EvoSCM Belief Revision"]
  C -->|"ACTIVE (weight 1.0)"| D["Current Rules & Scoped Exceptions"]
  C -->|"SUPERSEDED (weight 0.02)"| E["Audit Log Only (Zero Leak)"]
  D --> F["MCP Briefing -> Cursor / Claude / Antigravity"]
```

**Episteme MCP** separates an immutable verbatim **Cold Lab Notebook (`ColdStore`)** from an epistemic **Hot Map (`MentalPalace`)**:
- **Evidence-gated belief revision:** Older rules are marked `superseded` or `falsified` with an explicit audit trail — never silently erased, and never leaked as active truth (`0` traps vs `8` traps on Dense RAG).
- **Scoped coexistence:** Knows the difference between a deprecated global default (`v1 -> v2`) and a valid scoped exception (`e.g., sandbox` or `EU-only fallback`).
- **Incremental `sha256` ingestion:** Edit a Markdown/ADR file and re-run `ingest` — unchanged files are skipped, and edited files automatically supersede their previous version.

---

## 60-Second Quick Start

### 1. Try it in the terminal (`uvx`, zero setup)

```bash
# Ingest a local docs/, ADR folder, or Obsidian vault (incremental sha256 + auto-supersession)
uvx episteme-mcp ingest ./docs --palace-dir ./palace_data

# Query active truths (with superseded-fact guardrails)
uvx episteme-mcp query "What is the current production auth standard?" --palace-dir ./palace_data

# Inspect stored docs, claims, and revision log
uvx episteme-mcp stats --palace-dir ./palace_data
```

*(Add `--embed-model nomic-embed-text` for opt-in Hybrid `FTS5 + Dense RRF` retrieval via Ollama.)*

### 2. Plug into Cursor, Claude Desktop, or Antigravity

Add this to your MCP config (`mcp_config.json`, `claude_desktop_config.json`, or `.cursor/mcp.json`) — use an **absolute path** for `--palace-dir` so desktop MCP clients always resolve the same database:

```json
{
  "mcpServers": {
    "episteme": {
      "command": "uvx",
      "args": [
        "episteme-mcp",
        "--palace-dir",
        "/absolute/path/to/palace_data",
        "--default-profile",
        "full_cloud"
      ]
    }
  }
}
```

Exposes **2 primary tools** (`palace_remember`, `palace_recall`), **7 low-level primitives** (`palace_ingest_document`, `palace_propose_claim`, `palace_revise_belief`, `palace_query`, `palace_dereference_chunks`, `palace_sleep_consolidate`, `palace_curiosity_frontier`), and **3 resources** (`palace://stats`, `palace://revision-log`, `palace://curiosity-frontier`).  
See [docs/MCP_SETUP.md](docs/MCP_SETUP.md) for all CLI flags, environment variables, and LLM sleep-adjudicator options.

---

## Honest Positioning: Episteme vs. Local RAG, Graphify, and MemPalace

| Capability | Local RAG MCP (`BM25` / Chroma) | Graphify (`tree-sitter` AST) | Conversational Memory (`MemPalace`) | **Episteme MCP (`episteme-mcp`)** |
| :--- | :---: | :---: | :---: | :---: |
| **Best for** | Static doc & PDF search | Codebase AST & call graphs | Verbatim multi-session chat recall | **Living KBs** (ADRs, specs, policies, Obsidian vaults, research) |
| **Handles `v1 -> v2` supersession** | ❌ Mixes old & new chunks | N/A (current code snapshot) | ⚠️ Session-centric | ✅ **Evidence-gated (`0` traps on Living KB)** |
| **Scoped exceptions + evergreen rules** | ⚠️ Often over-retrieved or missed | N/A | ⚠️ Unstructured | ✅ **Explicit boundary conditions + Dual-Layer PPR** |
| **Infrastructure required** | Vector DB / local embeddings | Tree-sitter parser | ChromaDB + MiniLM + SQLite | ✅ **Zero infra** (SQLite WAL + FTS5 + NumPy, 100% CPU) |
| **Auditability** | Similarity score | AST edges | Chat snippets | ✅ **Immutable `BeliefRevisionEvent` log** |

> **Complementary, not mutually exclusive:** Use **`graphify`** for codebase AST / blast-radius navigation, and **`episteme-mcp`** alongside it for the evolving *"why"* — ADRs, architecture decisions, API policies, and specs that change over time.

---

## Verified Benchmark Highlights

* **Living KB (`--extract-with-llm`, `google/gemini-3.8-flash`, 20 versioned docs):** **`0.952` Net Score (`0` traps)** vs Dense RAG (`0.844`, `8` traps), Hybrid RRF (`0.867`, `5` traps), and Hybrid + LLM Reranker (`0.910`, `4` traps). `7/7` deprecated docs superseded, `0/13` false positives.
* **Multi-Doc Scientific Interference (Exp 1 — 12 real 2026 papers, 303 chunks + superseded prior):** **`0.838` vs `0.792` (`+4.6 pp`)** overall, and **`+25.0 pp` (`0.854` vs `0.604`)** on belief revision.
* **Active Discovery & Executable World Models (Exp 2 & Exp 3 — blind `--anonymize`):** Beat Flat-Log **15/15 (100%)** (`+31.1 pp` avg) on Exp 2; **`1.000 ± 0.000`** exact hold-out accuracy on Exp 3 (`100%` promoted on attempt `1/3`, `0/10` false promotions on `qwen2.5:3b`).
* **LongMemEval (`knowledge-update`, `N=15`):** Tied #1 at **`0.933` (`14/15`)** with opt-in Hybrid RRF + EvoSCM, beating BM25 (`+6.6 pp`), Hybrid+Reranker (`+13.3 pp`), and Dense (`+20.0 pp`). *(EvoSCM Phase 3 sub-session fact supersession is implemented and unit-tested in `v0.5.0`; live re-evaluation on LongMemEval is scheduled for `v0.5.1`.)*
* **Speed & Footprint (`v0.5.0` Lazy SQLite):** **`2.15 ms`** load (`0` chunk texts preloaded in RAM at 2,101 chunks), **`2.47 ms`** incremental `+1 doc` write (`BEGIN IMMEDIATE`), **`14.3 ms`** FTS5 BM25 at 7,500 chunks, **`28.7 ms`** end-to-end `palace.query()`.

<details>
<summary><strong>Click to expand full benchmark tables & methodology</strong></summary>

### 1. Living KB Benchmark — Zero-Touch Auto-Extraction (`--extract-with-llm`, 20 versioned docs, 24 Qs)
Running on **`google/gemini-3.8-flash`** (Vertex AI) with **zero manual curation** (`7/7` deprecated docs automatically superseded, `0/13` false positives) against modern 2026 RAG baselines (`nomic-embed-text`):

| System | Fact Recall | Net Score | Total Traps | `superseded_rule` | `scoped_coexistence` | `evergreen` | `multi_hop` |
| :--- | :---: | :---: | :---: | :---: | :---: | :---: | :---: |
| `B4_dense_rag_k5` (`nomic-embed-text`) | `0.927` | `0.844` | `8` | `0.708` | `0.875` | `1.000` | `0.792` |
| `B5_hybrid_rrf_k5` (`BM25 + Dense RRF`) | `0.919` | `0.867` | `5` | `0.875` | `0.833` | `1.000` | `0.758` |
| `B3_recency_rag_k5` | `0.912` | `0.902` | `1` | `1.000` | `0.833` | `0.917` | `0.858` |
| `B6_hybrid_rerank_k5` (`Hybrid + LLM Reranker`) | `0.952` | `0.910` | `4` | `0.917` | `0.875` | `1.000` | `0.850` |
| **`P_balanced_10k`** *(auto-extracted)* | `0.933` | **`0.933`** | **`0`** | **`1.000`** | `0.833` | `1.000` | **`0.900`** |
| **`P_full_cloud`** *(auto-extracted)* | **`0.952`** | **`0.952`** | **`0`** | **`1.000`** | **`0.917`** | `0.958` | **`0.933`** |

*(On local `qwen2.5:3b` zero-touch auto-extraction, `P_full_cloud = 0.899 (0 traps)` and `P_balanced_7b = 0.888 (0 traps)` also beat every RAG baseline: `BM25 = 0.838`, `Recency = 0.835`, `Dense = 0.817`.)*

### 2. Multi-Document Scientific Interference (Exp 1 — 12 real 2026 papers, 303 chunks + superseded 2022 prior)
- **Asymmetric Architecture (`qwen2.5:3b` local indexer → `google/gemini-3.8-flash` `full_cloud` QA):**
  - **`Mental Palace = 0.838`** vs **`Flat RAG = 0.792`** (**`+4.6 pp`** overall; `belief_revision`: **`0.854` vs `0.604` (`+25.0 pp`)**; `factual`: **`0.854` vs `0.792` (`+6.2 pp`)**).
- **Local `qwen2.5:3b` (`compact_3b`):** `0.617` vs `0.583` (`0/20` vs `8/20` superseded-prior pollution; `0.000` degradation from 1 to 12 documents).

### 3. Active Scientific Discovery & Executable World Models (Exp 2 & Exp 3 — Blind `--anonymize`, Zero Leakage)
- **Exp 2 (15 blind seeds across `qwen2.5:3b`, `qwen2.5:7b`, `olmo2:7b`):** Mental Palace + EvoSCM + Active Curiosity (`A3`) beat Flat-Log (`A1`) **15/15 (100%)**, averaging **`+31.1 pp`** on unseen compositional hold-out scenarios.
- **Exp 3 (*WorldCoder* + SCL Promotion Gate):**
  - `qwen2.5:3b` (10 seeds): gate rejected `10/10` underfit programs (`0%` false promotions, `0` regressions vs `A3_neural`).
  - `google/gemini-3.8-flash` (3 blind seeds): **`1.000 ± 0.000`** exact hold-out accuracy in `A3_neural` and **`1.000 ± 0.000`** in `A4_worldcoder_gated` (**`100%` promoted on attempt `1/3`**), compiling discovered rules into a sandboxed Python simulator (`$0` / `<1 ms` per counterfactual query).

### 4. External Benchmark: LongMemEval (`knowledge-update`, `xiaowu0162/longmemeval-cleaned`, `N=15`)
Evaluated on `google/gemini-3.8-flash` + `nomic-embed-text` (~40 real multi-turn chat sessions per question, zero oracle hints):

| System | Judge Accuracy | Latest Recall@5 | Stale Rate@5 | Avg Chars |
| :--- | :---: | :---: | :---: | :---: |
| `B2_dense_k5` (`nomic-embed-text`) | `0.733` (`11/15`) | `0.800` | `0.800` | `7755` |
| `B4_hybrid_rerank_k5` (`Hybrid + LLM Reranker`) | `0.800` (`12/15`) | `1.000` | `0.933` | `7800` |
| `B1_bm25_k5` | `0.867` (`13/15`) | `0.933` | `0.933` | `7852` |
| `B3_hybrid_rrf_k5` | **`0.933`** (`14/15`) | `0.933` | `0.800` | `7751` |
| **`P_palace_hybrid_evoscm`** *(opt-in Hybrid RRF + EvoSCM)* | **`0.933`** (`14/15`) | `0.933` | `0.800` | `7777` |

*(Note: on casual multi-topic chat logs, document-level EvoSCM stayed conservative with `0` false-positive supersessions while opt-in Hybrid RRF tied #1 at `0.933`. EvoSCM Phase 3 adds sub-session atomic fact supersession with `[SUPERSEDED FACT]` guardrails.)*

### 5. Scale, Low-RAM Lazy SQLite & Concurrency (v0.5.0)
- **Lazy LRU `ColdStore` (`2,101` chunks / 150 docs):** **`2.15 ms` load** (`0` chunk texts preloaded in RAM), **`2.47 ms` incremental `+1 doc` write** via `BEGIN IMMEDIATE` + incremental `UPSERT` (multi-agent safe).
- **7,500 chunks / 500 docs:** **`14.3 ms` FTS5 BM25** | **`28.7 ms` end-to-end `palace.query()`**.
- **Token & Write Efficiency:** Hot/Cold deduplication trims redundant `full_cloud` prose (`-6.1%` chars on Living KB with `1.000` recall); batched document extraction packs up to 5 chunks/call (`~4–5×` fewer write calls).

</details>

---

## Development & Repository Structure

```bash
git clone https://github.com/Dhekki/episteme-mcp.git
cd episteme-mcp
pip install -e ".[dev]"
pytest -q tests/   # 58 deterministic CPU unit & integration tests
```

- `src/palace/` — Core runtime: `cli.py`, `cold_store.py` (with opt-in `HttpEmbeddingClient` & `search_hybrid`), `mental_palace.py` (Dual-Layer Epistemic PPR + EvoSCM Phases 1–3), `sqlite_store.py` (Lazy LRU + WAL `BEGIN IMMEDIATE` + FTS5), `schema.py`, `llm_client.py`, `baselines.py`, `mcp_server.py`.
- `experiments/` — Reproducible benchmarks: `exp0_bacterial_confinement/`, `exp1_multi_doc_interference/`, `exp2_blackbox_lab/`, `exp3_worldcoder/`, `exp_living_kb/`, `exp_longmemeval/`.
- `docs/` — [FOUNDATIONS_AND_MATHEMATICS.md](docs/FOUNDATIONS_AND_MATHEMATICS.md), [MCP_SETUP.md](docs/MCP_SETUP.md), [HANDOFF_STATE.md](docs/HANDOFF_STATE.md).
- `tests/` — 58 deterministic CPU unit & integration tests.

## License

[MIT](LICENSE)
