Skip to content
Back to blog
AI system

Designing Agent Memory Architecture: Working, Episodic, Semantic, and Long-Term Memory

Updated 25 min read

AI agents need more than conversation history. A practical guide to Working, Episodic, Semantic, and Long-Term memory: how to extract, store, retrieve, consolidate, and forget information without losing accuracy, security, or relevance.

Table of Contents

Introduction

An AI agent can process a request, call tools, reason about results, and produce an answer.

But what happens when the same agent receives another request tomorrow?

Should it remember the previous conversation? Should it remember a failed tool execution? Should it retain a user's preferences? Should it store facts extracted from a document? Should it remember a decision made several weeks ago?

These questions introduce a fundamental architectural problem: memory management.

A system that remembers everything becomes expensive, noisy, and difficult to maintain. A system that remembers nothing repeats work, loses useful context, and cannot benefit from previous experience.

The objective is not to maximize the amount of stored information.

It is to preserve information that can improve future decisions and retrieve it only when it is relevant.

This article explores four complementary memory categories:

  1. Working Memory.
  2. Episodic Memory.
  3. Semantic Memory.
  4. Long-Term Knowledge.

They serve different purposes and should have different lifecycle, retrieval, and storage strategies.


1. Why AI Agents Need Memory

Consider a Contract Operations Assistant.

On Monday, a user asks the agent to review a contract. The agent identifies an unusual termination clause and records the result.

On Tuesday, the user uploads a revised version of the same contract.

On Wednesday, the user asks:

Compare the latest version with the previous one. Did the termination risk change?

A stateless system needs to reconstruct the entire context from available documents and conversation history.

A system with appropriate memory can reuse useful information:

  • The previous analysis.
  • The contract version that was analyzed.
  • The identified termination clause.
  • The reasoning behind the previous risk assessment.
  • The outcome of the previous task.

Memory enables continuity across separate executions.

The difference between remembering and storing

Storing data is a persistence problem.

Remembering useful information is a decision problem.

A database can store millions of records, but an agent should not retrieve all of them for every request.

The system needs to decide:

  • What information is worth retaining?
  • What is its scope?
  • How long should it remain useful?
  • Which future tasks may need it?
  • How should conflicting information be handled?
  • When should the information be updated or forgotten?

These are memory architecture responsibilities.

flowchart TD
    A[Agent Execution] --> B[Experience and Observations]
    B --> C[Memory Extraction]
    C --> D[Memory Evaluation]
    D --> E{Worth Retaining?}

    E -->|Yes| F[Memory Storage]
    E -->|No| G[Discard or Keep Temporarily]

    F --> H[Future Task]
    H --> I[Memory Retrieval]
    I --> J[Relevant Context]
    J --> K[Agent Decision]

Memory should be treated as an independent subsystem, not simply a longer prompt.


2. Memory Is Not the Same as Conversation History

Conversation history and memory are often used interchangeably, but they represent different things.

Conversation history

Conversation history preserves what happened in a conversation.

For example:

text
User: Review this contract.
Assistant: I found three unusual clauses.
User: Explain the termination clause.
Assistant: The termination clause allows...

This is a chronological record of interaction.

It is useful when reconstructing the context of an ongoing conversation.

Agent memory

Agent memory preserves selected information that may be useful beyond the original conversation.

For example:

text
Memory:
- Contract ABC was analyzed on November 10.
- The termination clause was classified as high risk.
- The analysis used policy version 2.1.
- The user requested a comparison against the previous contract version.

This is a structured representation of information selected for future use.

Knowledge base

A knowledge base stores source material that the agent can retrieve and reference.

For example:

  • Contract documents.
  • Internal policies.
  • Legal guidelines.
  • Product documentation.
  • Technical specifications.

These documents are not necessarily memories of the agent's own experience.

Comparison

SystemPrimary purposeTypical content
Conversation historyPreserve interactionsMessages and tool responses
Agent memoryPreserve useful experience and contextPreferences, decisions, lessons
Knowledge baseProvide external knowledgeDocuments and reference material
Execution stateResume an unfinished taskCurrent step, checkpoint, pending actions

These systems may share infrastructure, but their responsibilities should remain separate.

An execution checkpoint should not automatically become a long-term memory. A retrieved document should not automatically become an agent experience.


3. Four Types of Agent Memory

A practical architecture can divide memory into four categories.

flowchart TB
    A[Agent Memory Architecture]

    A --> B[Working Memory]
    A --> C[Episodic Memory]
    A --> D[Semantic Memory]
    A --> E[Long-Term Knowledge]

    B --> F[Current Execution]
    C --> G[Past Experiences]
    D --> H[Reusable Facts and Relationships]
    E --> I[External Documents and References]

Each category answers a different question.

Memory typeQuestion it answers
Working MemoryWhat am I doing right now?
Episodic MemoryWhat happened before?
Semantic MemoryWhat do I know that can be reused?
Long-Term KnowledgeWhat external information can I consult?

The categories are conceptual boundaries, not mandatory database products.

A system may use one relational database with separate tables, or several storage systems when scale and access patterns justify it.


4. Working Memory: Managing the Current Task

Working Memory contains the information required to execute the current task.

It is usually temporary and closely connected to the agent runtime.

Consider a contract review task:

text
Task ID: task_123

Goal:
Review contract ABC.

Current state:
Extracting termination clauses.

Completed:
- Document loaded.
- Metadata extracted.
- Payment clauses identified.

Pending:
- Termination analysis.
- Risk assessment.
- Final report.

Current observations:
- Contract has two termination conditions.
- One condition references a separate appendix.

This information helps the agent continue its work without repeatedly reconstructing the execution context.

Working Memory responsibilities

Working Memory may contain:

  • Current user intent.
  • Task instructions.
  • Current plan.
  • Completed steps.
  • Pending steps.
  • Relevant retrieved information.
  • Recent tool results.
  • Intermediate reasoning outputs.
  • Execution constraints.
  • Current task-specific variables.

Not all of this information needs to be sent to the LLM on every call.

The runtime can retain a complete execution state while assembling a smaller context for each model invocation.

Working Memory versus runtime checkpoint

These concepts are related but not identical.

A checkpoint exists primarily to recover execution after interruption.

Working Memory exists to support the current task's reasoning and execution.

A checkpoint may contain a serialized representation of Working Memory, but it may also include runtime-specific information such as:

  • Current state machine state.
  • Pending tool invocation.
  • Retry count.
  • Worker lease.
  • Execution sequence number.

Example data model

ts
type WorkingMemory = {
  executionId: string;
  taskId: string;

  goal: string;

  plan: Array<{
    id: string;
    description: string;
    status: "pending" | "running" | "completed" | "failed";
  }>;

  observations: Array<{
    source: string;
    content: string;
    createdAt: string;
  }>;

  constraints: {
    maxIterations: number;
    remainingBudget: number;
  };

  updatedAt: string;
};

This model is illustrative. A production implementation should avoid keeping unbounded observations in a single object.

Large tool outputs should normally remain in external storage, with references and relevant excerpts included in Working Memory.

Lifecycle

Working Memory usually follows the execution lifecycle:

stateDiagram-v2
    [*] --> Initialized
    Initialized --> Active
    Active --> Active: Update context
    Active --> Paused
    Paused --> Active: Resume
    Active --> Completed
    Active --> Failed
    Completed --> [*]
    Failed --> [*]

When the task finishes, its Working Memory can be archived or deleted according to retention policies.

Selected information may be promoted into Episodic or Semantic Memory.

It should not automatically be promoted in its entirety.


5. Episodic Memory: Learning from Past Experiences

Episodic Memory records meaningful events and experiences from previous executions.

An episode describes something that happened, including its context and outcome.

For example:

text
Episode:
A contract analysis failed because the PDF contained
a scanned appendix that the parser did not recognize.

Context:
- Task: Contract review.
- Document type: Scanned PDF.
- Parser: PDF extraction pipeline v1.
- Failure: Missing appendix content.

Action:
The document was processed through OCR.

Outcome:
The appendix was successfully extracted.

Lesson:
Check document extraction coverage before analyzing
contracts with scanned attachments.

This is more useful than storing a generic statement such as:

text
OCR is useful for scanned documents.

The episode preserves the actual experience, while Semantic Memory may later contain a generalized lesson.

What should become an episode?

Useful candidates include:

  • A task completed successfully.
  • A tool execution failed.
  • A recovery strategy worked.
  • A user corrected an incorrect assumption.
  • An important decision was made.
  • An unexpected condition changed the execution plan.
  • A workflow produced a measurable result.

Not every tool call deserves its own episode.

A single execution may contain dozens of tool calls, most of which have little value outside the task.

The memory extraction process should identify meaningful events.

Episode structure

ts
type EpisodicMemory = {
  id: string;

  executionId: string;
  taskType: string;

  eventType:
    | "success"
    | "failure"
    | "decision"
    | "correction"
    | "recovery";

  context: Record<string, unknown>;

  action?: string;
  outcome: string;

  lesson?: string;

  createdAt: string;
};

For a production system, context should use validated schemas or typed event payloads rather than unrestricted objects.

Why preserve the outcome?

An agent should distinguish between:

  • An action that was attempted.
  • An action that succeeded.
  • An action that failed.
  • An action that appeared successful but was never verified.

These are different experiences.

For example, a tool call that timed out does not prove that the operation failed. The external system may have completed the action even though the agent did not receive a response.

Episodic Memory should preserve uncertainty rather than converting it into a false fact.

Episodes as experience, not instructions

An episode is evidence about a previous execution.

It should not automatically become an instruction for future executions.

Suppose a previous task succeeded after using a particular API endpoint. That does not mean the endpoint should always be used in the future.

The current environment and task requirements may have changed.

Memory retrieval should provide the episode as context. The agent runtime and policy engine should still validate the proposed action.


6. Semantic Memory: Preserving Reusable Knowledge

Semantic Memory contains generalized knowledge that can be reused across multiple tasks.

It differs from Episodic Memory because it does not need to preserve the complete history of an event.

Consider these two records:

Episodic Memory

text
On November 10, a contract review failed because
the appendix was scanned. OCR resolved the issue.

Semantic Memory

text
Contract appendices may contain scanned pages.
Document extraction should verify page coverage
before clause analysis.

The first describes an experience.

The second expresses reusable knowledge.

Typical semantic memory content

  • User preferences.
  • Stable project facts.
  • Previously established decisions.
  • Reusable workflow rules.
  • Known constraints.
  • Verified lessons.
  • Relationships between entities.
  • Repeated corrections.

A useful semantic memory structure

ts
type SemanticMemory = {
  id: string;

  subject: string;
  predicate: string;
  object: string;

  scope: {
    tenantId?: string;
    projectId?: string;
    userId?: string;
  };

  sourceEpisodeIds: string[];

  confidence: number;

  validFrom: string;
  validUntil?: string;

  createdAt: string;
  updatedAt: string;
};

The subject-predicate-object structure makes relationships explicit.

For example:

text
Subject: Contract Review Workflow
Predicate: requires
Object: Document Extraction Validation

Another example:

text
Subject: Project ABC
Predicate: uses
Object: Policy Version 2.1

This representation can support filtering, relationship traversal, and conflict detection.

Facts need scope and provenance

A fact without scope can be dangerous.

Consider:

text
The user prefers concise reports.

Does this apply to all users? One user? One project? A particular task?

A better representation makes the scope explicit.

Similarly, a fact should ideally retain its source.

If a user corrects an agent, the system should know which statement was corrected and why the new fact is trusted.

Semantic Memory should not be a dump of model-generated summaries

A summary may contain:

  • Incorrect interpretations.
  • Missing qualifications.
  • Outdated facts.
  • Unsupported conclusions.

Before promoting information into reusable memory, the system should validate its source, scope, and usefulness.


7. Long-Term Knowledge and External Knowledge Bases

Long-Term Knowledge contains information that the agent may need to consult repeatedly but that is not necessarily an experience or a generalized memory.

Examples include:

  • Company policies.
  • Product documentation.
  • Contract templates.
  • Legal references.
  • Technical documentation.
  • Internal operating procedures.

This information is usually maintained as an external source of truth.

Why separate it from Semantic Memory?

Suppose a company has a 200-page contract policy.

It would be inefficient and potentially inaccurate to convert the entire policy into a collection of agent memories.

The document itself should remain authoritative.

Semantic Memory can store a useful pointer:

text
The Contract Review Agent uses the current
Contract Policy as its primary risk reference.

Long-Term Knowledge stores the actual policy and its versioned content.

Memory and knowledge are complementary

flowchart TD
    A[User Request] --> B[Agent Runtime]

    B --> C[Memory Retrieval]
    B --> D[Knowledge Retrieval]

    C --> E[Past Experiences and Reusable Facts]
    D --> F[External Documents and References]

    E --> G[Context Assembly]
    F --> G

    G --> H[Model Reasoning]
    H --> I[Validated Result]

The agent may need both:

  • Memory tells it what happened previously.
  • Knowledge tells it what the available sources currently say.

For example, a previous contract analysis may indicate that a clause was considered high risk. The current policy document may have changed. The agent must retrieve the latest policy instead of treating an old memory as authoritative.

Source of truth

A useful precedence model is:

  1. Current authoritative source.
  2. Explicit application policy.
  3. Verified user or project facts.
  4. Historical episodes.
  5. Inferred or uncertain memories.

This ordering is contextual, not universal. The application must define precedence for each domain.

The important rule is that historical memory must not silently override authoritative current data.


8. Memory Lifecycle: From Extraction to Retrieval

Memory architecture is not just about storing records.

It needs a complete lifecycle.

A practical lifecycle has six stages:

  1. Capture.
  2. Extract.
  3. Evaluate.
  4. Store.
  5. Retrieve.
  6. Update or forget.

8.1 Capture

The system captures information from:

  • User messages.
  • Task outcomes.
  • Tool results.
  • Execution events.
  • Explicit user corrections.
  • External data sources.

Capture does not mean every event becomes permanent memory.

8.2 Extract

An extraction process identifies candidate memories.

For example:

text
Input:
The user corrected the report format and requested
that future contract reports include a risk table.

Candidate:
The user prefers contract reports with a risk table.

The extraction process should identify:

  • Candidate content.
  • Memory type.
  • Scope.
  • Source.
  • Confidence.
  • Potential sensitivity.
  • Expiration requirements.

8.3 Evaluate

Not every candidate should be retained.

A memory evaluator can consider:

DimensionQuestion
RelevanceCould this improve a future task?
StabilityIs the information likely to remain valid?
ConfidenceIs it supported by a reliable source?
ReusabilityCould multiple future tasks benefit from it?
SensitivityIs storage allowed under applicable policy?
RedundancyDoes an equivalent memory already exist?
RetentionHow long should it remain available?

The system should not treat one model's confidence score as proof that a fact is correct.

For important memories, provenance and explicit verification are more valuable than an uncalibrated confidence number.

8.4 Store

The storage layer assigns an identifier and persists the validated record.

It should preserve:

  • Memory type.
  • Scope.
  • Source.
  • Timestamp.
  • Version.
  • Status.
  • Retention metadata.

8.5 Retrieve

The retrieval system searches for relevant memories when a task needs them.

It should return a small set of useful records, not the entire memory database.

8.6 Update or forget

Memory can become outdated.

The system needs explicit mechanisms for:

  • Updating facts.
  • Expiring temporary information.
  • Superseding older versions.
  • Marking conflicting records.
  • Deleting records when required.
  • Preserving audit history where legally and operationally appropriate.

Complete lifecycle

flowchart TD
    A[Messages and Execution Events] --> B[Candidate Extraction]
    B --> C[Type and Scope Classification]
    C --> D[Memory Evaluation]

    D --> E{Accept?}
    E -->|No| F[Discard or Temporary Retention]
    E -->|Yes| G[Deduplication and Conflict Check]

    G --> H[Memory Storage]
    H --> I[Retrieval]
    I --> J[Context Assembly]

    H --> K[Consolidation and Expiration]
    K --> L[Update, Supersede, or Delete]

9. Memory Retrieval and Relevance

A memory system can store millions of useful records and still fail if it retrieves the wrong information.

Retrieval should be based on the current task.

Consider:

Compare this contract with the version we reviewed last week.

The retrieval system should search for memories related to:

  • The same contract.
  • The previous analysis.
  • The relevant version.
  • The earlier risk findings.

It should not retrieve unrelated user preferences or experiences from other projects.

Retrieval dimensions

A practical retrieval system can use:

  • Memory type.
  • Entity or project identifiers.
  • Task type.
  • Tenant and user scope.
  • Time range.
  • Validity status.
  • Explicit relationships.
  • Textual or semantic similarity, when appropriate.

Structured filtering first

If the current task contains a known contract ID, use it.

ts
type MemoryQuery = {
  types: Array<
    "episodic" | "semantic"
  >;

  scope: {
    tenantId?: string;
    projectId?: string;
    userId?: string;
  };

  entityIds?: string[];

  taskType?: string;

  limit: number;
};

A query that filters by project and entity can be more precise than searching the entire memory database.

Ranking relevant memories

After applying hard filters, the system may rank candidates.

A conceptual score:

text
score(m, q) = w_r * relevance(m, q)
            + w_f * freshness(m)
            + w_c * confidence(m)
            + w_u * utility(m)

Where:

  • relevance measures how well the memory matches the task.
  • freshness measures whether the memory is still current.
  • confidence reflects the quality of supporting evidence.
  • utility estimates whether using the memory can improve the task.

These values should be normalized and calibrated using retrieval evaluation data.

Some dimensions should be hard filters rather than score components.

For example, a memory from another tenant must not become eligible simply because it has a high relevance score.

Retrieval should be task-aware

Different task types need different memory.

Current taskUseful memory
Continue an executionWorking Memory and checkpoints
Repeat a failed workflowRelevant Episodic Memory
Understand a projectSemantic Memory
Apply a company policyLong-Term Knowledge
Compare document versionsHistorical analysis and document references

This prevents unnecessary context from entering the model.


10. Memory Consolidation, Updates, and Forgetting

A memory system that only adds records will eventually become noisy.

The system needs a way to consolidate repeated experiences and resolve outdated information.

10.1 Consolidation

Suppose the agent repeatedly encounters scanned contract appendices.

It records several episodes:

text
Episode 1: OCR recovered a scanned appendix.
Episode 2: OCR recovered a scanned appendix.
Episode 3: OCR recovered a scanned appendix.

A consolidation process may derive a semantic memory:

text
Document extraction should detect scanned pages
and apply OCR when text extraction coverage is incomplete.

The episodes remain available as provenance, while the generalized rule becomes easier to retrieve.

Consolidation should not erase important exceptions or transform a small number of observations into a universal rule.

10.2 Deduplication

The same fact may be extracted multiple times.

For example:

text
Project ABC uses PostgreSQL.
Project ABC uses PostgreSQL as its primary database.
The primary database for Project ABC is PostgreSQL.

These records may describe the same fact.

A deduplication process should compare:

  • Subject.
  • Predicate.
  • Object.
  • Scope.
  • Validity.
  • Provenance.

The system should merge equivalent records only when their meaning and scope genuinely match.

10.3 Conflict resolution

Consider two records:

text
Project ABC uses Policy Version 2.1.
Project ABC uses Policy Version 2.2.

The system should not arbitrarily choose one.

It should inspect:

  • Source timestamps.
  • Effective dates.
  • Authority of the source.
  • Whether the newer version supersedes the old one.
  • Whether both versions apply to different time periods.

A useful representation is temporal validity:

text
Policy 2.1:
Valid from: October 1
Valid until: November 14

Policy 2.2:
Valid from: November 15
Valid until: Current

This preserves historical accuracy.

10.4 Forgetting

Forgetting is a core memory operation.

Some information should be retained only temporarily.

Examples:

  • Temporary task instructions.
  • Expired credentials or access references.
  • Short-lived execution observations.
  • Outdated preferences.
  • Records that a user requests to remove.

Memory records should support:

  • Expiration.
  • Supersession.
  • Deletion.
  • Retention policy enforcement.

A deleted memory should not reappear through another copy, cache, summary, or derived record.

The system therefore needs deletion propagation and provenance tracking.

Memory lifecycle state

stateDiagram-v2
    [*] --> Candidate
    Candidate --> Active: Accepted
    Candidate --> Rejected: Not useful

    Active --> Updated: New evidence
    Active --> Superseded: Replaced by newer fact
    Active --> Expired: Retention ended
    Active --> Deleted: Removal requested

    Updated --> Active
    Superseded --> [*]
    Expired --> [*]
    Deleted --> [*]
    Rejected --> [*]

11. Memory Architecture and Data Model

The architecture should separate memory operations from the agent's reasoning process.

The agent should request memory through an interface rather than directly querying storage tables.

Memory service interface

ts
type MemoryCandidate = {
  type: "episodic" | "semantic";
  content: string;

  scope: {
    tenantId?: string;
    projectId?: string;
    userId?: string;
  };

  sourceId: string;
  confidence?: number;
};

type MemoryRecord = {
  id: string;
  type: "episodic" | "semantic";
  content: string;

  scope: MemoryCandidate["scope"];

  sourceId: string;

  createdAt: string;
};

interface MemoryService {
  extract(
    input: {
      executionId: string;
      events: unknown[];
    },
  ): Promise<MemoryCandidate[]>;

  store(
    candidates: MemoryCandidate[],
  ): Promise<MemoryRecord[]>;

  retrieve(
    query: MemoryQuery,
  ): Promise<MemoryRecord[]>;

  update(
    memoryId: string,
    content: string,
  ): Promise<void>;

  delete(
    memoryId: string,
  ): Promise<void>;
}

This is a simplified application contract. In a production system, update operations should support version checks, deletion should be scope-aware, and candidate types should be represented with validated schemas.

Separate interfaces for different memory types

As the system grows, a single generic interface may become too broad.

A more explicit design can separate operations:

ts
interface WorkingMemoryStore {
  get(executionId: string): Promise<WorkingMemory | null>;

  save(memory: WorkingMemory): Promise<void>;

  delete(executionId: string): Promise<void>;
}

interface EpisodicMemoryStore {
  append(memory: EpisodicMemory): Promise<void>;

  search(query: MemoryQuery): Promise<EpisodicMemory[]>;
}

interface SemanticMemoryStore {
  upsert(memory: SemanticMemory): Promise<void>;

  search(query: MemoryQuery): Promise<SemanticMemory[]>;
}

This gives each store a clearer lifecycle and data contract.

Storage choices

Memory typeTypical storage
Working MemoryRedis, relational database, runtime checkpoint store
Episodic MemoryRelational database or event-oriented storage
Semantic MemoryRelational database, graph database
Long-Term KnowledgeDocument store, object storage, search index

These are starting points, not mandatory technology choices.

For many applications, PostgreSQL can support the first three categories through separate tables and indexes. A separate graph database or vector database should be introduced only when the retrieval workload justifies it.

Logical architecture

flowchart TB
    A[Agent Runtime] --> B[Memory Facade]

    B --> C[Working Memory Manager]
    B --> D[Episodic Memory Manager]
    B --> E[Semantic Memory Manager]
    B --> F[Knowledge Retrieval Adapter]

    C --> G[(Checkpoint Store)]
    D --> H[(Experience Store)]
    E --> I[(Fact and Relationship Store)]
    F --> J[(Knowledge Base)]

    K[Memory Extraction] --> B
    L[Memory Consolidation] --> B
    M[Retention and Deletion] --> B

The Memory Facade provides a consistent entry point while preserving specialized behavior underneath.


12. Security, Privacy, and Memory Governance

Memory creates a long-lived data surface.

A security mistake can affect many future executions, not just one conversation.

12.1 Scope isolation

Every memory retrieval must enforce its access scope.

A user must not retrieve another user's private memory.

A project must not inherit facts from an unrelated project merely because the text is similar.

Tenant isolation should be enforced in the storage and authorization layers, not only in an LLM prompt.

12.2 Treat stored content as untrusted input

An agent may store information extracted from:

  • User-provided documents.
  • Websites.
  • Tool responses.
  • External messages.

These sources may contain prompt injection or malicious instructions.

Storing the content does not make it trusted.

Retrieved memory should retain source and trust metadata. The runtime must not interpret arbitrary stored text as executable instructions.

12.3 Sensitive information

A memory extraction pipeline should identify information that must not be stored or requires special handling.

Examples include:

  • Credentials.
  • Authentication tokens.
  • Personal sensitive information.
  • Confidential business data.
  • Financial records.

The exact policy depends on the application and applicable regulations.

12.4 User control

Users and administrators may need to:

  • Inspect stored memories.
  • Correct inaccurate information.
  • Request deletion.
  • Configure retention.
  • Restrict memory to a particular project.
  • Disable memory for certain workflows.

12.5 Provenance and audit

For every important memory, the system should be able to answer:

  • Where did it come from?
  • When was it created?
  • Who or what created it?
  • Which execution used it?
  • Was it updated?
  • Which source superseded it?

Without provenance, debugging memory-related errors becomes difficult.


13. Evaluation and Observability

A memory system should be evaluated by how much it improves future task performance.

The number of stored records is not a useful quality metric by itself.

Retrieval evaluation

Build test cases containing:

  • A user request.
  • Relevant memories.
  • Irrelevant memories.
  • Conflicting memories.
  • Expired memories.
  • Restricted memories.

Evaluate:

MetricPurpose
Recall@KAre relevant memories retrieved?
Precision@KAre retrieved memories actually relevant?
MRRHow highly ranked is the first relevant memory?
Context utilizationDoes the agent actually use retrieved information?
Retrieval latencyHow long does retrieval take?

End-to-end evaluation

A memory system can retrieve the correct record and still fail to improve the answer.

For example, the agent may retrieve an old contract analysis but incorrectly assume that it applies to a new document version.

Therefore, evaluate the complete task:

  1. Was the relevant memory available?
  2. Was it correctly interpreted?
  3. Was its freshness checked?
  4. Was conflicting information handled?
  5. Did it improve task success?

Useful memory metrics

ts
type MemoryMetrics = {
  candidateCount: number;
  acceptedCount: number;
  rejectedCount: number;

  retrievalCount: number;
  retrievalLatencyMs: number;

  relevantResults: number;
  irrelevantResults: number;

  staleMemoryUsage: number;
  conflictCount: number;

  storageBytes: number;
};

Additional operational metrics should track:

  • Memory creation cost.
  • Memory extraction latency.
  • Consolidation frequency.
  • Expiration rate.
  • Deletion completion.
  • Cross-scope access violations.
  • Memory-related task failures.

Memory quality is not memory quantity

A system that stores 100 highly useful facts may outperform one that stores 100,000 noisy summaries.

The target is not maximum retention.

It is maximum useful information with minimum retrieval noise and operational overhead.


14. Implementation Roadmap

Do not begin by building four independent databases and several AI-powered memory agents.

Start with the minimum architecture that supports real use cases.

Phase 1: Working Memory

Implement:

  • Execution-scoped state.
  • Task context.
  • Checkpoint persistence.
  • Resume and recovery.
  • Retention after completion.

This builds on the agent runtime architecture discussed in the previous article.

Phase 2: Episodic Memory

Store meaningful execution outcomes:

  • Successful workflows.
  • Important failures.
  • Recovery strategies.
  • User corrections.
  • Significant decisions.

Keep provenance and execution references.

Phase 3: Semantic Memory

Extract reusable facts from episodes.

Introduce:

  • Structured facts.
  • Explicit scope.
  • Source references.
  • Versioning.
  • Conflict detection.

Phase 4: Memory Retrieval

Implement structured filtering first.

Add ranking and more advanced retrieval only when simple filtering is insufficient.

Phase 5: Consolidation and Governance

Implement:

  • Deduplication.
  • Temporal validity.
  • Expiration.
  • Deletion.
  • Access controls.
  • Audit history.

Phase 6: Evaluation

Build test datasets and measure retrieval quality and end-to-end task improvements.

Do not introduce adaptive memory extraction or complicated ranking without evidence that it improves the system.


15. Summary

An AI agent needs more than a conversation history to operate effectively across multiple tasks and sessions.

A well-designed memory architecture separates information according to its purpose:

  • Working Memory supports the current execution.
  • Episodic Memory preserves meaningful past experiences.
  • Semantic Memory stores reusable facts and relationships.
  • Long-Term Knowledge provides access to external authoritative information.

The most important design principles are:

  1. Do not treat all stored information as memory.
  2. Separate execution state from long-term experience.
  3. Preserve provenance and scope.
  4. Retrieve only information relevant to the current task.
  5. Distinguish historical experience from authoritative knowledge.
  6. Consolidate repeated experiences carefully.
  7. Handle conflicts and outdated information explicitly.
  8. Make expiration and deletion first-class operations.
  9. Enforce authorization independently of model reasoning.
  10. Evaluate memory by its impact on future task success.

A reliable memory system is not one that remembers everything.

It is one that preserves the right information, understands where that information came from, and makes it available at the right moment.


Next article: Context Engineering for AI Agents: Building the Right Context at the Right Time.

Memory determines what information is available for future tasks. Context Engineering determines which information should enter a specific model invocation, how it should be organized, and how to stay within the model's context and execution budgets.

  • Agent memory systems
  • Working Memory in AI Agents
  • Episodic Memory
  • Semantic Memory
  • Long-Term Memory for AI
  • AI memory retrieval
  • Agent knowledge management
  • Memory consolidation
  • Context engineering
Have a similar problem?

If something here resonates with a problem you're working on, let's talk.

Let's talk
Keep reading