AI Agent Execution: Building Persistent Memory and Controlled Improvement
Reliable AI agents need more than longer conversation histories. This article explains how to separate working memory, persistent facts, and procedural skills; turn failures into reviewed, versioned improvements; and use deterministic tools for repeatable execution. It also covers task templates, runtime safeguards, memory lifecycle management, and practical metrics for evaluating cost and reliability.
Why Poor Memory Undermines Both Cost and Reliability
When developers and enterprises put AI agents into real workflows, the complaints are often similar: a task succeeds today but gets stuck at an unexpected step tomorrow; complex tasks require the same prerequisites to be explained repeatedly; and context windows fill with repeated instructions and corrections, causing inference costs to rise linearly—or even faster—as conversations grow.
These may look like three separate problems: high cost, interrupted execution, and inconsistent results. Often, however, they share a structural flaw. Steps that should be handled by deterministic software are delegated to fragile interaction loops.
An agent spends tokens observing a page, guessing its state, clicking, detecting failure, replanning, and trying again. Yet it never turns the successful path into a reusable asset. Every run effectively starts by rediscovering how the system works.
Beyond any particular product, the capabilities that matter are persistent memory across sessions, constraints learned from failures, reusable skills derived from manual adjustments, and reliable tools that replace trial-and-error automation.
Separate Three Types of Memory
There is no standard product interface for agent memory. From an engineering perspective, however, at least three layers should be distinguished. Otherwise, “better memory” amounts to pasting logs back into a prompt.
Session working memory
This includes the current goal, confirmed facts, unfinished steps, and temporary variables. It should be concise and structured, then archived or discarded when the task ends—not appended indefinitely to one conversation.Persistent facts and preferences
These are relatively stable user- or tenant-level constraints: default environments, prohibited operations, naming conventions, approval requirements, and the business systems that hold relevant data. They change infrequently and fit well in key-value or document storage. Each record should include its source and last update time so that outdated preferences do not remain active.Procedural skills
These capture the parameters, checklists, failure branches, and rollback conditions behind a task that required several manual adjustments before it succeeded. A skill is not a conversation excerpt. It is a versioned operational specification covering inputs, preflight checks, execution steps, success criteria, and known failure modes.
If only raw conversations are stored, the model must infer again which statements still apply. Extracting preferences and skills into structured records reduces repeated alignment work.
The following structure illustrates these layers; it is not a vendor-specific interface:
memory_item:scope: user | team | task_templatekind: preference | fact | skillstatement: "Do not install with elevated privileges unless the ticket explicitly requires it"evidence: "2026-03 task record #1842, corrected once by the user"confidence: 0.9expires_at: nullversion: 3
Memory writes need a validation threshold. A single mistaken statement should not immediately become a permanent rule. When new information conflicts with an existing rule, flag it for confirmation rather than silently overwriting the record.
Iterative Improvement Requires a Controlled Feedback Loop
“Learning from failure” should not mean allowing a model to modify production code, permissions, or prompts at will. That would amplify instability.
A safer feedback loop has five stages:
- Execute: Run the task using the current skills and tools, recording steps, input summaries, exit codes, and durations.
- Validate: Apply machine-checkable success criteria rather than accepting the model’s claim that the task “looks complete.”
- Diagnose: Distinguish environmental problems, tool defects, ambiguous instructions, and genuine business exceptions.
- Propose: Generate a skill patch or an additional check and place it in a review queue.
- Release: After approval by a person or policy engine, publish a new skill version and retain the previous version for rollback.
Without validation and release gates, “automatic evolution” merely stores random trial and error in a knowledge base. In enterprise settings, skill changes should receive rigor comparable to code changes: they must be auditable, reversible, and isolated by tenant.
A Shared Source of Cost and Variability: Fragile Interactions
Browser and graphical interface automation have legitimate uses, particularly for legacy systems without APIs. But when the default execution path is “inspect the screen, guess the button, fail, and replan,” three kinds of overhead follow:
- Token consumption: Each round carries page summaries, click history, and the model’s corrections.
- Latency and interruptions: Small changes in page structure, pop-ups, or authentication state can stall or break long-running tasks.
- Poor reproducibility: Execution depends on the interface state at that moment, making regression testing difficult.
A better division of responsibility assigns work to deterministic components wherever APIs, task queues, scripts, and explicit exit codes are sufficient. The agent interprets goals, selects skills, supplies parameters, explains exceptions, and decides when human escalation is necessary.
The model should not replace established capabilities such as querying databases, sending messages, writing objects, or checking monitoring data.
| Step Type | Preferred Implementation | Agent’s Role |
|---|---|---|
| Query structured data | Read-only queries or controlled APIs | Express query intent and verify the result scope |
| Archive files and artifacts | Object storage and versioned directories | Decide which artifacts to retain |
| Run long asynchronous tasks | Message queues and task state machines | Submit tasks and explain their status |
| Report failures | Logging, monitoring, and alerting | Summarize causes without replacing the alerting system |
| Operate legacy interfaces without APIs | Wrap operations in a small set of stable actions where possible | Intervene only when the wrapper fails |
For cloud-based implementations, object storage can hold skill packages and execution artifacts. Logging, monitoring, and alerting help track interruptions and retries. Message queues move long-running work out of the conversation process.
Cloud platforms such as Baidu AI Cloud generally offer services in these categories. Availability, quotas, pricing, and interfaces must be checked in the official documentation for the relevant environment. An architecture should not assume unverified performance figures or service availability.
Turn Repeated Instructions into Executable Task Templates
Repeatedly rebuilding a workflow often indicates that the task lacks a template. A reusable template should include at least:
- Goals and non-goals, explicitly defining what the agent must not do.
- Required inputs and validation rules: stop when inputs are missing rather than guessing.
- An allowlist of permitted tools and clear permission boundaries.
- A step graph defining which operations must run sequentially and which may run in parallel.
- Success criteria and sample-based checks.
- Failure stop conditions that prevent unlimited retries and escalating costs.
The following skill description is illustrative pseudoconfiguration:
name: sync_readonly_reportinputs: [report_date, tenant_id]deny: [privilege_escalation, destructive_sql]steps:- check_inputs- run_readonly_query- write_artifact- verify_row_countsuccess:- artifact_exists- row_count_within_expected_rangeon_fail:- stop_after: 2- attach_logs: true
Once the template is stable, a new session only needs the date and tenant identifier, not a fresh explanation of the entire workflow. This uses fewer tokens and is easier to test than inserting the previous conversation into the context window.
Reliability Comes from Runtime Controls
Long-running tasks often fail because process lifecycle, authentication state, and retry behavior have not been treated as system design concerns.
At a minimum, implement the following:
- Decouple tasks from conversations: The conversation submits work and queries status. The executor can restart, while progress is stored in an external state machine.
- Ensure idempotency: Repeated submissions with the same task identifier must not create duplicate side effects.
- Bound retries: Distinguish retryable network errors from non-retryable permission or data errors. Set retry limits and backoff rather than allowing open-ended replanning.
- Persist checkpoints: Save progress after each deterministic step. Recovery should resume from a checkpoint instead of reasoning through the task from the beginning.
- Provide observability: Associate each run with a trace identifier. Logs should reveal the stalled step, tool responses, and whether the task reached a human operator.
- Apply least privilege: A remembered preference such as “do not elevate privileges without approval” must become an enforced tool policy, not merely something the model is expected to remember.
Reliability metrics can be expressed in operational terms: success rate for the same template on a fixed dataset, human intervention rate, tokens and wall-clock time per task, and the proportion of interrupted tasks that can resume.
Without such metrics, “it worked today” is not evidence of dependable execution.
Memory Needs a Lifecycle
More memory is not necessarily better. Incorrect preferences, outdated interfaces, and one-off emergency procedures can all be treated as authoritative in later runs.
Practical safeguards include:
- Record evidence and applicability for each memory item.
- Require human confirmation for low-confidence or conflicting records.
- Isolate memory by project or tenant so that one team’s restrictions do not affect another.
- Regularly replay a fixed set of tasks to determine whether a new skill improves success rates or introduces regressions.
- Exclude secrets and personal information from persistent memory by default. Store a pointer to the appropriate retrieval location instead.
When learning from failure, a skill should capture what to check, not permanently hard-code a “magic” parameter that happened to work once. Parameters must be tied to the relevant environment and version; otherwise, a dependency change can make them fail consistently.
Evaluate Whether Memory Actually Improves Execution
The comparison does not need slogans. Use the same set of real work tickets for two groups: one receives only the current task prompt; the other receives reviewed preferences and skill templates. Keep tools and permissions identical.
Four observations are sufficient:
- Does the number of repeated human explanations decrease?
- Do model calls and token usage decrease before the task meets its success criteria?
- Can execution recover from an unexpected interruption without planning again from scratch?
- Do failures stop more often at explicit checkpoints rather than disappearing into interface loops without useful logs?
If these measures do not improve, first examine tool reliability, ambiguous success criteria, and unfiltered memory. Simply lengthening prompts is unlikely to address the underlying problem.
Conclusion
Agents do not gain useful memory by receiving more conversation history. They need separate stores for preferences, facts, and skills; machine-checkable success criteria and versioned releases to govern improvement; and deterministic tools for queries, archiving, queues, logging, and other established operations.
High costs, interrupted execution, and inconsistent results are often three symptoms of the same design choice. Turning experience into auditable, reversible, and testable assets gives long-running agent tasks a path from trial and error to reliable engineering delivery.
