Metadata-Version: 2.5
Name: supermem
Version: 0.5.0
Summary: Persistent AI memory without RAG — lifecycle-aware local retrieval
Project-URL: Homepage, https://github.com/lamenting-hawthorn/supermem
Project-URL: Repository, https://github.com/lamenting-hawthorn/supermem
Project-URL: Documentation, https://github.com/lamenting-hawthorn/supermem
Project-URL: Bug Tracker, https://github.com/lamenting-hawthorn/supermem/issues
Author-email: Hawthorn <rv.help23@gmail.com>
License: Apache-2.0
License-File: LICENSE
Keywords: ai,fts5,knowledge-base,llm,mcp,memory,rag,semantic-search
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Requires-Python: >=3.11
Requires-Dist: aiofiles
Requires-Dist: aiosqlite>=0.22.1
Requires-Dist: fastembed>=0.7.3
Requires-Dist: httpx>=0.27.0
Requires-Dist: jinja2
Requires-Dist: openai>=1.30.0
Requires-Dist: pydantic>=2.0.0
Requires-Dist: python-dotenv>=1.0.0
Requires-Dist: rich>=13.7.0
Requires-Dist: sqlite-vec>=0.1.6
Requires-Dist: structlog>=24.0.0
Requires-Dist: tenacity>=9.1.4
Requires-Dist: watchdog>=6.0.0
Provides-Extra: all
Requires-Dist: anthropic>=0.30.0; extra == 'all'
Requires-Dist: chromadb>=0.4.0; extra == 'all'
Requires-Dist: fastapi>=0.111.0; extra == 'all'
Requires-Dist: fastmcp>=2.0.0; extra == 'all'
Requires-Dist: huggingface-hub>=0.34.3; extra == 'all'
Requires-Dist: pygments>=2.19.2; extra == 'all'
Requires-Dist: sentence-transformers>=3.0.0; extra == 'all'
Requires-Dist: transformers<4.54.0,>4.51.0; extra == 'all'
Requires-Dist: uvicorn[standard]>=0.29.0; extra == 'all'
Requires-Dist: vllm>=0.5.5; (sys_platform != 'darwin') and extra == 'all'
Provides-Extra: claude
Requires-Dist: anthropic>=0.30.0; extra == 'claude'
Provides-Extra: local
Requires-Dist: huggingface-hub>=0.34.3; extra == 'local'
Requires-Dist: transformers<4.54.0,>4.51.0; extra == 'local'
Requires-Dist: vllm>=0.5.5; (sys_platform != 'darwin') and extra == 'local'
Provides-Extra: mcp
Requires-Dist: fastmcp>=2.0.0; extra == 'mcp'
Requires-Dist: pygments>=2.19.2; extra == 'mcp'
Provides-Extra: vector
Requires-Dist: chromadb>=0.4.0; extra == 'vector'
Requires-Dist: sentence-transformers>=3.0.0; extra == 'vector'
Provides-Extra: worker
Requires-Dist: fastapi>=0.111.0; extra == 'worker'
Requires-Dist: uvicorn[standard]>=0.29.0; extra == 'worker'
Description-Content-Type: text/markdown

# supermem

> **Persistent AI memory without RAG** — local-first, lifecycle-aware retrieval
> backed by SQLite FTS5, a SQLite entity graph, and your markdown vault.

[![PyPI](https://img.shields.io/pypi/v/supermem)](https://pypi.org/project/supermem/)
[![Python 3.11](https://img.shields.io/badge/python-3.11-blue.svg)](https://python.org)
[![License: Apache 2.0](https://img.shields.io/badge/License-Apache%202.0-green.svg)](LICENSE)
[![MCP](https://img.shields.io/badge/protocol-MCP-purple.svg)](https://modelcontextprotocol.io)
[![Docker](https://img.shields.io/badge/downloads-140%2B-orange)](https://github.com/lamenting-hawthorn/supermem/pkgs/container/supermem)
[![CI](https://github.com/lamenting-hawthorn/supermem/actions/workflows/ci.yml/badge.svg)](https://github.com/lamenting-hawthorn/supermem/actions/workflows/ci.yml)

An MCP (Model Context Protocol) server for trusted local stdio clients and
authenticated loopback HTTP clients. It provides **persistent, structured
memory** backed by SQLite, including its derived entity graph. Supported memory
retrieval stops at lifecycle-aware tiers 1–3; raw-vault Agent navigation (Tier
4) is unavailable until a source-aware lifecycle broker exists.

## Highlights

| Capability | What it gives you |
|------------|-------------------|
| **Boundary-aware retrieval** | Fast FTS5 first, graph expansion second, and optional vector search third. Every supported transport stops at Tier 3. |
| **Local-first vault** | Markdown files remain portable and inspectable; SQLite graph/FTS and sqlite-vec indexes can be rebuilt. |
| **Memory lifecycle** | Observations carry provenance, confidence, sensitivity, validity, TTL, and `active`/`retracted` status metadata. |
| **Retraction workflow** | Stale or sensitive observations can be retracted from FTS, vector-backed retrieval, timelines, and derived summaries. |
| **Local productivity insights** | Heuristic open-task extraction, follow-up suggestions, and day summaries without an LLM call. |
| **Safer operations** | Path-safe backup restore, shared MCP auth/rate guards, PR-safe CI release validation, and a documented security posture. |

---

## Python SDK (Embed in Agents, VLMs, Papers)

```bash
pip install supermem
```

```python
from supermem import SyncMemory  # plain blocking calls — no async boilerplate

mem = SyncMemory.open("./brain.db")
mem.remember("Switched to the Sony A7III", slot_key="camera")  # slot_key = update path
hits = mem.recall("suggest lenses for my camera", limit=5)
mem.close()
```

The async surface (`from supermem import Memory`) exposes the same five methods
(`open` / `remember` / `recall` / `forget` / `close`, plus
`recall_with_confidence`) for async applications. Both wrap the canonical
composition root: lifecycle-aware supersession, retraction, validity windows,
and sensitivity behave exactly as they do through the MCP/Worker adapters.
Semantic recall uses the embedded sqlite-vec tier with the local bge-small
embedder — no LLM ingest cost and no external services. State lives in one
authoritative SQLite database; vector embeddings sit in a rebuildable
sidecar cache that never needs backing up. FTS-only writes are
sub-millisecond; semantic writes pay the local embedding cost — a query-side
conflict scan plus document embedding, low tens of milliseconds on CPU.

---

## Quick Start (Personal, No GPU)

```bash
pip install "supermem[mcp]"

# Point supermem at a directory of markdown files
export SUPERMEM_VAULT_PATH=~/notes
export SUPERMEM_LLM_PROVIDER=openrouter
export OPENROUTER_API_KEY=your_key_here

# Start the MCP server (add to Claude Desktop's mcp.json)
supermem serve
```

Add to Claude Desktop `mcp.json`:
```json
{
  "mcpServers": {
    "supermem": {
      "command": "supermem",
      "args": ["serve"]
    }
  }
}
```

---

## Quick Start (Local Docker)

```bash
# Clone and configure
git clone https://github.com/lamenting-hawthorn/supermem
cp .env.example .env
# Edit .env: set SUPERMEM_VAULT_PATH, SUPERMEM_LLM_PROVIDER, API keys

# MCP server only (stdio, for Claude Desktop)
docker compose up supermem-mcp

# MCP server + HTTP dashboard
docker compose --profile worker up

# Dashboard at http://localhost:37777
```

---

## Architecture: Boundary-Aware Retrieval

Available content tiers run concurrently and their ranked lists are fused with
Reciprocal Rank Fusion (k=60); graph expansion enriches the fused results.
Tiers 1–3 never call an LLM. Every supported transport is capped at Tier 3.
Tier 4 raw-vault Agent navigation is deliberately unavailable until a
source-aware lifecycle broker can enforce the same retraction and deletion
policy as indexed retrieval.

```
Query
  │
  ├─ Tier 1: SQLite FTS5 full-text search          ~1ms    always available
  │          porter tokenizer, WAL mode
  │
  ├─ Tier 3: sqlite-vec vector similarity          ~10ms   optional (SUPERMEM_VECTOR=true)
  │          fastembed embeddings (BAAI/bge-small-en-v1.5, ~130MB ONNX,
  │          downloaded on first use); pluggable providers incl. local
  │          OpenAI-compatible endpoints. ChromaDB remains as an optional
  │          legacy backend (`vector` extra, SUPERMEM_VECTOR_BACKEND=chroma).
  │
  ├─ optional: local cross-encoder rerank          flag-gated (SUPERMEM_RERANKER=true)
  │          re-orders the top-50 fused candidates (fastembed TextCrossEncoder)
  │
  ├─ Tier 2: SQLite entity-graph expansion         local   always available
  │          recursive BFS entity expansion seeded by fused hits
  │
  └─ Tier 4: raw-vault Agent navigation            unavailable
             pending a source-aware lifecycle broker
```

**Fusion rule**: FTS and vector search run in parallel and their rankings fuse
with calibrated score interpolation by default (`rrf` remains an opt-in
fallback); graph hits are appended behind the fused ranking; the optional
reranker only re-orders the fused set. Candidate IDs are filtered through
observation lifecycle status **after** fusion, so retracted, expired, or
deleted memories can never surface no matter how a tier ranked them. Vector
hits worse than `SUPERMEM_VECTOR_MAX_DISTANCE` (cosine distance, default 0.55
for the default bge-small embedder) are dropped as a generous recall floor.
That floor is not an abstention gate: search responses also carry advisory
`confidence` metadata (`top_score`, `score_margin`, `lexical_overlap`, and
`low_confidence`) so callers can decide how cautiously to use weak evidence.
`score_margin` is the gap to the second-best distinct fused source and is null
when only one exists; `low_confidence` is true only when lexical overlap is
below 0.15 and the top fused score is below the calibrated content midpoint.
The metadata never filters or reorders retrieval results.

Write-time enrichment is deterministic by default: relative dates are grounded
inline against the observation/session timestamp, whitespace/case-normalized
exact duplicates reuse the active memory, and (when vectors are available) the
single existing write-time scan can add up to three typed `related` links.
Semantic near-dedup and atomic fact extraction are opt-in; fact extraction uses
an application-supplied provider seam and ships no built-in LLM client.
Observation relationships use `obs_edges` because `entity_edges` is keyed by
entity names, while memory similarity and supersession relationships are
between observation IDs.

---

## Memory Lifecycle and Retraction

Each observation is stored with lifecycle/provenance metadata designed for source-grounded memory:

| Field group | Examples | Purpose |
|-------------|----------|---------|
| Source | `source_id`, `source_span`, `observed_at` | Trace a memory back to an import, file, conversation, or time span. |
| Validity | `valid_from`, `valid_until`, `confidence`, `trust_level` | Represent changing facts and retrieval confidence. |
| Governance | `sensitivity`, `status`, `expires_at` | Support privacy labels, TTL cleanup, and active/retracted filtering. |

Use `retract_observation` or `POST /observations/{id}/retract` to mark stale or sensitive records as retracted. Retraction removes the observation from FTS, filters it from hybrid retrieval, deletes vector chunks when available through the MCP/worker path, removes it from timelines and recent-session context, and invalidates derived session summaries. Retraction reasons are stored in a non-FTS audit table so the value being forgotten is not re-indexed as an active memory.

---

## MCP Tool Reference

| Tool | Parameters | Returns | Notes |
|------|-----------|---------|-------|
| `use_memory_agent` | `question: str` | Formatted answer | Compatibility name; uses lifecycle-aware tiers 1–3 only |
| `supermem_hybrid` | `query: str`, `tier_limit: int = 3` | JSON with `obs_ids`, `source_tier`, `latency_ms`, advisory `confidence` | Requests above 3 are capped for every transport; Tier 4 is unavailable |
| `get_observations` | `ids: list[int]` | JSON array of observation dicts | Fetch full content for specific IDs |
| `get_timeline` | `obs_id: int`, `window: int = 5` | JSON array of chronological observations | Context around a specific observation |
| `list_open_tasks` | `days: int = 14`, `limit: int = 20` | JSON with likely unresolved tasks | Local heuristic open-loop inbox inspired by ambient memory tools |
| `suggest_followups` | `days: int = 14`, `limit: int = 10` | JSON with next-action suggestions | Turns open tasks into concise follow-up prompts |
| `list_day_summaries` | `days: int = 7` | JSON day summaries | Keywords, highlights, and open-loop counts from recent observations |
| `retract_observation` | `obs_id: int`, `reason: str = ""` | JSON retraction status | Marks stale or incorrect memories as retracted so retrieval ignores them |

### Progressive Disclosure Pattern

```python
# 1. Search — cheap, returns IDs only
result = await supermem_hybrid("Alice's project status", tier_limit=2)
# {"obs_ids": [42, 17, 88], "source_tier": 1, "latency_ms": 2.1}

# 2. Fetch — only for IDs you actually need
obs = await get_observations([42, 17])
# [{"id": 42, "content": "...", "tier_used": 1}, ...]

# 3. Timeline — context around interesting observations
ctx = await get_timeline(42, window=3)

# 4. Retract — remove stale/sensitive memory from retrieval
await retract_observation(obs_id=42, reason="superseded by current roadmap")
```

### Local Insight Pattern

```python
# Open-loop inbox for recent memory
tasks = await list_open_tasks(days=14, limit=20)

# Turn open tasks into concise next-action prompts
followups = await suggest_followups(days=14, limit=10)

# Summarize recent days without an LLM call
summaries = await list_day_summaries(days=7)
```

---

## Environment Variables

| Variable | Default | Description |
|----------|---------|-------------|
| `SUPERMEM_LLM_PROVIDER` | `openrouter` | `openrouter` \| `ollama` \| `claude` \| `lmstudio` |
| `SUPERMEM_LLM_MODEL` | provider default | Model string (e.g. `openai/gpt-4o-mini`, `llama3`) |
| `SUPERMEM_DB_PATH` | `~/.supermem/supermem.db` | SQLite database path |
| `SUPERMEM_VAULT_PATH` | `.memory_path` file | Markdown vault directory |
| `SUPERMEM_VECTOR` | `false` | Set `true` to enable the vector tier |
| `SUPERMEM_VECTOR_BACKEND` | `""` (auto) | `sqlite` (default when sqlite-vec installed) \| `chroma` (optional `vector` extra) \| `none` |
| `SUPERMEM_VECTORS_PATH` | beside `SUPERMEM_DB_PATH` | sqlite-vec store path (`vectors.db`) |
| `SUPERMEM_VECTOR_MAX_DISTANCE` | `0.55` | Generous cosine-distance recall floor for vector hits (`off` disables); calibrated only for the default bge-small model, not an abstention gate |
| `SUPERMEM_RESOLVE_RELATIVE_DATES` | `true` | Deterministically annotate grounded dates inline at write time (for example `yesterday [2026-11-27]`) without removing the original words |
| `SUPERMEM_AUTO_RELATED_EDGES` | `true` | Reuse the write-time vector scan to link up to three active neighbors at cosine distance `<= 0.55` with typed `related` observation edges |
| `SUPERMEM_EXACT_DEDUP` | `true` | Reuse an active observation of the same type when canonical case/whitespace-normalized content is identical; superseded or expired copies do not block rewrites |
| `SUPERMEM_SEMANTIC_DEDUP` | `false` | Conservative opt-in near-dedup: vector similarity `>= 0.85` revises/supersedes the matching active memory instead of storing a duplicate |
| `SUPERMEM_FACT_EXTRACTION` | `false` | Enable an application-injected fact-extraction provider; no LLM extractor ships or runs by default |
| `SUPERMEM_EMBEDDING_PROVIDER` | `""` (auto) | `fastembed` (default) \| `local-endpoint` (OpenAI-compatible) |
| `SUPERMEM_EMBEDDING_MODEL` | `BAAI/bge-small-en-v1.5` | Embedding model for the fastembed provider |
| `SUPERMEM_EMBEDDING_BASE_URL` | `http://localhost:1234/v1` | Base URL for the local-endpoint provider |
| `SUPERMEM_RERANKER` | `false` | Enable local cross-encoder rerank of top-50 fused candidates (fastembed, ~80MB ONNX on first use) |
| `SUPERMEM_RERANK_MODEL` | `Xenova/ms-marco-MiniLM-L-6-v2` | Reranker model |
| `SUPERMEM_DEFAULT_TIER_LIMIT` | `3` | Default lifecycle-aware retrieval ceiling; values above 3 are capped |
| `SUPERMEM_API_KEY` | _(none)_ | Bearer token required for primary MCP HTTP and protected Worker HTTP endpoints (fail closed if unset) |
| `SUPERMEM_RATE_LIMIT` | `60` | Requests/minute limit per client identity across MCP tools |
| `SUPERMEM_WORKER_PORT` | `37777` | HTTP dashboard port |
| `SUPERMEM_COMPRESS_EVERY` | `50` | Observations written before LLM compression |
| `SUPERMEM_OBS_TTL_DAYS` | `90` | Retention window for regular observations (`0` disables TTL expiry) |
| `SUPERMEM_MAX_OBS_CHARS` | `65536` | Maximum vault-file body characters stored in one FTS observation; larger files log a warning (vectors still chunk full clean text) |
| `OPENROUTER_API_KEY` | _(required for openrouter)_ | OpenRouter API key |
| `ANTHROPIC_API_KEY` | _(required for claude)_ | Anthropic API key |
| `OLLAMA_HOST` | `http://localhost:11434` | Ollama server URL |
| `LMSTUDIO_HOST` | `http://localhost:1234` | LM Studio server URL |

> **Note:** Local model inference (vLLM/CUDA) is an optional extra. Install with `pip install supermem[local]` if you need it. Not included in the default install.

**Contextual embedders.** Embedders are plain callables mapping `list[str]` →
vectors; any object with that shape can be injected as a custom provider. An
embedder may additionally expose `embed_documents(docs: list[list[str]])` —
the optional contextual-embedding seam used by document-aware models
(Perplexity pplx-embed-context, Voyage-context style). When present, the
sqlite-vec backend passes chunks grouped by parent document (one inner list
per vault file, in upsert order) so every chunk is encoded with its document
context; batching never splits a document across calls. Embedders without
`embed_documents` are unaffected: they receive the exact same flattened
`list[str]` batches as always. Query embedding is unchanged — retrieval still
embeds queries through the plain callable/`query_embed` path.

---

## Connector Guide

Import external data into your vault with one command:

```bash
# ChatGPT export (Settings → Data controls → Export data → .zip)
supermem connect chatgpt ~/Downloads/chatgpt_export.zip

# Notion workspace export (.zip)
supermem connect notion ~/Downloads/notion_export.zip

# Nuclino workspace export (.zip)
supermem connect nuclino ~/Downloads/nuclino_export.zip

# GitHub repositories (live via API)
supermem connect github owner/repo1,owner/repo2 --token ghp_xxx

# Google Docs (OAuth, opens browser)
supermem connect google_docs "My Doc Name"
```

All connectors write markdown to your vault, then automatically index the files into SQLite + graph. Private content wrapped in `<private>...</private>` tags is stripped before indexing.

---

## CLI Reference

```bash
supermem serve            # Start MCP server (stdio transport, for Claude Desktop)
supermem serve --worker   # Start MCP server + HTTP dashboard on :37777
supermem chat             # Interactive terminal REPL (no client required)
supermem backup           # Create timestamped .tar.gz (vault + consistent SQLite snapshot)
supermem backup --output /path/to/archive.tar.gz
supermem restore <archive.tar.gz>
supermem connect <type> <source> [--token TOKEN] [--max-items N]
```

### Backup and storage ownership

`supermem.db` is the authoritative store for observations, lifecycle state,
sessions, summaries, retraction audit records, and entity-indexing metadata.
Some projections live in that same file (`content_fts` and the SQLite
`entity_edges` adjacency projection), but `vectors.db` is different: it is only
a rebuildable sqlite-vec embedding cache and is not required in backups.

Because SQLite runs in WAL mode, copying a live `supermem.db` file by itself can
omit committed data still in `supermem.db-wal`. Both `supermem backup` and the
Worker `/backup` endpoint therefore use SQLite's online backup API to place a
transactionally consistent snapshot in the archive. Restore removes stale
`-wal`, `-shm`, and `-journal` sidecars before installing the snapshot.

To rebuild `vectors.db`, delete it and reindex: vault walks detect the empty
derived cache and regenerate vectors even when file mtimes are unchanged, while
`POST /index/rebuild` forces a full rebuild.

---

## HTTP Dashboard (Optional)

Start with `supermem serve --worker` or `docker compose --profile worker up`.

| Endpoint | Method | Description |
|----------|--------|-------------|
| `/.well-known/oauth-protected-resource` | GET | Protected-resource metadata only; no OAuth issuer/JWKS/scope validation |
| `/health` | GET | `{"status":"ok","db":true,"graph":false,"vector":false}` |
| `/sessions` | GET | Paginated session list with summaries |
| `/observations` | GET | Active observations only; filter by session/type |
| `/search` | POST | `{"query": "...", "tier_limit": 3}` (HTTP cap) |
| `/index/rebuild` | POST | Forces a full vault reindex, including regeneration of derived vectors |
| `/backup` | GET | Streams vault + consistent SQLite snapshot as `.tar.gz` |
| `/stats` | GET | `{obs_count, entity_count, session_count, db_size_mb}` |
| `/open-tasks` | GET | Local heuristic open-loop/task extraction |
| `/followups` | GET | Follow-up suggestions derived from recent open tasks |
| `/day-summaries` | GET | Local day summaries with keywords and highlights |
| `/observations/{id}/retract` | POST | Mark an observation retracted so retrieval ignores it |

Auth: protected Worker endpoints require `Authorization: Bearer <SUPERMEM_API_KEY>`
and fail closed when the key is unset.
The dashboard prompts for this key and keeps it only in the current page's
JavaScript memory; it does not put the credential in the URL or browser storage,
and a refresh clears it.

The primary MCP HTTP profile is authenticated, loopback-only, and stateless:
each request creates no resumable MCP transport session and no MCP session ID is
issued. Clients needing persistent protocol sessions should use local stdio.

> Keep HTTP on a trusted loopback/private boundary. Static API-key auth does not establish remote-production or multi-tenant support; see [`SECURITY.md`](SECURITY.md).

---

## Privacy and Security

Wrap sensitive content in `<private>...</private>` tags. It is stripped before
writing to any storage layer (SQLite or vector store). Raw Agent vault content
and metadata inspection are unavailable until a source-aware lifecycle broker
exists. The restricted executor is not a hostile-code sandbox; remote execution
remains unsupported.

```markdown
# Meeting Notes

Alice discussed the roadmap.
<private>Budget: $2.4M approved for Q3</private>
Next steps: ship v2 by June.
```

Additional safeguards:

- Backup restore rejects archive members that would escape the configured vault.
- Notion/Nuclino ZIP imports bound member count, central-directory size, compression ratio, total extraction, parsed Markdown/CSV size, and attachment size separately.
- MCP tools share one auth/rate-limit guard and one per-client rate bucket.
- The Python executor blocks denied imports (including direct platform raw-I/O modules), scrubs inherited environment variables, and wraps common filesystem APIs; it is still a restricted local executor, **not** a substitute for container/OS isolation for hostile code.
- Keep current HTTP surfaces off untrusted networks. OAuth identities, scopes, installed-artifact E2E, staging, and remote-production proof remain future work; see [`SECURITY.md`](SECURITY.md).

---

## CI and Release Checks

Pull requests run lint, formatting, type-checking, tests with coverage, Docker build validation, and package build validation. Docker pushes and PyPI publishing remain gated to version-tag pushes (`v*`) so PRs validate release artifacts without publishing them.

---

## Running Tests

```bash
uv run pytest tests/ -v                          # all tests
uv run pytest tests/unit/ -v                     # unit only (fast, no network)
uv run pytest tests/integration/ -v              # integration (real storage)
uv run pytest tests/ --cov=supermem --cov-report=term-missing  # with coverage
```

Coverage gate: 60% (CI enforced). Anthropic tests are auto-skipped if the package is not installed.

---

## License

Apache 2.0 — see [LICENSE](LICENSE).
