Agent Memory and Self-Evolution: A Practical Engineering Guide

    This article explains why AI agents struggle with reliability and cost, and how to fix it through architecture rather than better recall. It covers a four-layer memory design (working memory, preferences and constraints, tasks and results, skills), the structure of a memory entry, how to turn one-off successes into versioned, contract-driven skills with promotion gates, and four engineering levers for stability and cost control: deterministic tools first, externalized state, observability, and context budgets. The conclusion frames agent usability around memory, tools, and governance.

    1. The Real Problem: Missing Architectural Layers, Not Poor Recall

    A class of agent designs built around “persistent memory plus self-iteration” has been drawing attention, and with it a debate about whether the previous generation of approaches is now obsolete. Seen from an engineering perspective, the real issue is not that the model “forgets.” It is that the system lacks clear layering: work that should be handled by deterministic programs is handed to probabilistic reasoning to retry over and over.

    Browser automation is a good example. Many agents spend a large number of turns cycling through “read the page, guess the state, click, discover the failure, replan, try again.” Every cycle refills the context from scratch, which burns compute and makes the execution path impossible to reproduce. The three pain points users report are all external symptoms of this one architectural problem:

    • Repeated onboarding: preconditions, constraints, and caveats for a complex task have to be restated every time, which amounts to training a new hire on each run.
    • Uncontrolled cost: repeated reasoning and repeated trial-and-error pack the context with redundant instructions and correction messages, and the bill climbs accordingly.
    • Random stability: the same task succeeds today and stalls tomorrow, and the cause is hard to pin down because the path itself was never fixed.

    So is “memory” plus “skill evolution” enough? No. Memory solves “knowing”; tools and orchestration solve “doing.” Both have to be in place at the same time.

    2. Layered Memory Architecture: Breaking “Remembering” into Four Engineerable Pieces

    Reliable long-term memory is not about stuffing the entire conversation history back into the context. It is about building a layered structure where information from different lifecycles lives in the right place.

    1. Session working memory: keeps only the context the current task needs, and is reclaimed when the task ends so it cannot pollute the long-term layers.
    2. Preferences and constraints layer: stores long-term preferences the user has stated explicitly (permission-usage habits, output format requirements, and so on) as structured entries rather than long natural-language passages.
    3. Tasks and results layer: records task goals, key intermediate artifacts, final results, and failure reasons, forming a searchable experience base.
    4. Skills layer: abstracts operation sequences that have been proven to work into reusable capabilities, each with a version number and applicability conditions.

    A sketch of a memory entry structure:

    1. {
    2. "id": "pref_0421",
    3. "type": "preference",
    4. "scope": "global",
    5. "content": "Prefer non-privileged execution for scripts; ask first when elevation is necessary",
    6. "confidence": 0.92,
    7. "updated_at": "2026-08-27"
    8. }

    Three design principles matter here. Writes must be filtered and deduplicated so noise does not accumulate. Retrieval must factor in relevance and time decay so you do not recall a pile of stale experience. And every entry must be auditable and rollback-able, so that when behavior goes wrong you can trace it back to a specific memory source.

    3. Skill Hardening: Turning “Did It Once” into “Does It Every Time”

    The value of the skills layer is converting one-off successful experience into a deterministic asset. A qualified skill should include an applicability description, an input/output contract, precondition validation, a failure fallback strategy, and version history.

    1. def run_skill(name: str, payload: dict) -> dict:
    2. spec = registry.get(name) # load the skill contract and version
    3. if not spec.validate(payload): # precondition check, fail early
    4. return {"ok": False, "reason": "invalid_payload"}
    5. result = spec.executor(payload) # deterministic execution, no ad-hoc reasoning
    6. if not result["ok"]:
    7. log_and_alert(result) # failures are observable
    8. return result

    One point deserves emphasis: autonomously generated skills must pass a promotion gate. A new skill is first validated in a sandbox and only enters the production registry after it meets success-rate and latency baselines. Attempts that fail validation stay in the experience layer and cannot directly affect production execution. This preserves the ability to evolve while keeping low-quality skills out of the main path.

    4. Stability and Cost: Confining Uncertainty Inside Deterministic Tools

    For interrupted runs and high cost, four paths can be tightened at the same time:

    • Deterministic first: operations with well-defined semantics, such as file reads and writes, data queries, and API calls, go to deterministic tools; the model handles planning and exception decisions only.
    • Externalized state: write the progress of long-running tasks to external storage or a message queue so that after a process interruption you resume from a checkpoint instead of starting over.
    • Observability loop: unify logs, metrics, and alerts, and set baselines for turn counts, tool failure rates, and per-task duration, with anomalies automatically triggering human involvement.
    • Context budget: set a context ceiling and compression strategy per task type, retrieving historical detail on demand instead of carrying all of it.

    On cloud infrastructure, these can be combined: a container platform to host the execution environment, object storage for checkpoints and skill packages, a message queue for task decoupling, and logging plus monitoring and alerting services for observability. These are all general capability categories; specific choices should be evaluated against scale and compliance requirements.

    5. Conclusion: The Competition Is Over Memory, Tools, and Governance

    The “who replaces whom” narrative has limited value. What actually determines whether an agent is usable is whether memory is built as a searchable, auditable layered structure, whether experience is consolidated into skills with contracts and versions, and whether high-risk, strongly deterministic actions are handed to reliable tools. Baidu AI Cloud continues to provide relevant general capabilities for agent development and deployment, helping developers achieve more stable execution at lower cost in real business scenarios.