Content
# 🧠 APEX-MEM
> **The strongest multi-dimensional memory system for AI agents.** A drop-in replacement and **superset** of OpenClaw's memory subsystem, implemented in pure Rust.
[](https://www.rust-lang.org/)
[](LICENSE)
[](https://modelcontextprotocol.io/)
[]()
APEX-MEM unifies everything that makes OpenClaw's memory good, and **adds** what it doesn't have:
| Feature | OpenClaw | APEX-MEM |
|---|---|---|
| Memory dimensions | 3 (Session/Working, Long-term, Wiki) | **5** (Working, Episodic, Semantic, Procedural, Declarative) + Meta |
| Hybrid retrieval | ✅ (BM25 + vector + graph) | ✅ + RRF + weighted fusion + lexical cross-encoder rerank + query expansion |
| Dreaming / consolidation | ✅ (opt-in) | ✅ (auto-decay, merge, promote, relation discovery) |
| Memory flush | ✅ (pre-compaction) | ✅ + heuristic + LLM-powered extraction |
| Self-healing | ❌ | ✅ APEX diagnosis with auto-repair |
| Self-evolution | ❌ | ✅ Genetic algorithm for weights |
| Knowledge graph | ✅ (MemWiki) | ✅ (petgraph + SQLite + semantic relations) |
| Storage | Markdown + JSON + LanceDB | **SQLite FTS5 + Tantivy BM25 + HNSW + petgraph** |
| Protocol | ClawHub | **MCP 2024-11-05 (JSON-RPC over HTTP)** |
| API | Custom | **REST + MCP + CLI** |
| Implementation | TypeScript | **Pure Rust** (zero-cost abstractions, ~5× faster cold start) |
---
## 🏗️ Architecture
```
┌─────────────────────────────────────────────┐
│ LLM Agent (Claude / GPT / Local Model) │
└──────────┬──────────────────┬───────────────┘
│ tool calls │ ingestion
▼ ▼
┌─────────────────────────────────────────────┐
│ MCP Server / REST API / CLI │
│ (apex_ingest, apex_retrieve, apex_dream,…)│
└──────────┬──────────────────┬───────────────┘
│ │
▼ ▼
┌──────────────────────────────────────────────────────┐
│ Hybrid Retriever │
│ ┌───────────┐ ┌───────────┐ ┌──────────────┐ │
│ │ BM25 │ │ Vector │ │ Graph BFS │ │
│ │ Tantivy │ │ HNSW │ │ petgraph │ │
│ └─────┬─────┘ └─────┬─────┘ └──────┬───────┘ │
│ └──────┬─────────┴──────────────┘ │
│ ▼ │
│ RRF / Weighted-Sum Fusion + Rerank │
└──────────────────────────────────────────────────────┘
│
┌───────────────┴───────────────┐
▼ ▼
┌─────────────┐ ┌─────────────┐
│ Dreaming │ │ APEX │
│ consolidator│ │ doctor │
│ (decay, │ │ (health, │
│ merge, │ │ repair) │
│ promote, │ └─────────────┘
│ relations) │
└─────────────┘
```
---
## 🚀 Quick start
```rust
use apex_mem::{ApexMem, ApexMemConfig, MemoryDimension, MemoryRecord};
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let mem = ApexMem::new(ApexMemConfig::default()).await?;
mem.ingest(MemoryRecord::new(
MemoryDimension::Semantic,
"Rust is a memory-safe systems language with zero-cost abstractions.",
)).await?;
let hits = mem.search("memory safety", 5).await?;
for h in hits { println!("[{:.3}] {}", h.score, h.record.content); }
Ok(())
}
```
### CLI
```bash
# Start the server (REST + MCP on the same port)
cargo run --release -p apex-mem -- serve --bind 127.0.0.1:8765
# Ingest a fact
cargo run --release -p apex-mem -- ingest "Rust is a memory-safe systems language." \
--dimension declarative --tags language --importance 0.9
# Search
cargo run --release -p apex-mem -- search "memory safety" --top-k 5
# Run a dreaming sweep
cargo run --release -p apex-mem -- dream
# Run APEX self-diagnosis
cargo run --release -p apex-mem -- apex
```
### MCP
```bash
# List available tools
curl http://127.0.0.1:8765/mcp/tools
# Call a tool
curl -X POST http://127.0.0.1:8765/mcp/rpc \
-H 'Content-Type: application/json' \
-d '{
"jsonrpc": "2.0",
"id": 1,
"method": "tools/call",
"params": {
"name": "apex_ingest",
"arguments": {
"content": "OpenClaw has 300k+ stars",
"dimension": "declarative",
"importance": 0.7
}
}
}'
```
### REST
```bash
# Ingest
curl -X POST http://127.0.0.1:8765/v1/memories \
-H 'Content-Type: application/json' \
-d '{"content": "Rust is fast", "dimension": "declarative", "importance": 0.7}'
# Search (with expansion + rerank)
curl -X POST http://127.0.0.1:8765/v1/search \
-H 'Content-Type: application/json' \
-d '{"query": "memory safety", "top_k": 5, "expand": true, "rerank": true}'
# Dreaming sweep
curl -X POST http://127.0.0.1:8765/v1/dream
# Stats
curl http://127.0.0.1:8765/v1/stats
```
---
## 🧬 The five memory dimensions
| Dim | Purpose | Example | Default decay |
|---|---|---|---|
| **Working** | Active context, transient | Current conversation turn | 1 hour |
| **Episodic** | Time-stamped events | "On 2026-04-01 the agent ran `cargo build`" | 7 days |
| **Semantic** | Concepts, facts, relations | "Rust is a memory-safe systems language" | 6 months |
| **Procedural** | Skills, methods, procedures | "Procedure: how to compile APEX-MEM" | 1 year |
| **Declarative** | Stable facts, identity | "OpenClaw has 300k+ stars" | 5 years |
---
## 🔧 Embedders
| Provider | Speed | Quality | Setup |
|---|---|---|---|
| `Hashing` (default) | 🚀 instant | good enough for hybrid | none |
| `Remote` (OpenAI-compatible) | 🌐 | high | set `OPENAI_API_KEY` |
| `Candle` (local model) | 🐢 first run, then fast | high | bring your own model id |
Switch by setting the `embedding_provider` field in `ApexMemConfig`.
---
## 🧬 Dreaming
Periodic background sweeps that:
1. **Decay**: exponential decay of all memories based on time since last access.
2. **Merge**: near-duplicate memories (by hash + vector cosine ≥ threshold) collapse.
3. **Promote**: high-value working/episodic memories graduate to durable dimensions.
4. **Discover relations**: recent semantic memories that are vector-similar are linked.
Configure via `DreamingConfig`:
- `sweep_cron` — full nightly sweep (default `0 17 3 * * *`)
- `promote_cron` — incremental promotion (default every 30 min)
- `merge_threshold` — cosine similarity for dedup (default 0.92)
- `promote_threshold` — minimum total score to promote (default 0.55)
---
## 💾 Memory Flush
Run `mem.flush(session_id, messages).await?` before context-window compaction to
extract durable facts into long-term storage. Two modes:
- **Heuristic** (no LLM): lines starting with `*` / `!` / `?` become task /
decision / question records. Good for offline.
- **LLM-powered**: send recent messages to your OpenAI-compatible endpoint
and parse the JSON array of facts.
Auto-flush triggers when working memory exceeds the configured message or
token threshold (see `FlushConfig`).
---
## 🩺 APEX self-healing
Run `mem.apex_diagnose().await?` to get a `MemoryHealth` snapshot including:
- Counts by dimension
- Vector / BM25 / graph sizes
- Detected issues (missing embeddings, duplicate hashes, dangling graph
edges, severely decayed records, working-memory bloat)
- ΔG score in [-1.0, 1.0] (lower = sicker)
With `ApexConfig.auto_repair = true`, the doctor automatically invokes
the consolidator to dedup / promote / repair on the next pass.
---
## 🧬 Self-evolution
`mem.evolve()?` runs a small genetic algorithm that tunes the retrieval
weights and the dreaming thresholds. The best genome is persisted to
SQLite (`dreaming_state` table) and can be replayed at any time.
---
## 🛠️ Workspace
```
apex-mem/
├── Cargo.toml # full heavy deps: tantivy, hnsw_rs, rusqlite+fts5, petgraph
├── src/
│ ├── lib.rs # public API
│ ├── config.rs # ApexMemConfig
│ ├── error.rs # ApexMemError
│ ├── memory/ # 5 dimensions + common + record
│ ├── storage/ # sqlite_store, tantivy_index, vector_store, graph_store
│ ├── embedding/ # hash (default), remote, pooled
│ ├── retrieval/ # hybrid retriever, fusion (RRF / weighted), query_expand, rerank
│ ├── dreaming/ # scheduler, scorer, consolidator
│ ├── flush/ # extractor (LLM + heuristic)
│ ├── apex/ # diagnosis (memory doctor)
│ ├── evolution/ # genetic engine
│ ├── pipeline/ # ingestion + ApexMem orchestrator
│ ├── mcp/ # MCP server + tool registry
│ ├── api/ # REST routes
│ └── cli/ # CLI binary
├── tests/ # end-to-end + unit tests
└── examples/ # basic_usage
```
---
## 📝 License
MIT or Apache-2.0, at your option.
---
*Built with ❤️ by the APEX-AGI team. Faster, stronger, and more principled than OpenClaw's memory system, in 100% Rust.*
Connection Info
You Might Also Like
buddy
Your persistent AI coding companion — the /buddy rescue mission. A...
Vera
Local code search combining BM25, vector similarity, and cross-encoder...
agent-base
Agent Base is a source-level research project on coding agents. It compares...
mitmproxy-mcp
MCP Server that wraps mitmproxy and exposes it as a tool to any MCP client,...
nothumanallowed
NotHumanAllowed — AI Agent Tools, CLI, Documentation & MCP Integration
bouvet
Sandbox for Agents