# 🧠 Mnemosynth

**Persistent, hallucination-resistant memory for any LLM, agent, or AI workflow.**

```bash
pip install mnemosynth       # Fast, lightweight install (Keyword-based engines)
pip install "mnemosynth[ml]" # Advanced install (Loads PyTorch/Transformers for Neural Models)
```

PyPI · Apache 2.0 · Python ≥ 3.10 · No external services required

---

## The Problem

LLMs forget everything when a session ends. RAG helps — but raw retrieval doesn't verify, decay, or reason about what it stores. You get confident hallucinations, stale facts, and no audit trail.

**Mnemosynth is a cognitive memory OS, not a vector store.**

---

## Three-Tier Memory Model

Inspired by how the brain actually works:

| Tier | Brain Region | Backend | What It Stores |
|---|---|---|---|
| **Episodic** | Hippocampus | LanceDB (vector) | Events, conversations, timestamped history |
| **Semantic** | Neocortex | NetworkX (graph) | Verified facts, entity relationships |
| **Procedural** | Cerebellum | JSON registry | Tools, schemas, workflows |

Memories are **automatically classified** on write. No manual tagging required.

---

## Quickstart

### Python API

```python
from mnemosynth import Mnemosynth

brain = Mnemosynth()

# Store — auto-classified into episodic/semantic/procedural
brain.remember("User prefers Python and dark mode")
brain.remember("Yesterday we finalized the auth module")
brain.remember("Deploy with: docker compose up -d")

# Retrieve with semantic search
for r in brain.recall("What languages does the user prefer?"):
    print(f"[{r.memory_type.value}] {r.content} ({r.confidence:.0%})")

# Compress relevant memories into a <150-token LLM context block
digest = brain.digest("Starting a new project")

# Dream: cluster episodic patterns -> promote to verified semantic facts
brain.dream()
```

### MCP Server (Claude Desktop / Cursor / Windsurf)

```json
{
  "mcpServers": {
    "mnemosynth": {
      "command": "mnemosynth",
      "args": ["serve"]
    }
  }
}
```

Everything runs locally under `~/.mnemosynth/`. No external services.

---

## Anti-Hallucination Engine

Mnemosynth doesn't just store — it **defends**:

- **Forgetting curve** — Ebbinghaus decay with configurable half-life; stale memories lose confidence
- **Contradiction detection** — Flags conflicting facts (*Uses DeBERTa NLI if `[ml]` is installed, otherwise falls back to fast keyword analysis*)
- **Sentiment analysis** — Emotion-aware memory retrieval (*Uses DistilBERT if `[ml]` is installed, otherwise falls back to fast keyword scoring*)
- **Belief revision chains** — Deprecated facts link forward to their replacements
- **Corroboration scoring** — Repeated observations boost confidence
- **Memory immune system** — Prompt injection detection, rate limiting, quarantine

---

## Dream Consolidation

Run `brain.dream()` (or `mnemosynth dream`) to trigger offline consolidation:

1. **Cluster** episodic memories with HDBSCAN
2. **Promote** recurring patterns to verified semantic facts
3. **Decay** memories that haven't been accessed recently

Think of it as sleep for your AI's memory.

---

## MCP Tools

| Tool | Description |
|---|---|
| `add_memory` | Store with auto-classification |
| `search_memory` | Semantic search across all tiers |
| `get_digest` | Compressed XML context block for LLM injection |
| `get_contradictions` | Surface conflicting facts |
| `run_dream` | Trigger consolidation |
| `forget` | Delete by ID |
| `get_stats` | Memory statistics |
| `get_provenance` | Full audit trail for any memory |

---

## CLI

```bash
mnemosynth serve              # Start MCP server
mnemosynth stats              # Memory dashboard
mnemosynth search "query"     # Semantic search
mnemosynth inspect            # Browse memory tree
mnemosynth dream              # Run consolidation
mnemosynth health             # System diagnostics
mnemosynth export -o out.json # Export to JSON or Markdown
mnemosynth forget <ID>        # Delete a memory
mnemosynth reset --confirm    # Wipe everything
```

---

## Configuration

Override defaults at `~/.mnemosynth/config.yaml`:

```yaml
embedding_model: all-MiniLM-L6-v2
max_episodic_memories: 10000
max_semantic_nodes: 5000

decay:
  half_life_days: 30.0
  min_confidence: 0.1

dream:
  interval_hours: 24
  min_cluster_size: 3

digest:
  max_tokens: 150
  top_k: 5
```

---

## Architecture

```
Claude Desktop / Cursor / Windsurf / Python API
              |  MCP (stdio) / Python import
     Router · Digest · Decay · Dream
     Sentiment · Contradiction · Immune System
              |
  Episodic (LanceDB) · Semantic (NetworkX) · Procedural (JSON)
              |
         ~/.mnemosynth/
```

---

Built by [Vasudev Jaiswal](https://github.com/vasudevjaiswal) · Apache 2.0