
A ground-up Rust rebuild of my personal long-term memory system for Claude Code — local-LLM fact extraction, hybrid recall, an interactive memory graph, and overhead-free savings metrics, all in one self-contained daemon.
MIT licensed · runs entirely on the machine it grows on · no network at runtime
v1 is complete and in daily use. Every acceptance criterion is met, the legacy Python system was shut down on 2026-08-21, and this is the only memory system wired to Claude Code on my machine. Status, phases and cutover gates →
An AI coding assistant starts every session amnesiac. It re-reads the same files, re-derives the same conclusions, and asks you things you settled last week. MemGarden is the layer that stops that: conversations are captured automatically, distilled into facts by a local LLM, linked to each other, and served back — in about seven milliseconds — as the handful of memories that matter for the prompt you just typed.
The name is the design. Memory here is not a bucket you throw things into; it is tended. Sessions rain down through hooks. Facts take root in per-project banks. Consolidation prunes duplicates and grafts observations into knowledge. What a later fact contradicts is pulled rather than left to compete. A ledger keeps honest books on what the garden actually yields. Nothing leaves the machine it grows on.
Claude Code hooks (Rust subcommands, 0.85ms per turn — budget 10ms)
│ raw transcript / query
▼
memgardend (axum, :9100) ──────── web UI (dashboard + graph viewer)
├─ retain: caps → <private> stripped → chunk → Ollama extraction → facts + links
│ └─ task ledger: the bank's working state, written but not yet read
├─ recall: FTS5 BM25 + sqlite-vec KNN + graph + temporal → RRF → token budget
│ (retracted and expired facts filtered out in one place)
├─ embeddings in-binary (bge-small, 384-dim, CPU) · consolidate · reflect
└─ metrics: lock-free atomics (88ns/request) + benefit ledger
▼
single SQLite file (WAL, STRICT) — vec0 vectors + FTS5 + graph tables
One binary, one file, zero external processes. A backup is cp memgarden.db. Extraction runs on your own Ollama; embeddings and reranking are compiled in and run on CPU so they never fight the LLM for VRAM. There is no cloud path to accidentally enable.
Design decisions, and why this was rebuilt rather than patched →
Measured on one machine (Ryzen 7 9800X3D, release build) and traceable to a design note. Absolute latencies drift ±1.5ms between runs of identical bits, so paired deltas are the trustworthy figures.
| measured | budget | |
|---|---|---|
| recall, idle | 7.1ms p50 / 7.8ms p95 — 3,000 nodes, all four arms | ≤35 / ≤60ms |
| recall, under concurrent ingest | 19.6ms p50 / 48.8ms p95 while ~35,700 nodes load | ≤35 / ≤60ms |
| hooks, whole turn | 0.845ms p50 (recall + retain) |
<10ms |
| cost of measuring | 88ns per request — 0.00025% of the SLO | zero added latency |
| input-cap savings | −86.9% on a 5.8MB transcript’s first retain, −75.3% on a tool-heavy fixture; ~0% on per-turn retains in the default text mode (why) | −55…−87% |
| embedding | 2.41ms p50 single · 26.2s for a 2,718-node corpus | — |
The legacy Python hooks cost 33ms on their disabled path — more to do nothing than these cost to work.
Recall quality is measured against a frozen 2,718-fact corpus with 20 graded queries, so a ranking change reports a delta instead of a feeling. It has already paid for itself: the embedded reranker looked like a win until a temporal bug was fixed, after which it showed +0.013 nDCG@10 with recall@10 going 0.044 negative — which is why it ships off.
Every number, per-arm, with conditions and caveats →
Against the Python system it replaced: 13 better / 5 worse / 1 equivalent on a blind recall-quality panel, 7.1ms instead of ~51ms, and 0.845ms of hook per turn against a disabled path that cost 33ms.
On its own terms the record is mixed, and the losses are in the repository next to the wins:
Those four agree on one thing: the value measured so far is retrieval, not storage. It surfaces the paragraph of yours that answers the question — including, once, a line in book/src/roadmap.md that reopened a month-old crash investigation because nobody was going to grep for it.
The tier above raw facts has since been measured and repaired: distillation is worth +27% recall@10, and mental models — which had never once run, because every call failed on a grammar limit and nothing called them anyway — now run on four. The store also learned to retire a fact, so a superseded memory stops reaching the synthesiser at all. Noticing a retraction automatically is the part that does not work: the detector found 2 of 3 targets and 22 things that were not retractions, and ships off.
Every one of those stores what was true. What none of them holds is what is being worked on right now — the open goal, what is done, what is blocked, the next action — so a session resuming after a break gets similar facts and no answer to “where was I”. Schema v12 adds that tier as a task ledger, one row per bank, and nothing reads it yet: the rows accumulate so their content can be judged before any of it is injected. Given that memory lost 11–7 on substitution, “the extractor writes something worth injecting” is a claim to check, not to assume.
The full analysis, with what is still unmeasured →
Requires Rust and a running Ollama with an extraction model (default qwen3-14b-nothink, a 16 GB card; 12 GB and 8 GB options in What GPU it needs).
cargo install --path crates/memgardend --bin memgardend # the daemon
cargo install --path crates/memgarden-cli --bin memgarden # the hook binary
cp config.example.toml ~/.config/memgarden/config.toml # env overrides: MEMGARDEN_*
memgardend # 127.0.0.1:9100
Wire it into Claude Code. Installing turns nothing on — the default install wires all four events in shadow mode: real daemon calls, real latency, nothing reaches the model. Flip [hooks] mode = "full" in config.toml when you want injection, and back to "shadow" to roll it back in one line.
memgarden hooks install --dry-run # print the exact lines, write nothing
memgarden hooks install # shadow mode
memgarden hooks status # what is wired per event, daemon health, poisoned sessions
memgarden hooks uninstall # restores settings.json to its pre-install bytes
settings.json is edited by line splice and never reserialized, so uninstall restores it byte for byte — a serde_json round-trip would silently re-sort every key in a file shared with other tools. And the hook can never exit 2, because on UserPromptSubmit exit 2 erases what you typed: no clap, no ? out of main, and a panic hook that exits 0 with empty stdout.
The web UI is at http://127.0.0.1:9100/ui/ — dashboard, benefit ledger, and the memory graph.
Coming from the old Python system? Only then: migration runbook. A fresh install skips it and just lets the bank fill.
The hot path never touches the GPU. Recall, embeddings and reranking run on CPU and finish in milliseconds. The card serves one thing — the local extraction model behind Ollama — and only in the background: fact extraction after a session, the task ledger, consolidation, mental-model refresh. On this machine that is about a hundred calls a day, nothing waits on any of them, and the card sits idle in between. So it does not have to be your GPU. The spare in the second slot, or the card you just replaced, is the right home for it.
Measured with Ollama 0.21 at an 8,192-token context (the largest window the
daemon ever requests), q8_0 KV cache, flash attention, every layer on the
card. “VRAM” is what ollama ps reports after a warm load; nvidia-smi reads
about 0.5 GB more for the driver context.
| Card | Model | Weights on disk | VRAM in use | Status |
|---|---|---|---|---|
| 16 GB | qwen3-14b-nothink (Qwen3-14B Q6_K), the default |
11.3 GB | 12.2 GB | validated — every number in this README came from it |
| 12 GB | Qwen3-14B Q5_K_M (hf.co/bartowski/Qwen_Qwen3-14B-GGUF:Q5_K_M) |
9.8 GB | 10.7 GB | same model, smaller quant; 1.3 GB to spare |
| 8 GB | qwen3:8b (Qwen3-8B Q4_K_M) |
4.9 GB | 5.6 GB | fits — and measured short: 17 vs 29 recall hits on the same 15 questions, worse on 9 of 15. It keeps what things are and drops what was decided. 12 GB is the practical minimum. |
The 8 GB measurement is docs/evidence/extraction-8b-result.md: the 8B never
malformed a reply and ran three times faster, and still lost two of every
three questions about conclusions.
Two settings decide whether a card fits. OLLAMA_KV_CACHE_TYPE=q8_0 halves
the KV cache — the 14B’s is 0.7 GB at 8k tokens quantized, 1.4 GB at Ollama’s
f16 default — and the daemon never asks for more than 8,192 tokens of context,
so a larger num_ctx in the Modelfile only spends VRAM. The model is one line
in config.toml: [ollama] model = "qwen3:8b".
If the card disappears — a driver that no longer matches the kernel, Secure
Boot refusing the DKMS module — Ollama falls back to CPU silently. Recall is
unaffected. Extraction slows about 15× (0.25 → 3.8 minutes per chunk,
measured on a Ryzen 9800X3D) and consolidation rounds stop finishing inside
their deadline. The daemon says so in three places: /healthz turns
DEGRADED with ollama: cpu-only (the prober reads /api/ps every 30 s) or
failing (a call exhausted its retries; ollama_last_error has the reason);
every settled retain job records the path it ran on in its detail
("inference"); and the recall hook shows one warning line in Claude Code
per session. A reply that collapsed into one repeated character or phrase is
refused at the boundary and retried at a higher temperature, so it never
becomes a fact. When retain looks slow, nvidia-smi is still the first thing
to check.
Nothing here is required — the bank fills on its own. These are the three things an operator actually reaches for.
Keep a turn out of it. Wrap it in <private>…</private> and retain drops it before extraction reads it. The marker is exact and lower-case, it covers message text rather than tool payloads, and an unclosed <private> discards the rest of that message rather than storing it. It works at retain time only: it cannot unwrite what an earlier retain already stored.
Retire a fact that is no longer true. A superseded memory is retired rather than edited, and every retrieval path — /reflect and the mental-model refresh included — then stops serving it. The row and its graph edges stay.
curl -X POST .../v1/banks/{bank}/nodes/{id}/supersede -d '{"by": <newer node id>}'
curl -X DELETE .../v1/banks/{bank}/nodes/{id}/supersede # put it back
Noticing this automatically, during extraction, was built and measured: it found 2 of 3 targets and 22 things that were not retractions, so it ships off.
Turn off a mental model that has gone wrong. A synthesis refreshes on a schedule and reads as authoritative, so stop the schedule first and decide about the content after. The model, its content and its citations stay.
curl -X DELETE .../v1/banks/{bank}/mental-models/{mm_id}/trigger
More, including what to check when something looks wrong →
cargo test --workspace # full suite (unit + API + schema)
cargo clippy --workspace --all-targets -- -D warnings
cargo run -p memgardend # daemon on 127.0.0.1:9100
cargo test -p memgardend -- --ignored # live tests (need Ollama running)
cargo run -p memgarden-cli --bin hook_bench # hook latency, interleaved-paired
./scripts/hook-budget.sh # binary size, ldd set, dependency closure
mdbook serve book # the wiki, at http://localhost:3000
Work lands as PRD-tracked pull requests (template in .github/), each 3-way reviewed (functional / security / code). Fixes are confirmed by mutation-testing them — reverting the fix has to fail a test, or the test does not count.
The daemon creates its data dir 0700 and speaks plain HTTP on loopback with a Host-header guard. It is a single-user local tool by design.
mdbook serve book.docs/design/ — one design note per merged PR, each standing alone without the diffdocs/evidence/ — the measurements the acceptance criteria were signed on, including the ones that were retracted, and why write-time supersession detection ships offdocs/parity-gaps.md — legacy behaviour deliberately not ported, each row with the fact that would reopen itdocs/PRD.md — the deep-interview spec this repo executescrates/memgarden-core — types, config, lock-free metricscrates/memgarden-store — SQLite layer (migrations, vec/FTS, banks/nodes/search/ledger)crates/memgardend — the daemon (routes, Ollama client, extraction, retain pipeline, embed worker) and mg_migrate, the one-way legacy migration toolcrates/memgarden-cli — the memgarden hook binary; dependency-closure-checked in CI, because a hook pays for its binary on every invocationgold/ — the frozen recall-quality corpus, graded queries, and the results ledgerbook/ — the wiki, built with mdBookclaude-code-integration — the fork whose caps, tags, and profile presets are ported server-side hereMIT — see LICENSE. Vendored browser libraries keep their own notices in crates/memgardend/ui/vendor/.