AI Agent Memory and Self-Evolution: How to Keep State, Reuse Experience, and Stabilize Execution

    This article explains why AI agents lose context between sessions and become unstable over long runs, and how to fix it at the engineering level. It breaks the problem down into context management, capability abstraction, and execution determinism, then proposes a three-tier memory structure (working, episodic, and semantic), a strategy for turning repeated prompt flows into versioned skills with input/output contracts, and a rule for preferring deterministic tools over UI automation. It also outlines a four-layer reference architecture, a step-by-step rollout order, evaluation based on variance rather than pass/fail, and common pitfalls such as unbounded memory, auto-modifying code without rollback, and ignoring least-privilege boundaries.

    1. The Problem: Why Agents Keep “Meeting the World for the First Time”

    Agents with long-term memory and self-iteration capability have become a hot topic in technical discussions. The core of the debate is not which model is smarter, but three engineering questions: can state survive across sessions, can experience be distilled into reusable capability, and can the execution path be reproduced reliably.

    Break those three questions apart and they map to the most basic layers of an agent system: context management, capability abstraction, and execution determinism. The familiar complaints — “every meeting starts by re-aligning on requirements” and “open a new window and it asks what step one is” — are fundamentally a missing externalized state. Meanwhile, “token burn is painful” and “it worked today and breaks tomorrow” are the combined result of weak capability abstraction and a fragile execution path.

    2. Root Cause: Three Symptoms, One Shared Source

    2.1 Repeated Context Amplifies Cost

    Complex tasks usually require preconditions, constraints, a glossary, and a history of corrections. If that information lives only in the session context, it must be re-injected every turn, input length grows linearly, and reasoning plus trial-and-error accumulate — so cost climbs. A more hidden loss is repeated correction: the model makes the same mistake, gets corrected, and makes it again in the same place.

    2.2 Insufficient Stability Over Long Runs

    Long-chain tasks often contain dozens of steps, each depending on the implicit state of the previous one. Once a step fails and there is no checkpoint or rollback mechanism, the only option is to start over. The visible result is interruption, lost context, and crashes that are hard to localize.

    2.3 Using Probabilistic Tools for Deterministic Work

    The most typical case is UI automation: identify the page, guess the state, click, judge the failure, replan, try again. This loop turns operations that a deterministic interface could complete in one call into a probabilistic task. Step count rises, failure probability compounds across steps, and cost and stability degrade at the same time.

    Conclusion: missing memory is only the surface. The deeper problem is that deterministic tasks were handed to a probabilistic execution path.

    3. Design Principles: Layering and Determinism First

    3.1 A Three-Tier Memory Structure

    • Working memory: temporary state for the current task, reclaimed when the session ends;
    • Episodic memory: task traces and failure reasons, used for review and retrieval;
    • Semantic memory: stable preferences, terminology, and environment constraints, retained long term.

    The point is not to “remember everything” but to define write and forgetting policies. Give each memory entry a confidence score, a source, and a timestamp, and allow conflict resolution:

    1. def upsert(memory, key, value, confidence, ttl):
    2. old = memory.get(key)
    3. if old and old.confidence > confidence and not old.expired():
    4. return old # Prefer the higher-confidence old value so a single accidental feedback cannot overwrite it
    5. memory[key] = Entry(value, confidence, ttl)
    6. return memory[key]

    3.2 Solidify “Prompts” into “Skills”

    When a flow has been executed repeatedly with stable results, abstract it into a capability unit with an input/output contract instead of continuing to rely on natural-language description. A skill should contain at least: precondition checks, execution steps, failure handling, and observable logs. Example:

    1. def skill_query_db(conn, sql, params, retries=2):
    2. assert is_readonly(sql), "Read-only queries only"
    3. for i in range(retries + 1):
    4. try:
    5. return conn.execute(sql, params).fetchall()
    6. except TransientError as e:
    7. if i == retries:
    8. raise SkillFailed(e) from e

    The payoff is twofold: context length drops and behavioral consistency rises.

    3.3 Prefer Deterministic Tools

    Any operation that has a stable interface should not be handed to visual recognition and guessing. The rule can be simple: if an action can be described by an explicit signature, write it as a tool; only when the interface is missing should you fall back to UI operations, and those should get stricter retry and human-confirmation thresholds of their own.

    4. Reference Architecture and Rollout Steps

    A four-layer structure — planning layer, memory layer, tool layer, execution layer — paired with unified logging and monitoring/alerting is recommended. Write each step’s input summary, latency, and failure code to a logging service so runs can be replayed and localized.

    Suggested rollout order:

    1. Externalize state first, and persist key constraints to durable storage;
    2. Then converge the tool set, replacing high-frequency UI operations with deterministic interfaces;
    3. Then extract high-frequency flows into skills, with versioning and rollback;
    4. Finally introduce an evaluation set and run regression on success rate, average step count, and cost per task.

    Evaluation cannot look only at “does it run.” Variance matters more. Poor stability is essentially high variance, and a good mean means nothing on its own.

    5. Common Pitfalls

    • More memory is better: without a forgetting mechanism, noise accumulates and hit rate actually drops;
    • Self-evolution equals auto-editing code: automated changes without validation and rollback carry very high risk;
    • Substituting longer context for engineering work: cost rises with length while marginal returns diminish;
    • Ignoring permission boundaries: for write, delete, and privilege-escalation operations, keep least privilege and explicit confirmation.

    6. Conclusion

    The dividing line for agent capability is shifting from “how smart the model is” to “how solid the engineering is.” Persist the state, solidify the experience, and give deterministic work to deterministic tools — do these three things well and cost and stability problems ease together. For teams building such systems in their own environments, general cloud capabilities such as container platforms, object storage, message queues, and monitoring/alerting can serve as the foundation for an observable, rollback-capable execution base, and the relevant general product categories from Baidu AI Cloud can also be a reference when selecting infrastructure.