Building AI Agent Long-term Memory: How to Make Cross-session Memory Not Collapse

TL;DR: On 2026-10-31, thedotmack/claude-mem hit 107k stars on GitHub Trending, turning cross-session persistent context into a baseline expectation — it captures everything an agent does in a session, compresses it with AI, and injects relevant context back into future sessions; the same day Jiqizhixin shipped VoiceMem (streaming dual-brain memory infrastructure) and A5 (lifelong-context proactive assistant), while arXiv:2610.25119 proposed BEAM Bayesian memory, upgrading memory value from a historical hit-rate into a dynamic belief calibrated by execution feedback. For developers, long-term memory is no longer about whether to build it, but how to build it so it does not drag the agent down with rotten memories over long horizons. This post gives the three-layer architecture, the collapse points of naive RAG, and two runnable scripts.

1. Background: why long-term memory suddenly became mandatory

Within a single turn the context window is enough; but for an agent to remember you across days and projects, experience must hit disk. Three signals stacked in the same week:

SignalFactMeaning
claude-mem (GitHub Trending, 2026-10-31)107k stars; captures every agent session, AI-compresses, re-injects into future sessions; works with Claude Code / Codex / Gemini / Copilotcross-session memory becomes a first-class tool default
VoiceMem / A5 (Jiqizhixin, 2026-10-31)VoiceMem uses a streaming dual-brain for fact and emotional memory, ~300 tokens and 0-300ms speculative prefetch per query; A5 drives tasks proactively via lifelong contextmemory splits into fact/emotion brains and turns proactive
BEAM (arXiv:2610.25119, 2026-10-18)models memory value as a dynamic belief calibrated by task context and execution feedback, not a passive statisticmemory valuation itself needs reasoning

Jiqizhixin article library (2026-10-20) also surfaced MemT 1.0 (memory as an in-model capability) and WorldMemArena (multimodal memory in real interaction), showing memory is moving from an external store toward model-native.

2. How it works: the three-layer memory architecture

A production memory layer that survives long horizons needs at least three layers:

  1. Store: persist each episode with structured metadata (role, importance, timestamp, embedding). The key is an importance weight and deduplication, or memory grows without bound.
  2. Retrieve: top-k recall by embedding similarity times importance. Naive RAG ranks only by similarity and floats high-frequency but low-value memories to the top.
  3. Compress: as memory grows, summarize old episodes into shorter facts or merge duplicates; claude-mem and VoiceMem both use this step to keep a single query at a few hundred tokens.

BEAM’s contribution is a dynamic belief on top of retrieval: whether a memory is useful now depends on the current task context and on historical feedback of whether reusing it actually helped — not a simple historical hit-rate. That turns memory from passive storage into an adaptive cognitive mechanism.

3. Tie-in to today's news

This week’s signals consistently point at memory-as-capability: claude-mem fixes cross-session loss, VoiceMem fixes latency and layering, A5 fixes memory-driven proactivity, BEAM fixes whom to trust. Their shared engineering pain is memory rot: a stale preference from three months ago, an overturned conclusion, or a context-mismatched old experience all poison recall. That is exactly why belief calibration and compression matter, instead of blind append. Note this is the same coin as our 2026-10-30 post AI Memory Poisoning — memory is both a capability and an attack surface, so the write path must be sanitized (see related reading).

4. Developer checklist

  1. Define three layers before code: keep Store / Retrieve / Compress responsibilities separate.
  2. Score every memory by importance: explicit user preference > successful tool result > chit-chat; rank by score times similarity.
  3. Add expiry and dedupe: keep only the newest fact per class; TTL or down-weight on contradiction.
  4. Rank by belief, not hit-rate: record whether each memory helped after reuse, calibrate with feedback (script 5.2).
  5. Treat writes as untrusted: run prompt-injection detection on anything entering memory before persistence.
  6. Cap per-query recall size: like VoiceMem, keep a single query to a few hundred tokens instead of dumping the whole memory back into context.

5. Step-by-step: runnable SQLite memory layer + BEAM-style belief update

5.1 Minimal persistent memory layer (runs as-is, stdlib only)

import sqlite3, hashlib, json, re
from collections import Counter

DB = "agent_memory.db"

def _embed(text):
    # minimal runnable embedding: hash buckets over 1-2grams, zero external deps
    toks = re.findall(r"\w+", text.lower())
    grams = toks + [f"{a}_{b}" for a, b in zip(toks, toks[1:])]
    buckets = Counter()
    for g in grams:
        buckets[hashlib.md5(g.encode()).hexdigest()[:8]] += 1
    norm = sum(v * v for v in buckets.values()) ** 0.5 or 1
    return {k: v / norm for k, v in buckets.items()}

def similarity(a, b):
    return sum(a.get(k, 0) * b.get(k, 0) for k in (set(a) | set(b)))

def store_episode(role, content, importance=1.0):
    conn = sqlite3.connect(DB)
    conn.execute("CREATE TABLE IF NOT EXISTS mem "
                 "(id INTEGER PRIMARY KEY, role TEXT, content TEXT, "
                 "emb TEXT, importance REAL, ts REAL)")
    conn.execute("INSERT INTO mem VALUES (NULL,?,?,?,?,strftime('%s','now'))",
                 (role, content, json.dumps(_embed(content)), importance))
    conn.commit(); conn.close()

def retrieve(query, top_k=3):
    conn = sqlite3.connect(DB)
    q = _embed(query)
    rows = conn.execute("SELECT role,content,emb,importance FROM mem").fetchall()
    scored = [(similarity(q, json.loads(e)) * imp, c) for _, c, e, imp in rows]
    conn.close()
    return [c for _, c in sorted(scored, reverse=True)[:top_k]]

if __name__ == "__main__":
    store_episode("user", "Preference: always use type hints in Python code")
    store_episode("agent", "Called search_web tool, returned 3 results")
    print(retrieve("how to write a Python function"))   # should recall the type-hint preference

Expected: the first returned item is the user preference, proving the Store+Retrieve layers already work.

5.2 BEAM-style belief update (runs as-is)

def update_belief(prior, evidence_weight, observed_useful):
    # BEAM-style: memory value is a dynamic belief calibrated by execution feedback
    # prior: 0..1 initial belief; observed_useful: did reusing this memory actually help
    lr = min(0.3, evidence_weight)
    target = 1.0 if observed_useful else 0.0
    posterior = prior + lr * (target - prior)
    return max(0.0, min(1.0, posterior))

mem_belief = {"prefer_type_hints": 0.5}
mem_belief["prefer_type_hints"] = update_belief(mem_belief["prefer_type_hints"], 0.2, True)
print(round(mem_belief["prefer_type_hints"], 3))   # 0.6: belief rises after a successful reuse

Use mem_belief as the retrieval ranking weight and memory gets smarter with use, instead of being held hostage by historical hit-rates — exactly the incremental value of BEAM over naive RAG.

6. Recap

DimensionOne-liner
Trendcross-session memory is now standard (claude-mem 107k, VoiceMem, A5)
ArchitectureStore / Retrieve / Compress, separated
Collapse pointnaive append + RAG rots from stale memories
UpgradeBEAM calibrates memory value by execution feedback
Red linesanitize the write path to prevent memory poisoning

Long-term memory is the agent’s second brain in 2026, but a second brain can also go senile — layering, compression and belief calibration are what keep it getting smarter. Related: AI Memory Poisoning Is Here and More Agents Is Not a Silver Bullet.

Further reading

Feedback

This site is front-end only — no backend, no accounts — so feedback goes to GitHub Issues, Discussions, or email.

Paste it into the issue or email to help track it down — it never includes anything you typed

Also:Browse existing issues · Email feedback (no GitHub account needed):278975598@qq.com