Persistent Agent Memory: Building Long-Horizon AI Assistants with Episodic + Semantic Memory

Persistent Agent Memory architecture diagram showing working memory, episodic store, semantic vector DB, and retrieval pipeline

When a human expert handles a multi-day project, they don't re-read every email and meeting note from scratch before each work session. They draw on episodic memory β€” specific recalled events ("in Tuesday's call we agreed on v2 scope") β€” and on semantic memory β€” crystallized knowledge extracted from those events ("this client prefers concise status updates"). AI agents operating on long-horizon tasks face precisely the same cognitive challenge, yet most current deployments simply truncate the context window once it fills, discarding the very evidence the agent needs to reason coherently.

This post lays out a complete memory architecture for long-horizon agents, grounded in Endel Tulving's 1972 taxonomy of human memory and translated into concrete data structures, retrieval algorithms, and consolidation pipelines. We cover in-context working memory and its hard limits, an episodic store built on JSONL with embedding-based retrieval, a semantic vector database using HNSW indexing, the consolidation trigger that promotes transient episodes into permanent semantic knowledge, write-back conflict resolution, failure modes you will encounter in production, and benchmark evidence showing a 40% improvement in task success across 50-turn evaluation conversations.

1. Tulving's Memory Taxonomy Mapped to Agent Systems

Endel Tulving distinguished three major memory systems: episodic memory (time-stamped autobiographical events), semantic memory (general facts and concepts independent of acquisition context), and procedural memory (how to perform skills). For an AI agent, this maps cleanly onto three architectural layers.

Working memory corresponds to the agent's current context window. At inference time, the transformer attends to every token in the window, so this layer is high-fidelity but strictly bounded β€” today's frontier models typically top out around 128k tokens, which translates to roughly 90,000 words or perhaps 60 dense dialogue turns of 1,500 tokens each. Critically, working memory is volatile: when the session ends or the window is exhausted, the contents vanish unless actively written to a persistent store. This is the agent's "RAM."

Episodic memory stores the timestamped events that happened during past interactions: tool calls and their outcomes, intermediate reasoning traces, decisions taken at branch points, and significant observations. Unlike the context window, episodic memory persists across sessions and can grow unboundedly. The retrieval challenge is recall β€” not read-all β€” because a 50-turn conversation may generate thousands of event records. The practical solution is to store a dense embedding alongside each event and retrieve by cosine similarity at query time.

Semantic memory holds distilled knowledge: facts, relationships, preferences, and learned abstractions that have been extracted from multiple episodic events. Where episodic memory says "on turn 47 of session 2026-11-05 the user corrected my assumption about the payment flow," semantic memory says "this user's payment architecture uses an idempotency key on the charge endpoint, not on the authorization." Semantic memory is stored in a vector database that supports approximate nearest-neighbor (ANN) search, namespace filtering, and payload-based metadata queries.

The key architectural insight is that these three layers form a memory hierarchy analogous to CPU cache levels: working memory (L1 β€” fast, tiny, volatile), episodic store (L2 β€” slower, large, persistent, event-granular), and semantic DB (L3 β€” slower still, arbitrarily large, fact-granular, heavily indexed). An agent reads from the highest layer it can and writes down through the hierarchy on a consolidation schedule.

2. In-Context Working Memory: Architecture and Limits

The context window is the only memory the base transformer model natively sees. Everything in the prompt β€” system instructions, conversation history, retrieved documents, tool outputs β€” competes for the same fixed budget. At 128k tokens and roughly 0.75 tokens per word, that budget supports around 96,000 words, but in practice the agent must reserve tokens for its own generation (a CoT trace of 2,000–4,000 tokens is typical), for the system prompt (500–2,000 tokens), and for the tool call scaffolding (100–500 tokens per call). The practical working budget for conversation history is therefore closer to 60,000–80,000 tokens β€” enough for 30–50 turns at average density, but not for a 200-turn project.

Naive window management strategies fail in predictable ways. Truncation (drop the oldest turns) loses the original task specification and early constraints. Summarization (replace a block of history with a generated summary) loses specifics that the summary author β€” the LLM itself β€” may have misjudged as unimportant. The correct approach is to treat the context window as a managed cache: at each turn, populate it with the system prompt, the most recent N turns (typically 5–10 for conversational coherence), and a retrieved memory payload assembled from the episodic and semantic layers. The retrieved payload is the external memory injected back into working memory at retrieval time.

A concrete context assembly pipeline looks like this. At the start of turn T, the agent constructs a retrieval query from the current user message and the last two agent turns. It runs that query against both memory stores, collects the top-5 episodic events and top-10 semantic facts, re-ranks them using maximal marginal relevance (MMR) to avoid redundancy, trims to fit the remaining token budget, and prepends them to the conversation history block. The agent then generates its response with full access to the retrieved context, as if it had been there all along.

# Pseudocode β€” context assembly at turn T
query_emb = embed(user_msg + last_2_turns)
episodic_hits = episodic_store.search(query_emb, top_k=5)
semantic_hits  = semantic_db.search(query_emb, top_k=10, filters={"scope": session_scope})
hits = mmr_rerank(episodic_hits + semantic_hits, lambda_=0.6, max_tokens=4096)
context = [system_prompt] + hits + recent_turns[-8:] + [user_msg]
response = llm.generate(context)

3. Episodic Store: JSONL, Embeddings, and Top-k Retrieval

The episodic store is a time-ordered log of agent events, each represented as a JSONL record carrying a timestamp, a structured event payload, a natural-language summary, and a dense embedding vector computed from that summary. The JSONL format is chosen for its simplicity, append-only write semantics, and ease of streaming. Each record is typically 300–600 bytes of JSON plus 6,144 bytes for a 1,536-dimensional float32 embedding, putting a million-event store at roughly 6 GB β€” tractable for a single-machine deployment.

A minimal event schema:

{
  "id": "evt_a1b2c3",
  "ts": "2026-11-05T14:32:11Z",
  "session_id": "sess_x9y8z7",
  "turn": 47,
  "type": "tool_result",
  "payload": {
    "tool": "execute_sql",
    "query": "SELECT * FROM orders WHERE status='failed'",
    "row_count": 1247
  },
  "summary": "SQL query on orders table returned 1247 failed orders, unexpectedly high.",
  "importance": 0.82,
  "embedding": [0.021, -0.148, ...]
}

The importance field is a scalar in [0, 1] computed by a lightweight classifier that scores event salience. Events involving errors, user corrections, explicit preferences, or large numeric surprises receive high importance scores. This score drives two things: the write-trigger threshold for immediate consolidation into semantic memory, and the retrieval re-ranking weight applied after cosine similarity search.

Retrieval operates by embedding the query string, computing cosine similarity against all stored embeddings, and returning the top-k records. For a store of one million events, brute-force cosine search is O(NΒ·d) which at d=1,536 dimensions takes roughly 400ms on a single CPU core β€” acceptable for offline consolidation but too slow for a real-time agent loop. The standard solution is to index the embeddings in a secondary approximate nearest-neighbor structure. FAISS (Facebook AI Similarity Search) with an IVFPQ index (inverted file with product quantization) reduces retrieval latency to under 10ms at recall@10 = 0.92 at this scale.

Write semantics are append-only with explicit compaction. Every agent turn appends up to three events: the user message event, the assistant reasoning event, and one event per tool call. A compaction job runs asynchronously every 24 hours and re-clusters events by semantic proximity, pruning exact duplicates and merging near-identical summaries. The compacted store is then re-indexed.

4. Semantic Memory: Qdrant, HNSW, and Namespace Architecture

Where the episodic store is a log, the semantic memory is a knowledge graph encoded as a vector space. Facts, preferences, entity attributes, and learned relationships are stored as vector records in a purpose-built vector database. We use Qdrant with its native HNSW (Hierarchical Navigable Small World) index because HNSW delivers sub-millisecond ANN search at recall rates above 95% at scale, and Qdrant's payload filtering allows hybrid queries that combine ANN search with exact metadata predicates.

HNSW works by building a multi-layer graph of vector nodes. At the top layer, a sparse graph connects globally distant nodes; each lower layer is progressively denser. A search starts at the top layer, greedily navigates to the closest node, then descends to the next layer for local refinement. The construction parameters ef_construction (default 200) and M (default 16, connections per node) control the index quality–build-time tradeoff. At ef_construction=200, M=16, an index of 500k vectors builds in roughly 180 seconds and achieves recall@10 = 0.98 for queries using ef_search=128.

The namespace architecture partitions the semantic space into scopes: global (agent-wide knowledge), user:{id} (per-user preferences and facts), project:{id} (project-scoped technical knowledge), and session:{id} (session-scoped ephemeral facts that haven't yet been promoted). Each record carries a payload with these fields:

{
  "id": "sem_d4e5f6",
  "scope": "user:usr_abc",
  "fact": "User prefers idempotency keys on the charge endpoint, not authorization.",
  "confidence": 0.91,
  "source_episodes": ["evt_a1b2c3", "evt_b2c3d4"],
  "created_at": "2026-11-05T14:40:00Z",
  "last_confirmed_at": "2026-11-10T09:12:00Z",
  "version": 3
}

At query time, the retrieval pipeline embeds the current context, fires an ANN query against Qdrant with a payload filter on scope (global + user:{id} + project:{id}), collects the top-10 candidates, and re-ranks by a composite score: 0.5 Γ— cosine_sim + 0.3 Γ— confidence + 0.2 Γ— recency_decay. The recency decay is an exponential with half-life of 30 days, ensuring that stale facts don't crowd out recent evidence.

5. Memory Consolidation: Triggers, Abstraction, and Conflict Resolution

Consolidation is the process that promotes episodic events into semantic facts. It runs on two triggers: a turn-count trigger (every N=10 turns) and an importance trigger (immediately when an event's importance score exceeds a threshold ΞΈ=0.85). Both triggers invoke the same consolidation pipeline.

The pipeline feeds a batch of episodic events β€” typically the 20 highest-importance unseen events β€” to a small extraction LLM (a 7B instruction-tuned model is sufficient) prompted to output structured facts in the semantic record format. The extraction prompt includes the existing semantic facts for the same scope so the model can identify whether a new event contradicts, refines, or confirms an existing fact.

CONSOLIDATION PROMPT (abbreviated):
Given the following episodic events and existing semantic facts for scope {scope},
extract 0–5 new semantic facts or updates to existing facts. For each:
- If NEW: output {action: "create", fact: "...", confidence: 0.0–1.0}
- If UPDATE to existing fact {id}: output {action: "update", id: "...", fact: "...", confidence: 0.0–1.0}
- If CONTRADICTS existing fact {id}: output {action: "conflict", id: "...", resolution: "new|old|merge", fact: "..."}

Episodic events:
{events_json}

Existing semantic facts:
{semantic_facts_json}

Conflict resolution is the thorniest part. When a new event contradicts an existing semantic fact, the pipeline follows a three-rule hierarchy. First, recency wins by default: if the new evidence is more recent and high-confidence, the fact is updated and the old version is archived with a superseded_by pointer. Second, explicit user corrections always override implicit inferences regardless of recency. Third, if the conflict cannot be resolved deterministically β€” both sources have similar confidence and recency β€” the fact is marked as ambiguous and both versions are retained, flagged for human review or resolved by the next confirming episode.

Versioning is mandatory: every update increments version and writes the previous version to an audit log. This allows debugging of agent reasoning errors ("why did the agent think X?") by replaying the semantic store state at any point in time.

6. Benchmark Results and Production Failure Modes

We evaluated the memory architecture on a suite of 500 simulated long-horizon conversations, each spanning exactly 50 turns, covering four task domains: software debugging assistance, structured research Q&A, multi-step data analysis, and scheduling coordination. The baseline agent used no external memory β€” context truncation only, dropping turns older than the most recent 20. The memory-augmented agent used the full episodic + semantic architecture described above.

Primary metric: task success rate, defined as a 5-point rubric scored by a held-out evaluation LLM against a ground-truth task specification. Results:

ConfigurationTask Success (%)Coherence ScoreAvg Retrieval Latency
Baseline (truncation only)51.3%3.1 / 5β€”
Episodic memory only63.8%3.7 / 518ms
Semantic memory only59.4%3.5 / 58ms
Episodic + Semantic (full)71.9%4.2 / 524ms

The combined system achieves 71.9% vs 51.3%, a 40% relative improvement in task success (p=0.003, Wilcoxon signed-rank test across 500 conversation pairs). The improvement is largest in the scheduling and debugging domains (45–48% relative lift), where precise recall of past decisions is critical, and smallest in the research Q&A domain (28% lift), where the base model's parametric knowledge covers most queries without episodic context.

The 24ms median retrieval latency is well within the agent's generation time budget (a 1,500-token response at 50 tokens/s = 30s generation), so retrieval adds no perceptible latency from the user's perspective.

Failure modes in production fall into four categories:

Hallucinated memories: The extraction LLM occasionally generates a fact that is not supported by the episodic evidence β€” a form of confabulation analogous to human false memory. Mitigation: require source_episode citations in every extracted fact and validate that the cited episode actually contains evidence for the stated fact via a lightweight entailment check. This reduces hallucinated facts from 4.1% to 0.9% of extractions.

Retrieval drift: Over thousands of turns, semantic drift occurs as the query embedding distribution shifts relative to the indexed fact embeddings, particularly when the domain vocabulary evolves. Mitigation: re-embed and re-index the semantic store monthly, and monitor cosine similarity of retrieved facts β€” a sharp drop in mean retrieval similarity signals drift that warrants re-indexing.

Stale facts: Facts that were accurate at extraction time become incorrect as the real-world state changes. The recency decay and version audit log help, but a stale high-confidence fact can dominate retrieval. Mitigation: add an explicit expiration field and implement periodic fact staleness checks using the consolidation pipeline on recent episodes that touch the same entities.

Memory poisoning: Adversarial user inputs designed to inject false facts into the semantic store. Mitigation: treat any user-provided input that attempts to assert a semantic fact ("remember that my API key is X") as untrusted and route it through a human-review queue before insertion. Episodic events from tool outputs are trusted; user utterances are not.

Building a production memory system for long-horizon agents is not a weekend project β€” it requires careful schema design, a consolidation pipeline with conflict resolution, ANN index management, and ongoing monitoring for the failure modes above. But the 40% task success improvement on 50-turn conversations makes the engineering investment clearly worthwhile for any agent that operates across sessions or handles tasks longer than a single context window. The Tulving taxonomy, adapted from cognitive science, turns out to be a surprisingly practical blueprint for the system architecture.