Back to all articles
ai automationAgent Memory

Agent Memory Is Not One Thing: Working, Episodic and Long-Term Context

Treating agent memory as a single vector dump or chat log leads to context window saturation and severe hallucination. Production architectures require three distinct tiers: Working Context, Episodic Task History, and Long-Term Knowledge Graphs.

August 20, 2026
11-13 min read
Digital Elliptical Engineering (Principal AI Knowledge Architect)
memory_architecture.exe
3. Permanent Knowledge Graph
2. Episodic Task Log
1. Working Context
LAYER SPECIFICATIONworking
Working Memory (Context Window)
RETENTION & LIFESPANLifespan of single request (Ephemeral)
WRITE & PRUNING POLICYStrict token budgeting & automatic pruning
ACCESS LATENCY< 10ms direct memory buffer
SECURITY & TRUST BOUNDARYUnsanitized user prompt & active tool outputs
Click layer rings to inspectDeterministic boundaries

Executive Summary

  • Dumping raw chat logs into vector databases causes semantic drift and retrieval noise.
  • Working memory is ephemeral, strictly budgeted, and lives only within the active LLM context window.
  • Episodic memory requires temporal indexing and structured JSON envelopes to record task execution history.
  • Long-term memory requires structured entity graph extraction rather than unstructured embedding dumps.
  • Permission boundaries and data retention rules must be enforced separately at each memory layer.

The memory misconception: Why single-store designs fail

In naive AI implementations, developers often treat 'agent memory' as a single undifferentiated bucket. They take the user's raw prompt, append the last 50 conversational turns, run a vector similarity search over a flat Pinecone or pgvector table, and stuff the top 20 retrieved chunks into the prompt.

This approach fails in production. As the conversation progresses, the context window saturates with stale observations, irrelevant tool outputs, and noisy vector matches. The model loses focus on the original goal—a phenomenon known as 'lost in the middle'—and begins hallucinating.

Human memory is not a single database table, and agent memory should not be either. High-performance agentic systems require strict architectural separation between active working memory, temporal task history, and permanent relational knowledge.

Avoid raw vector dumping

Vector search finds semantic similarity, not temporal or relational relevance. Shoveling past tool outputs into a vector store creates noise that degrades agent reasoning.

The three distinct tiers of agent memory

A robust agentic architecture separates context into three distinct lifecycle tiers: Working Memory, Episodic Memory, and Long-Term Knowledge.

1. Working Memory (Active Context Window): Ephemeral, immediate memory passed in the model prompt. It contains the system instructions, the current plan, and the last 3–5 tool observations. It operates under strict token budgets (e.g., maximum 8,000 tokens) and is aggressively pruned.

2. Episodic Memory (Task Execution Log): An append-only event ledger tracking every step taken during a multi-hour task. Stored in Redis or PostgreSQL, it allows the agent to review past failures, reconstruct checkpoints, and verify that actions were executed.

3. Long-Term Knowledge (Entity Graphs & Vector Stores): Permanent enterprise knowledge that persists across tasks and users. Rather than raw chat text, long-term memory stores structured entity relationships (e.g. 'Customer X owns Account Y and requires SLA Tier 1') verified by human review.

3-Tier memory data flow

User Task Input
Working Memory Buffer (Pruned)
Episodic Event Log (Postgres / Redis)
Entity Extraction Engine
Long-Term Knowledge Graph
Deterministic Response

Information is filtered and structured as it moves from ephemeral working context into permanent long-term storage.

Tiered memory specifications and trade-offs

Each memory tier has distinct latency characteristics, write permissions, and operational constraints.

Technical comparison of agent memory layers

FeatureDimensionWorking MemoryEpisodic MemoryLong-Term Knowledge
Storage MediumRAM / Model Token BufferKey-Value / Document Store (Redis/Postgres)Graph DB (Neo4j) + Vector DB (pgvector)
LifespanSingle LLM Request (Seconds)Duration of Task (Minutes to Days)Permanent (Months to Years)
Token Budget4k - 16k tokens strictly cappedUnlimited on disk (Paged on demand)Indexed as discrete entity triples
Write AccessStateless LLM reasoning workerAppend-only background task engineHuman-reviewed / Entity extraction pipeline
Retrieval Latency< 5ms in-memory lookup10ms - 30ms database read50ms - 150ms hybrid graph/vector traversal
Security ModelUnsanitized active prompt scopeTask-scoped transaction envelopeStrict enterprise ACLs & tenant masks

Memory manager TypeScript schema contract

A production agent must interact with memory through explicit, strongly-typed interfaces. Below is the TypeScript contract for a multi-tier memory manager.

TieredMemoryManager.ts
TypeScript Interface
export interface WorkingContextEnvelope { systemPrompt: string; activeGoal: string; immutablePlanDAG: string[]; recentObservations: Array<{ tool: string; output: string; timestamp: number }>; tokenUsage: { current: number; budget: number }; } export interface EpisodicEventLog { taskId: string; sequenceId: number; timestamp: string; eventType: "PLAN_STEP" | "TOOL_INVOCATION" | "SCHEMA_ERROR" | "CHECKPOINT"; payload: Record<string, any>; } export interface LongTermEntityTriple { entityId: string; subject: string; predicate: string; object: string; confidenceScore: number; sourceDocumentUri: string; accessControlList: string[]; // Allowed tenant / role IDs }

Context pruning and recursive summarization

Working memory cannot grow indefinitely. When an agent executes 20 tool calls, raw tool outputs (such as large JSON payloads or multi-page file dumps) will quickly exceed token limits.

We maintain working memory health through two automated processes: Tool Output Compaction and Recursive Summarization.

Tool outputs must be compacted before entering the token buffer. If a search tool returns 50 records, the tool wrapper extracts only the 3 relevant fields. When the conversation history exceeds 70% of the token budget, a lightweight summarizer model compresses earlier turns into a 3-bullet state summary, preserving working space for active reasoning.

Working memory compaction lifecycle

1
Tool returns raw multi-kilobyte execution output
2
Schema filter compacts payload down to relevant fields only
3
Token counter evaluates total working context utilization
4
If utilization > 70%, background summarizer compresses completed steps
5
Pruned working envelope is passed to the frontier reasoning model

Security boundaries and data retention policies

Memory architectures must strictly respect enterprise privacy and regulatory compliance (such as GDPR, HIPAA, and SOC-2).

Working memory must never log raw customer PII to unencrypted caches. Episodic task logs must have automated Time-To-Live (TTL) expiration rules (e.g. automatically purging debug logs after 30 days).

Long-term knowledge stores must enforce metadata-level Access Control Lists (ACLs). When an agent queries permanent knowledge on behalf of a sales representative, the retrieval query must be filtered to exclude confidential executive HR records.

Memory architecture deployment checklist

Verify these architectural boundaries before deploying agent memory systems to production.

Memory system readiness check

1Working Memory Guardrails
  • Strict token budgets are enforced on prompt construction
  • Tool outputs are filtered and compacted before entering context
  • Automated summarization prevents 'lost in the middle' degradation
2Episodic Task Storage
  • Task execution steps are written to an append-only transaction ledger
  • Checkpoints are indexed by task ID and sequence number
  • TTL policies automatically purge stale episodic logs after 30 days
3Long-Term Knowledge Security
  • Entity triples are validated and de-duplicated before permanent indexing
  • Query-time ACL filters prevent cross-tenant and cross-role data leaks
  • Source document provenance hashes are attached to all knowledge nodes
Decision path

Design a tiered memory architecture for your AI agents

Dumping raw chat history into vector stores causes retrieval drift and prompt bloat. We will help you structure working token budgets, episodic event ledgers, and entity graph stores.

Request an agent memory review

Keep Reading