Skip to content
Back to search

causal-memory

Causal memory layer for AI agents — MCP server that records decision→outcome relationships. Survives compaction.

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/jingxuanc--causal-memory/badge.svg)](/listings/jingxuanc--causal-memory)

HTML

<a href="/listings/jingxuanc--causal-memory"><img src="/api/listings/jingxuanc--causal-memory/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

git clone https://github.com/JingxuanC/causal-memory.git
cd causal-memory
cargo build --release

MCP integration (Claude Code, Cursor, grok-build, etc.)

First-class installers: **Claude Code** (`integrations/claude-code/`) and **Codex CLI** (`integrations/codex/`) — MCP registration + activation prompt/skill in one idempotent script each.

{
  "mcpServers": {
    "causal-memory": {
      "command": "/path/to/causal-memory/target/release/causal-memory",
      "env": {
        "CAUSAL_MEMORY_DB": "~/.local/share/causal-memory/causal.db"
      }
    }
  }
}

No Rust toolchain? `pip install causal-memory` puts the same `causal-memory` console script on your PATH (the full CLI — bare invocation is the stdio MCP server), so `"command": "causal-memory"` works as the MCP entry too.

To teach the agent *when* to use the memory tools (agents don't call them proactively without instruction), install the bundled agent skill [skills/causal-memory/SKILL.md](skills/causal-memory/SKILL.md):

**Guided installer (recommended)** — one command installs the skill, the `causal-memory` server, and the MCP registration across every detected client (Claude Code / Cursor / Opencode / Claude Desktop / Kimi Code):

./install.sh                     # interactive, walks you through each step
./install.sh --yes               # non-interactive, accept all defaults
./install.sh --uninstall         # remove the skill (+ optional MCP)

Or via the Skills CLI, or by hand:

# Skills CLI (skills.sh ecosystem) — works with Claude Code, Cursor,
# Kimi Code CLI, Codex, Copilot and more:
npx skills add JingxuanC/causal-memory@causal-memory

…or copy `skills/causal-memory/` into your agent's skills directory (e.g. `~/.agents/skills/causal-memory/`), or paste [CLAUDE.md](CLAUDE.md) into your system prompt / `AGENTS.md`.

HTTP transport (remote agents, multi-agent shared memory)

./target/release/causal-memory http --port 9938   # MCP Streamable HTTP

Observability endpoints on the same port:

GET /metrics                    Prometheus text (RED + recall metrics)
GET /healthz / /readyz          liveness / readiness (readiness probes the store)
GET /debug/recall?query=...     run a recall now, return the full JSON trace
                                (seeds, hop summary, per-result provenance)
GET /debug/recalls              newest-first recall audit rows (persisted,
                                schema v13 recall_audit table; survives restarts)

`/metrics` and `/debug/*` expose the recall corpus, so they accept opt-in bearer auth: set `CAUSAL_MEMORY_HTTP_AUTH_TOKEN` (env or `causal-memory setconfig`) and they require `Authorization: Bearer <token>` (unset = open, the previous behavior). `/healthz` / `/readyz` stay open on purpose — kubelet probes cannot send bearer headers and leak nothing. `/mcp` client auth is a separate mechanism: per-tenant bearer tokens (see *Multi-tenant HTTP* below). Without the token, do not expose the port to the public internet.

Structured JSON logs on stderr: `CAUSAL_MEMORY_LOG_FORMAT=json`.

Multi-tenant HTTP (per-tenant databases)

Point `CAUSAL_MEMORY_TOKENS_FILE` (env or `causal-memory setconfig`) at a JSON file mapping bearer tokens to tenant names:

{ "token-for-alice": "alice", "token-for-bob": "bob" }

With the file configured and non-empty, `/mcp` requires `Authorization: Bearer <token>`, and each tenant reads and writes its own SQLite store at `<db-dir>/tenants/<tenant>.<fnv1a-hash>.db` — one database per tenant, opened lazily on first request, so one tenant can never see another's facts or causal edges (covered by an end-to-end isolation test). Missing or unknown tokens get `401` and never create a database file. The file is reloaded when its mtime changes, so tenants can be added or revoked without a restart; if the file turns unreadable at runtime the last-good map stays in force (fail closed).

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

.claude-plugin/marketplace.json · Manifest · 20 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.

  1. {
  2. "$schema": "https://anthropic.com/claude-code/marketplace.schema.json",
  3. "name": "causal-memory",
  4. "description": "Persistent causal memory for coding agents — decisions, outcomes, lessons, same-context counterfactuals, and a falsifiable prediction ledger. Shared across Claude Code, Codex, kimi, Hermes, and Python.",
  5. "owner": {
  6. "name": "JingxuanC"
  7. },
  8. "plugins": [
  9. {
  10. "name": "causal-memory",
  11. "description": "Persistent causal memory for Claude Code — decisions, outcomes, and lessons that survive compaction. Same-context counterfactuals (natural experiments), a falsifiable prediction ledger, and an activation skill that teaches when to recall and record.",
  12. "author": {
  13. "name": "JingxuanC"
  14. },
  15. "category": "memory",
  16. "source": "./plugins/claude-code",
  17. "homepage": "https://github.com/JingxuanC/causal-memory"
  18. }
  19. ]
  20. }
README.md · README · 582 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.

  1. # causal-memory
  2. > **An agent memory system with a causal core — and the only one that models inhibition.**
  3. >
  4. > Facts, temporal state, and `decision → outcome` causal edges on one SQLite store,
  5. > powered by a hippocampus-style engine: typed spreading activation (excitatory
  6. > *and* inhibitory), Hebbian co-occurrence reinforcement, Q-value dynamics, and
  7. > immutable SWR consolidation. Agents recall *what* happened, *when* it was true,
  8. > *why* it worked — and *what would happen if* they acted differently.
  9. [![License: Apache-2.0](https://img.shields.io/badge/license-Apache--2.0-blue.svg)](LICENSE)
  10. [![Status: v0.10.0](https://img.shields.io/badge/status-v0.10.0--alpha-orange.svg)](#status)
  11. [![Tests: 368](https://img.shields.io/badge/tests-368-brightgreen.svg)](#build--test)
  12. [![Release: v0.10.0](https://img.shields.io/badge/release-v0.10.0-blue.svg)](https://github.com/JingxuanC/causal-memory/releases)
  13. [![Hermes plugin](https://img.shields.io/badge/hermes-plugin-blue.svg)](hermes-plugin/)
  14. [![DSH plugin](https://img.shields.io/badge/deepseek--harness-plugin-blue.svg)](dsh-plugin/)
  15. **English** · [简体中文](README.zh-CN.md)
  16. ---
  17. ## Why
  18. Every agent forgets *why* it made past decisions after a few context compactions.
  19. It re-fixes the same bug the same wrong way, re-debates the same architecture
  20. choice, relearns the same lesson.
  21. This happens because **causal information is the most fragile type under text
  22. compaction**. Real-LLM benchmark (grok-build's production compaction prompt):
  23. | Compactions (k) | Textual recall | Causal-table recall |
  24. |---|---|---|
  25. | 1 | 100% | 100% |
  26. | 2 | 85% | 100% |
  27. | 3 | 55% | 100% |
  28. | 5 | **45%** | **100%** |
  29. The causal table survives because it lives **outside the agent's context window** —
  30. compaction cannot touch it.
  31. ---
  32. ## Demo
  33. **30-second single scene** — the agent is about to `git push --no-verify`;
  34. `intervention_query` fires a DANGER chain citing the lesson it recorded last
  35. time ("production login failed for 40 minutes; emergency rollback"):
  36. <!-- GitHub's CSP (media-src) only allows GitHub-hosted media, so an
  37. external <video> never plays on the repo page. An animated GIF goes
  38. through the camo image proxy and plays inline. Click for the mp4. -->
  39. [![30-second danger-warning demo](docs/demo/causal-memory-danger-30s.gif)](docs/demo/causal-memory-danger-30s.mp4)
  40. [Download video](docs/demo/causal-memory-danger-30s.mp4) ·
  41. [DANGER-scene screenshot](docs/demo/demo30_danger.png) ·
  42. Regenerate: `scripts/capture_demo30.py` → `scripts/render_demo30.py`
  43. A 21-second hands-on demo (real memory store, no mocks): pre-action warning
  44. (`intervention_query` → DANGER chain) → experience recall (`search_causal`)
  45. → counterfactual comparison (`counterfactual_query`) → write loop
  46. (`record_decision` → immediately searchable).
  47. [![21-second demo](docs/demo/causal-memory-demo.gif)](docs/demo/causal-memory-demo.mp4)
  48. [Download video](docs/demo/causal-memory-demo.mp4) ·
  49. [Warning-scene screenshot](docs/demo/demo_intervention.png) ·
  50. [Brand card](docs/demo/demo_card.png) ·
  51. Regenerate: `scripts/render_demo.py`
  52. ---
  53. ## Benchmarks
  54. ### CausalEval — the causal memory benchmark (primary)
  55. Most agent-memory benchmarks (LoCoMo, LongMemEval, Memora) test **fact recall**
  56. ("what is the user's preference"). causal-memory's differentiators — typed
  57. causal edges, inhibition, intervention prediction, cross-task transfer — are
  58. invisible on those suites. **CausalEval** measures them.
  59. **Design: the causal graph is the answer key.** Typed DAGs are generated
  60. deterministically; conversations are narrated from the graph; gold answers are
  61. derived from graph structure — zero hand annotation, zero ambiguity.
  62. **CausalEval v13 (soft supersession) — 140 questions, 20 graphs** (same LLM,
  63. same judge; v12 baseline was 70q/10 graphs; mem0 comparison ran on the 70q
  64. protocol):
  65. | Capability | causal-memory | v12 (70q) | mem0 (70q) | What it tests |
  66. |---|---|---|---|---|
  67. | **C7 Update** | **100%** | 50% | 80% | Supersede old belief after falsification (soft `superseded_by` annotation) |
  68. | C3 Counterfactual | **95%** | 90% | 80% | Choosing between alternatives with known outcomes |
  69. | C2 Intervention | **75%** | 70% | 40% | Forward prediction: "if X again, what happens?" |
  70. | C4 Inhibition | **80%** | 90% | 50% | Distinguishing root-cause fix vs blast-radius limiter (`prevented` edges) |
  71. | C1 Attribution | 85% | 90% | 90% | Backward causal chain → root cause |
  72. | C5 Temporal-causal | 90% | 100% | 90% | Ordering on a causal chain |
  73. | C6 Lesson transfer | 20% | 20% | 30% | Cross-task analogy via meta edges (open limitation) |
  74. | **Overall** | **78%** | 81% | 65% | |
  75. **Key result: C7 update 50% → 100% (+50pp, 20/20 questions) and it holds at
  76. doubled sample size.** Soft supersession annotates superseded edges
  77. (`superseded_by`) instead of hiding them — the falsification signal reaches
  78. the answer model while the old lesson stays retrievable for counterfactuals
  79. (C3 unharmed at 95%). The C6 gap (20% vs mem0 30%) is the remaining open
  80. limitation; C1/C4/C5 dips vs v12 are within re-distillation variance and
  81. new-graph difficulty (v12 and v13 do not share a distilled corpus).
  82. ### Fact-recall benchmarks (not our strong suit)
  83. On traditional fact-recall suites, causal-memory performs competitively but
  84. **does not beat mem0** — this is expected, because fact recall is mem0's
  85. specialty and not where causal-memory adds value.
  86. | Benchmark | causal-memory | mem0 | Note |
  87. |---|---|---|---|
  88. | LoCoMo (strict judge) | 79.1% | 91.6% | mem0's home turf |
  89. | LongMemEval-S (full pipeline, deepseek-chat) | **76.4%** @ 11.5K tok/q | 94.4% @ 6.8K tok/q (official) · 73.8% (ind. repro) | single-model stack vs platform stack; see docs/benchmarks/longmemeval.md |
  90. | Memora MPA | 67.4% | 71.8% | −4.4pp |
  91. | Compaction survival | 100% | 45% | External table = immune to compaction |
  92. | Agent repeat-mistake | 33% | 67% | −34pp on trap-world |
  93. ### Capability tests (322 across the workspace)
  94. These test capabilities that **no fact store (mem0, Zep, Letta) can offer**.
  95. | Capability | What it proves | Tests |
  96. |---|---|---|
  97. | **Prevented-edge warning** | `prevented` edge spreads −0.3 activation (GABA analogue) | 2 |
  98. | **Trace-cause attribution** | Backward CSR traversal finds root cause | 2 |
  99. | **Multi-hop causal chain** | Forward K-hop spreading reaches 2-3 hop outcomes | 2 |
  100. | **Inhibitory filtering** | Prevented outcomes appear as negative, not false positives | 1 |
  101. | **Intervention comparison** | Same outcome has +0.9 for "skip tests" and −0.3 for "add tests" | 4 |
  102. | **SWR consolidation** | LTP strengthens replayed edges, LTD weakens unvisited, GC forgets dormant | 5 |
  103. | **Q-value dynamics** | Good decisions rank higher; Bellman propagates to parents | 3 |
  104. | **Novelty entropy** | Diverse experience triggers consolidation; uniform does not | 3 |
  105. | **Meta-edge mining** | Cross-session pattern discovery (similar_to / repeated) | 3 |
  106. | **Hebbian co-occurrence** | Repeated co-activation strengthens connection | 3 |
  107. ---
  108. ## What makes it different
  109. | Capability | causal-memory | mem0 | Zep | Letta | HeLa-Mem |
  110. |---|---|---|---|---|---|
  111. | Typed causal semantics (caused/enabled/prevented) | ✅ | ❌ | ❌ | ❌ | ❌ |
  112. | **prevented negative spread (inhibitory)** | ✅ | ❌ | ❌ | ❌ | ❌ |
  113. | Hebbian co-occurrence edges (excitatory) | ✅ | ❌ | ❌ | ❌ | ✅ |
  114. | Immutable consolidation (delta + clone) | ✅ | ❌ | ❌ | ❌ | ❌ |
  115. | Q-value dynamic utility | ✅ | ❌ | ❌ | ❌ | ❌ |
  116. | Forward simulation (intervention_query) | ✅ | ❌ | ❌ | ❌ | ❌ |
  117. | SWR offline consolidation (LTP/LTD/GC) | ✅ | ❌ | ❌ | ❌ | ❌ |
  118. | Novelty-entropy consolidation trigger | ✅ | ❌ | ❌ | ❌ | ❌ |
  119. | Meta-edge cross-session pattern mining | ✅ | ❌ | ❌ | ❌ | ❌ |
  120. | Compaction survival evidence | ✅ +20.8pp | ❌ | ❌ | ❌ | ❌ |
  121. | One graph unifying all memory types | ✅ | ❌ | ⚠️ | ❌ | ⚠️ |
  122. | Write-time gatekeeping (raw → session_logs) | ✅ | ✅ | ❌ | ❌ | ❌ |
  123. | Local ONNX embedding (offline) | ✅ | ✅ | ❌ | ❌ | ❌ |
  124. **Core innovation: the excitatory/inhibitory duality.** HeLa-Mem (ACL 2026) builds
  125. the excitatory side (Hebbian co-activation, positive spread). causal-memory adds
  126. the inhibitory side (`prevented` edges spread **negative** activation — a GABA
  127. analogue). A complete memory needs both: "what caused this" *and* "what prevents
  128. this from happening again."
  129. ---
  130. ## Architecture
  131. ![architecture](docs/architecture.png)
  132. *Interactive version: [docs/architecture.html](docs/architecture.html)*
  133. ```
  134. ┌───────────────────────────────────────────────┐
  135. │ causal-memory (Rust, MCP) │
  136. │ │
  137. │ 14 tools ← Agent (stdio / HTTP) │
  138. │ ↓ │
  139. │ Write-time gatekeeping │
  140. │ raw turns → session_logs (audit only) │
  141. │ distill → facts + causal edges (searchable) │
  142. │ ↓ │
  143. │ Unified retrieval (RRF fusion) │
  144. │ BM25 + semantic cosine → RRF merge │
  145. │ Fact layer (BM25 + embeddings) │
  146. │ ↓ │
  147. │ ┌──── Hippocampus engine ──────────────────┐ │
  148. │ │ CSR graph + spreading activation │ │
  149. │ │ caused (+1.0) enabled (+0.5) │ │
  150. │ │ prevented (−0.3) ← GABA inhibitory │ │
  151. │ │ fact (+0.8) meta (+0.6) │ │
  152. │ │ co_occurrence (Hebbian, dynamic) │ │
  153. │ │ │ │
  154. │ │ DG: SimHash pattern separation │ │
  155. │ │ CA3: K-hop spreading (forward + reverse) │ │
  156. │ │ CA1: Novelty entropy trigger │ │
  157. │ │ SWR: LTP/LTD/GC (immutable delta + clone) │ │
  158. │ │ Q-value: Bellman dynamics (MemRL-style) │ │
  159. │ └────────────────────────────────────────────┘ │
  160. │ ↓ │
  161. │ SQLite (causal.db) — never compacted │
  162. └───────────────────────────────────────────────┘
  163. ```
  164. The `causal_edges` table is never compacted — it lives outside the agent's context
  165. window. That's the entire point.
  166. ---
  167. ## Edge types
  168. | Edge type | Spread coeff | Biological analogue | Meaning |
  169. |---|---|---|---|
  170. | `caused` | +1.0 | Glutamate (strong excitatory) | "Doing X caused Y" |
  171. | `fact` | +0.8 | Semantic association | "User is/has Z" |
  172. | `meta` | +0.6 | Cortical top-down | Cross-task pattern link |
  173. | `enabled` | +0.5 | Weak excitatory | "Doing X enabled Y" |
  174. | `co_occurrence` | dynamic | Hebbian LTP | "X and Y frequently co-occur" |
  175. | **`prevented`** | **−0.3** | **GABA (inhibitory)** | **"Doing X prevented Y"** |
  176. | `no_effect` | 0.0 | — | No causal relationship |
  177. ---
  178. ## Quick start
  179. ```bash
  180. git clone https://github.com/JingxuanC/causal-memory.git
  181. cd causal-memory
  182. cargo build --release
  183. ```
  184. ### MCP integration (Claude Code, Cursor, grok-build, etc.)
  185. First-class installers: **Claude Code** (`integrations/claude-code/`) and
  186. **Codex CLI** (`integrations/codex/`) — MCP registration + activation
  187. prompt/skill in one idempotent script each.
  188. ```json
  189. {
  190. "mcpServers": {
  191. "causal-memory": {
  192. "command": "/path/to/causal-memory/target/release/causal-memory",
  193. "env": {
  194. "CAUSAL_MEMORY_DB": "~/.local/share/causal-memory/causal.db"
  195. }
  196. }
  197. }
  198. }
  199. ```
  200. No Rust toolchain? `pip install causal-memory` puts the same `causal-memory`
  201. console script on your PATH (the full CLI — bare invocation is the stdio MCP
  202. server), so `"command": "causal-memory"` works as the MCP entry too.
  203. To teach the agent *when* to use the memory tools (agents don't call them
  204. proactively without instruction), install the bundled agent skill
  205. [skills/causal-memory/SKILL.md](skills/causal-memory/SKILL.md):
  206. **Guided installer (recommended)** — one command installs the skill, the
  207. `causal-memory` server, and the MCP registration across every detected client
  208. (Claude Code / Cursor / Opencode / Claude Desktop / Kimi Code):
  209. ```bash
  210. ./install.sh # interactive, walks you through each step
  211. ./install.sh --yes # non-interactive, accept all defaults
  212. ./install.sh --uninstall # remove the skill (+ optional MCP)
  213. ```
  214. Or via the Skills CLI, or by hand:
  215. ```bash
  216. # Skills CLI (skills.sh ecosystem) — works with Claude Code, Cursor,
  217. # Kimi Code CLI, Codex, Copilot and more:
  218. npx skills add JingxuanC/causal-memory@causal-memory
  219. ```
  220. …or copy `skills/causal-memory/` into your agent's skills directory
  221. (e.g. `~/.agents/skills/causal-memory/`), or paste [CLAUDE.md](CLAUDE.md)
  222. into your system prompt / `AGENTS.md`.
  223. ### HTTP transport (remote agents, multi-agent shared memory)
  224. ```bash
  225. ./target/release/causal-memory http --port 9938 # MCP Streamable HTTP
  226. ```
  227. Observability endpoints on the same port:
  228. ```
  229. GET /metrics Prometheus text (RED + recall metrics)
  230. GET /healthz / /readyz liveness / readiness (readiness probes the store)
  231. GET /debug/recall?query=... run a recall now, return the full JSON trace
  232. (seeds, hop summary, per-result provenance)
  233. GET /debug/recalls newest-first recall audit rows (persisted,
  234. schema v13 recall_audit table; survives restarts)
  235. ```
  236. `/metrics` and `/debug/*` expose the recall corpus, so they accept opt-in
  237. bearer auth: set `CAUSAL_MEMORY_HTTP_AUTH_TOKEN` (env or
  238. `causal-memory setconfig`) and they require
  239. `Authorization: Bearer <token>` (unset = open, the previous behavior).
  240. `/healthz` / `/readyz` stay open on purpose — kubelet probes cannot send
  241. bearer headers and leak nothing. `/mcp` client auth is a separate
  242. mechanism: per-tenant bearer tokens (see *Multi-tenant HTTP* below).
  243. Without the token, do not expose
  244. the port to the public internet.
  245. Structured JSON logs on stderr: `CAUSAL_MEMORY_LOG_FORMAT=json`.
  246. #### Multi-tenant HTTP (per-tenant databases)
  247. Point `CAUSAL_MEMORY_TOKENS_FILE` (env or `causal-memory setconfig`) at a
  248. JSON file mapping bearer tokens to tenant names:
  249. ```json
  250. { "token-for-alice": "alice", "token-for-bob": "bob" }
  251. ```
  252. With the file configured and non-empty, `/mcp` requires
  253. `Authorization: Bearer <token>`, and each tenant reads and writes its own
  254. SQLite store at `<db-dir>/tenants/<tenant>.<fnv1a-hash>.db` — one database
  255. per tenant, opened lazily on first request, so one tenant can never see
  256. another's facts or causal edges (covered by an end-to-end isolation test).
  257. Missing or unknown tokens get `401` and never create a database file. The
  258. file is reloaded when its mtime changes, so tenants can be added or revoked
  259. without a restart; if the file turns unreadable at runtime the last-good
  260. map stays in force (fail closed).
  261. Unset (or an empty/unreadable file) keeps the previous behavior: no `/mcp`
  262. auth, one shared store — local and stdio usage are unaffected. The startup
  263. log states the mode: `auth=multi-tenant (N tokens)` vs `auth=open`.
  264. Memory residency: every active tenant holds its own `CausalStore` and
  265. in-memory graph, so RSS grows with the tenant count — see
  266. [docs/design/enterprise-scaling.md](docs/design/enterprise-scaling.md)
  267. before packing many tenants into one process. The observability endpoints
  268. (`/metrics`, `/debug/*`) keep reporting on the default store and are still
  269. gated by `CAUSAL_MEMORY_HTTP_AUTH_TOKEN`, independently of tenant auth.
  270. ### With local embeddings (no API key needed)
  271. ```bash
  272. cargo build --release --features local-embed
  273. # Uses BAAI/bge-small-en-v1.5 (384 dims, ~130MB, downloads once then offline)
  274. ```
  275. ### With HTTP embeddings (OpenAI/ZhiPu/etc.)
  276. ```bash
  277. export CAUSAL_MEMORY_EMBED_API=https://open.bigmodel.cn/api/paas/v4
  278. export CAUSAL_MEMORY_EMBED_KEY=your-key
  279. export CAUSAL_MEMORY_EMBED_MODEL=embedding-3
  280. ```
  281. ### Python bindings (PyO3)
  282. All 14 memory operations are also available as a Python package, built on the
  283. same `causal_memory::memory::Memory` facade the MCP server uses:
  284. ```bash
  285. cd crates/causal-memory-py
  286. pip install maturin
  287. maturin develop # builds and installs into the active venv
  288. ```
  289. ```python
  290. from causal_memory import CausalMemory
  291. mem = CausalMemory("~/.local/share/causal-memory/causal.db") # or CausalMemory.in_memory()
  292. mem.record_decision("used Redis mutex for cache stampede protection",
  293. "deadlock under load", "caused", "concurrency",
  294. context="go 1.22, single redis, 5k rps")
  295. print(mem.search_causal(query="cache stampede protection"))
  296. print(mem.intervention_query("skip the test suite before shipping"))
  297. ```
  298. Methods mirror the 17 MCP tools one-to-one and return the same text. Embedding
  299. and LLM features use the same `CAUSAL_MEMORY_EMBED_*` / `CAUSAL_MEMORY_LLM_*`
  300. environment variables; without them the bindings degrade gracefully to
  301. BM25-only retrieval. Smoke tests: `maturin develop && pytest tests/`.
  302. > **macOS note:** always build the bindings through maturin. Plain
  303. > `cargo build -p causal-memory-py --release` fails to link — the Xcode CLT
  304. > Python ships no `libpython3.9` dylib (this is why the py crate sits outside
  305. > the workspace `default-members`).
  306. ---
  307. ## Integrations
  308. ### Hermes memory provider
  309. [hermes-plugin/](hermes-plugin/) turns causal-memory into a drop-in Hermes
  310. `MemoryProvider` — flat facts + decision→outcome causal lessons on one local
  311. SQLite store, per-profile by construction
  312. (`<hermes_home>/causal-memory/causal.db`). Wired hooks: system-prompt causal
  313. directory, budgeted prefetch recall, non-blocking `sync_turn` write-behind,
  314. and a `hermes causal-memory stats` CLI. Because the store lives outside the
  315. context window, Hermes compaction can't touch it. Install and configuration:
  316. [hermes-plugin/README.md](hermes-plugin/README.md).
  317. ### DeepSeek Harness (DSH) native plugin
  318. [dsh-plugin/](dsh-plugin/) mounts all 16 causal-memory tools onto DSH's
  319. `ctx.tools` with clean names (no `mcp__` prefix) and injects a system-prompt
  320. block telling the model when to consult the causal store. Zero runtime
  321. dependencies — JSON-RPC over stdio straight to the causal-memory binary.
  322. One-line install: `dsh plugin --profile web add "$PWD/dsh-plugin"` (needs the
  323. `causal-memory` binary — `pip install causal-memory`, or a repo
  324. `cargo build --release`).
  325. Details: [dsh-plugin/README.md](dsh-plugin/README.md).
  326. ---
  327. ## Seventeen MCP tools
  328. | Tool | When to call | What it does |
  329. |---|---|---|
  330. | `record_decision` | After acting on a decision | Logs `decision → outcome` as a causal edge with relation type; optional `context` records the world state — same task_tag + context becomes a comparable branch (fork) |
  331. | `remember` | After any meaningful exchange | Zero-friction alternative: paste conversation text, LLM auto-extracts facts/lessons/causal edges |
  332. | `search_causal` | Before a non-trivial decision | BM25 + semantic retrieval of past causal episodes |
  333. | `record_fact` | When learning a stable fact | Records flat facts with scope + confidence; idempotent |
  334. | `search_facts` | When you need "what is" info | BM25 + semantic retrieval over the fact layer |
  335. | `search_memory` | When unsure which type | Unified: facts + causal lessons fused by RRF |
  336. | `trace_cause` | When something fails | Single-hop reverse: which decision caused this outcome |
  337. | `trace_cause_chain` | Deep failure analysis | Multi-hop backward traversal through the causal graph |
  338. | `invalidate_decision` | When a lesson is wrong | Soft-invalidate (hidden from search, kept for audit) |
  339. | `invalidate_pattern` | When a mined pattern is wrong | Soft-invalidate a meta edge (the #N handle from search_patterns) |
  340. | `resolve_updates` | After contradicting outcomes | LLM-judged supersession pass over diverged repeated decisions |
  341. | `search_patterns` | To recall cross-task lessons | Mined meta edges: similar_to / repeated / contradicts / refines |
  342. | `causal_directory` | Pinned in system prompt | L0 compact pointer list of what the agent knows |
  343. | `intervention_query` | **Before taking an action** | Forward simulation: predicts outcomes (safe/warning/danger) |
  344. | `counterfactual_query` | When choosing between options | Contrastive: compares recorded outcomes of two alternatives; renders same-context branches (natural experiments) when they exist; every verdict logs a falsifiable prediction |
  345. | `prediction_report` | Periodic calibration check | Prediction-ledger accuracy overall / per method / per task_tag + pending list |
  346. | `reconstruct_lesson` | When you want the distilled lesson | Reconstructive retrieval: Markov-blanket subgraph → coherent narrative, with optional N-way calibration |
  347. ---
  348. ## Sleep consolidation
  349. ```bash
  350. causal-memory sleep --dry-run # preview what would change
  351. causal-memory sleep # run consolidation cycle
  352. ```
  353. Immutable SWR 2.0: produces a delta + clone (original graph untouched), with full
  354. audit log. Triple-criterion GC (weak AND dormant AND zero-access). Triggers
  355. automatically when novelty entropy exceeds threshold.
  356. ---
  357. ## Causal distill pipeline
  358. The distiller extracts structured memories from raw conversations:
  359. ```
  360. Raw conversation → V3 extraction prompt (130 lines, 6 rules, 5 few-shot)
  361. ↓
  362. Fact/Preference → agent_facts table (BM25 + embedding searchable)
  363. Lesson/Event → causal edges (self-referential, searchable)
  364. Causal → proper directed edge: decision → outcome
  365. with relation type (caused/enabled/prevented)
  366. ```
  367. Raw turns go to `session_logs` (audit/replay only) — they never enter the
  368. retrieval pool. This write-time gatekeeping keeps BM25 precision high.
  369. ---
  370. ## System layer coverage
  371. All 16 designed layers have end-to-end validation (322 workspace tests):
  372. | Layer | Benchmark | Tests |
  373. |---|---|---|
  374. | Fact layer | Memora / LoCoMo | — |
  375. | Causal edges (caused/enabled/prevented) | Capability | 12 |
  376. | Hippocampus spreading activation | Capability | — |
  377. | SWR consolidation (LTP/LTD/GC) | Longitudinal | 5 |
  378. | Q-value dynamics | Longitudinal | 3 |
  379. | Novelty entropy trigger | Longitudinal | 3 |
  380. | Sleep-wake cycle | Longitudinal | 1 |
  381. | Meta-edge pattern mining | Advanced | 3 |
  382. | Co-occurrence Hebbian | Advanced | 3 |
  383. | Intervention query (forward sim) | Advanced | 4 |
  384. | Trace cause chain | Capability | 2 |
  385. | Inhibitory ablation | Inhibition | 2 |
  386. | Distill / retrieval / facts | Memora / LoCoMo / LME | — |
  387. | Compaction survival | Compact | — |
  388. | Agent trap-world | Agent | — |
  389. | Pipeline e2e | Migration / Pipeline | 2 |
  390. ---
  391. ## Build & test
  392. ```bash
  393. cargo build --release # Build binary
  394. cargo test --workspace --no-fail-fast # Run 322 tests
  395. cargo test --features local-embed # Run with ONNX embedding tests
  396. cargo clippy --workspace -- -D warnings # Lint
  397. ```
  398. ## Agent Memory Challenge (AMC/01)
  399. causal-memory enters the [Agent Memory Leaderboard](https://agentmemories.ai/competition/)
  400. first evaluation cycle via an Add/Search integration server — a thin HTTP
  401. frontend over the same `Memory` facade the MCP server runs (BM25 + semantic +
  402. entity retrieval, RRF-fused; one store per `user_id`):
  403. ```bash
  404. cargo build --release --bin causal-memory-amc
  405. ./target/release/causal-memory-amc --db-dir amc_data --port 8787 --write-mode raw
  406. # --write-mode raw (no LLM, platform default) | distill (write-time LLM extraction)
  407. # POST /add (store memory, user_id-isolated) · POST /search (ordered evidence) · GET /health
  408. ```
  409. Docker route: `docker build -t causal-memory-amc . && docker run -p 8787:8787 -v amc-data:/data causal-memory-amc`.
  410. Submission details, method description, and the participation checklist live in
  411. [`docs/benchmarks/amc-2026.md`](docs/benchmarks/amc-2026.md).
  412. Test suite breakdown:
  413. - **186** library unit tests (types, store, distill, patterns, hippocampus)
  414. - **45** library integration tests (capability, longitudinal, advanced, pipeline)
  415. - **91** CLI, benchmark-harness & MCP e2e tests
  416. ---
  417. ## Research background
  418. Full documentation map: [`docs/README.md`](docs/README.md) — design docs,
  419. benchmark protocols, evaluation reports, paper drafts, and the literature
  420. survey.
  421. This project is the engineering output of 17 research notes on agent memory
  422. architecture ([insights/01-17](https://github.com/JingxuanC/agent-teardown/tree/main/insights)),
  423. a teardown of 7 production agent frameworks, and deep analysis of 10+ memory
  424. research papers. Key references:
  425. - **HeLa-Mem** (ACL 2026) — Hebbian spreading activation (our closest competitor; we add the inhibitory side)
  426. - **Anthropic Dreams API** — immutable consolidation pattern (aligned in SWR 2.0)
  427. - **mem0** — write-time gatekeeping architecture (adopted: session_logs separation)
  428. - **MemRL** (arXiv:2601.03192) — Q-value memory dynamics (implemented)
  429. - **Graph World Models** — causal-memory maps to "Graph as Reasoner"
  430. ---
  431. ## Status
  432. **v0.10.0 — alpha.**
  433. What works (16/16 layers with end-to-end validation):
  434. - ✅ 17 MCP tools (stdio + HTTP transport)
  435. - ✅ Write-time gatekeeping (session_logs separation, V3 distill prompt)
  436. - ✅ BM25 + semantic RRF unified retrieval
  437. - ✅ Hippocampus engine: CSR spreading activation, DG SimHash, CA1 novelty, SWR 2.0
  438. - ✅ 7 edge types: caused/enabled/prevented/fact/meta/co_occurrence/no_effect
  439. - ✅ Causal distill: extracts typed causal edges (caused/enabled/prevented) from conversations
  440. - ✅ Hebbian co-occurrence reinforcement
  441. - ✅ Q-value Bellman dynamics
  442. - ✅ Novelty-entropy consolidation trigger + sleep-wake cycle
  443. - ✅ Meta-edge cross-session pattern mining
  444. - ✅ Forward simulation (intervention_query) with prevented-edge warnings
  445. - ✅ Benchmark harnesses: LoCoMo, LongMemEval, Memora, CausalEval, compaction, agent ablation, capability, longitudinal, advanced, extraction calibration, adversarial injection
  446. - ✅ C7 LLM update-resolver (resolve-updates CLI + sleep stage 1.7 supersession)
  447. - ✅ Vela-style half-life decay tiers (90d / 7d / legacy 0.99-per-day)
  448. - ✅ Multi-session multi-pass retrieval (LongMemEval multi-session 42.9% → 57.9%, same-codebase)
  449. - ✅ PyO3 Python bindings (crates/causal-memory-py)
  450. - ✅ Hermes memory-provider plugin (hermes-plugin/)
  451. - ✅ DSH native plugin (dsh-plugin/) + architecture visualization (docs/architecture.html)
  452. - ✅ 368/368 tests passing + clippy clean
  453. What's not done yet:
  454. - ❌ TS bindings
  455. - ❌ Forward-simulation prediction-accuracy benchmark (designed, not yet run)
  456. - ❌ 7×24 production deployment validation
  457. ## License
  458. Apache-2.0. See [LICENSE](LICENSE).

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.