The Evolution of Agent Memory: Toward Persistence and Self-Improvement

    This article traces the evolution of AI agent memory across three generations, from short-term context to retrieval-based memory and finally to persistent, self-evolving memory. It explains the four core characteristics of third-generation memory, compares structured text files and layered architectures as storage designs, and details a self-improvement loop that makes memory more accurate over time. It also provides an engineering checklist covering isolation, cost, observability, evaluation, and cloud implementation. Readers will learn how to build a persistent, reliable agent memory system that works beyond a single session.

    1. The Starting Point: Why Agents Need Memory

    LLM-powered agents perform well within a single session, but once the session ends, the context window is cleared. User preferences, project conventions, and lessons from past failures accumulated earlier all reset to zero. A common pain point for developers is having to re-explain the background every time a new task begins, seeing the same mistake repeat across different sessions, and being unable to reuse intermediate conclusions from multi-step tasks. Without memory, an agent remains at the stage of a “stateless function” and struggles to support long-term collaboration.

    The industry typically divides agent memory into three generations. The first generation is short-term context memory, which relies on prompt concatenation and in-window conversation history. Its capacity is limited by the model’s context length, and its cost grows linearly with each turn. The second generation is retrieval-based memory, which writes historical fragments into a vector store and injects them into the prompt after similarity-based recall. This solves the capacity problem but introduces challenges around recall noise, timeliness, and consistency. The third generation, expected to mature around 2026, aims for persistence and self-improvement: memory persists across tasks and sessions over the long term and can be automatically corrected and enhanced during use.

    2. Core Characteristics of Third-Generation Memory

    The first characteristic is persistence. The authoritative copy of memory no longer exists only in the model context or a temporary cache. Instead, it resides on a medium that survives across processes and restarts, remaining readable after a process restart or service migration.

    The second characteristic is structure. Memory is not a pile of unlabeled text but a set of entries with type, scope, time, and confidence—for example, user preferences, project conventions, task conclusions, and failure patterns—each with its own lifecycle and conflict-resolution rules.

    The third characteristic is evolvability. The system has a self-improvement loop: execution results are evaluated and written back to memory, outdated entries are down-weighted or archived, and duplicate entries are merged, forming a positive feedback loop that becomes more accurate with use.

    The fourth characteristic is governability. Memory involves privacy and compliance, so it must support isolation by user and by tenant, as well as viewing, exporting, deletion, and retention-period control, preventing memory from becoming a “black-box liability.”

    3. Storage Design: Why Structured Text Files Remain a Preferred Choice

    A typical engineering choice is to use structured text files as the persistence medium. For example, a main memory file records long-term stable preferences and conventions, an agent instruction file records role constraints, tool-usage conventions, and output format requirements, and note files under a task directory store interim conclusions.

    The advantage of this approach is auditability and versionability. Text files naturally fit version control: changes can be diffed, rolled back, and reviewed. Developers can directly fix incorrect memory with an editor without writing migration scripts. It is also easy to include memory in a code repository, enabling sharing within a team and evolution alongside the project.

    An example memory entry format can be:

    1. <!-- memory: type=preference scope=user/1024 ttl=180d confidence=0.9 -->
    2. - Reply in Simplified Chinese; keep code comments in English
    3. <!-- memory: type=convention scope=project/demo repo -->
    4. - Unit tests and static checks must pass before committing

    The key point is that each memory entry carries its own metadata: type, scope, validity period, confidence, and source. Memory without metadata cannot be governed and eventually degrades into a pile of noise.

    4. Architecture Design: A Three-Layer Persistent Structure

    Another mature pattern is a three-layer architecture. The context compression layer distills long history into summaries and key facts when the window is constrained, controlling injection cost. The index layer typically uses an embedded relational database to store entries, tags, timestamps, and the indexes needed for similarity retrieval, handling exact queries and filtering. The persistence file layer stores the full original text and attachment references, serving as the ultimate source of truth. The three layers have clear responsibilities: the compression layer manages “how much fits right now,” the index layer manages “how to find it quickly,” and the file layer manages “what to keep permanently.”

    The write path should follow the order of landing files first, building the index next, and generating summaries last, ensuring the index can be rebuilt without losing the original text. The read path first performs structured filtering by scope and time, then similarity recall, and finally re-ranking by confidence and freshness, injecting only a small number of high-value entries into the prompt.

    1. def recall(query, scope, k=5):
    2. # 1) Structured filtering: scope, TTL, tenant isolation
    3. cands = index.filter(scope=scope, ttl_alive=True, tenant=ctx.tenant)
    4. # 2) Similarity recall
    5. hits = cands.vector_search(query, limit=k * 4)
    6. # 3) Re-ranking: confidence * freshness * hit relevance
    7. hits = sorted(hits, key=lambda x: x.confidence * x.freshness * x.score,
    8. reverse=True)[:k]
    9. return [files.load(h.doc_id) for h in hits]

    5. The Self-Improvement Loop: Making Memory More Accurate with Use

    The loop consists of four steps: execute, evaluate, extract, and write back. After a task ends, the evaluation step determines success or failure and user feedback. The extraction step distills reusable information into candidate memory. The write-back step performs deduplication, merging, conflict resolution, and down-weighting. Conflict resolution can use a simple rule: for the same type within the same scope, a new entry replaces the old one while preserving the historical version; entries with confidence below a threshold go into a pending-confirmation area and are not directly injected.

    The boundary must be emphasized: automatic write-back must set a whitelist and sensitive-information filtering to avoid writing keys and private data into long-term memory. A manual confirmation switch should also be retained, so that key convention-type memory takes effect only after human review.

    6. Engineering Implementation Checklist

    • Isolation and compliance: separate databases and files by tenant and user, provide export and thorough deletion capabilities, and set retention periods.
    • Cost and latency: control the number of injected entries and summary length, use hot/cold tiering, and archive history to low-cost storage.
    • Observability: log the entries and hit reasons for each recall to help troubleshoot “memory pollution.”
    • Evaluation mechanism: build a cross-session benchmark set and measure three metrics: memory hit rate, task success rate, and injection cost.
    • Cloud implementation: persistence files can be stored in object storage, indexes and metadata in a relational database, task scheduling and runtime in a container platform, and tracing and metrics in logging and monitoring services. These are all general-purpose capability combinations that do not require binding to a specific vendor.

    The essence of third-generation memory is to move an agent from being “smart within a session” to being “reliable over the long term.” Structured media solve auditability, the layered architecture solves capacity and speed, and the improvement loop solves accuracy. Only when the three are combined do they form an operable memory system. Baidu AI Cloud can provide support at the general infrastructure level, and developers can compose these capabilities as needed to build their own persistent agent memory.