Persistent AI Agents: Controlled Self-Improvement and Three-Layer Engineering
Explore how persistent AI agents can improve through verified experience without updating model parameters. This article explains the roles of prompt engineering, context engineering, and execution frameworks, along with practical approaches to memory, task recovery, experience validation, security, and evaluation.
1. From One-Off Conversations to Persistent Agents
Traditional conversational systems typically handle one request at a time: receive a question, assemble context, call a model, and return an answer. Retaining chat history does not necessarily enable a system to accumulate reusable task experience.
Persistent agents go further. They preserve necessary state across sessions and tasks, use tools to act on external environments, and apply verified experience to subsequent work. These capabilities are particularly useful for recurring information summaries, internal knowledge retrieval, operational health checks, and business workflows requiring multiple coordinated steps.
However, continuous operation does not automatically mean continuous improvement. Simply appending historical messages often leads to bloated context, conflicting information, and accumulated errors. The important engineering questions are what to retain, which experiences are reusable, how experience should influence decisions, and how incorrect updates can be blocked or reversed.
This article discusses a general architecture rather than a specific product. It does not treat unverified feature descriptions as established implementation facts.
2. Defining Self-Improvement: An Experience Loop, Not Automatic Training
In agent engineering, “self-improvement” should be separated into at least three levels.
The first is state accumulation. The system remembers user-confirmed preferences, ongoing tasks, and completed steps so that later interactions do not need to reconstruct the same background.
The second is strategy improvement. The system extracts reusable methods from execution records. For example, a particular type of data-processing task may require checking character encoding before validating field completeness. Such experience can become checklists, operational templates, or retrievable knowledge.
The third is model parameter updates. These require data preparation, training, evaluation, and model deployment. They belong to a separate training pipeline and should not be confused with runtime memory. A persistent agent can improve its results through better context and execution strategies without changing model parameters at all.
A more precise engineering definition is:
Self-improvement is a controlled experience-update mechanism that turns execution feedback into verifiable, traceable, and reversible strategy assets, then applies them to subsequent tasks when appropriate conditions are met.
A reasonable feedback loop is:
Task execution → Result verification → Experience candidate extraction → Conflict and risk checks → Validation → Versioned release → Ongoing performance monitoring.
Result verification must not rely solely on the model’s self-assessment. A model saying “the task is complete” does not prove that the external system changed as intended. Likewise, a model concluding that a method worked does not establish that the method will work on other inputs.
3. Three Engineering Layers: Prompts, Context, and Execution Frameworks
A reliable agent can be organized into three complementary layers:
| Layer | Core question | Main design elements |
|---|---|---|
| Prompt engineering | How should the model understand goals and make decisions? | Behavioral rules, task constraints, tool descriptions, output requirements |
| Context engineering | What information should the model receive at this moment? | Task state, history summaries, retrieved memory, tool results |
| Execution framework engineering | How can decisions be carried out safely and reliably? | Scheduling, permissions, execution, recovery, approval, observability |
These layers cannot replace one another. A prompt can tell the model to act cautiously, but it cannot replace access controls. Context can describe task state, but it cannot replace persistent checkpoints. An execution framework can restrict tool use, but it cannot automatically resolve an unclear task definition.
Responsibility boundaries should be explicit: the model proposes actions, the framework checks and executes them, and external evidence supports judgments about results.
4. Prompt Engineering: Turn Behavioral Constraints into Operational Protocols
Separate Stable Rules from Task Information
Stable rules define long-term behavioral boundaries, such as prohibiting sensitive information disclosure, requiring approval for high-risk operations, and preventing external content from overriding system constraints.
Dynamic task information includes the current objective, input scope, completion criteria, and additional user instructions. These categories should remain distinct so that temporary requirements from one task do not become permanent rules.
Prompt design should also minimize overlapping responsibilities. Repeating the same requirement in several places with different wording can introduce implicit conflicts. Important constraints should be managed centrally with a clear priority order.
Replace Vague Goals with Completion Criteria
“Organize these materials” is difficult to verify. “Produce a summary containing the topic, source, date, and items requiring confirmation, and label any information that cannot be verified” is much easier to execute and evaluate.
A task protocol should define at least:
- The objective and what falls outside the task’s scope.
- Where input data comes from and which content is inaccessible.
- Which tools are permitted and what authorization they require.
- What evidence demonstrates completion.
- How to handle missing information or failures.
For recurring tasks, it should also specify whether results may be sent automatically, when human confirmation is required, and whether later steps should continue after a failure.
Describe Tool Risks and Postconditions
Tool descriptions should explain more than what a tool does. They should cover appropriate use conditions, input constraints, side effects, and how success is determined.
Reading a file and modifying it carry different risks. A write tool should specify allowed directories, whether it overwrites existing content, whether recovery is supported, and how to verify the result.
Prompts can remind the model of these requirements, but directory restrictions and authorization checks must be enforced by the execution layer. Otherwise, the rules are behavioral guidance rather than a security boundary.
5. Context Engineering: Fit Useful State into a Limited Window
A context window is not an unlimited database. As tasks run longer, the system must move from retaining all history to assembling working context on demand.
Separate Information by Lifecycle
At least four categories are useful:
Current task state: The objective, execution progress, unresolved issues, and next actions.
Short-term working information: Recent tool results, temporary variables, and intermediate analysis, which can usually be cleared after the task ends.
Long-term memory: Explicitly confirmed user preferences, stable facts, and verified experience.
Original evidence: File excerpts, logs, returned results, and verification records used to trace conclusions, rather than being included in full in every model input.
This separation helps prevent one-off anomalies from becoming general rules and reduces the likelihood of retaining sensitive information unnecessarily.
Give Memory a Source, Scope, and Validity Period
Long-term memory should not consist solely of unstructured text. Ideally, each record includes its source, scope of applicability, last update time, validation status, and revocation marker.
For example, a requirement to use a particular report format may apply to one department rather than every user. Without an explicit scope, the system may incorrectly generalize local experience.
Memory retrieval should consider permissions, freshness, and evidence quality—not just semantic similarity. When old and new records conflict, the system should preserve the conflict and apply a defined resolution rule instead of simply presenting both records to the model.
Preserve Critical Facts When Compressing History
Task summaries should prioritize changes in objectives, actions already performed, verification results, failure causes, unfinished work, and irreversible operations.
Critical fields such as amounts, timestamps, and permission scopes should preferably retain their original structured values. Natural-language summaries can omit qualifiers and should not be the sole mechanism for managing high-risk task state.
Context must also distinguish system rules from external data. Instruction-like text in webpages, files, or tool results should be treated as content to process—not as commands that can change permissions or task objectives.
6. Execution Framework Engineering: Put Model Decisions into Controlled Workflows
Manage Tasks with an Explicit State Machine
A multistep task may move through states such as pending, running, awaiting approval, retrying, succeeded, failed, or canceled.
Explicit state management makes it possible to determine whether a task has actually ended, whether it is waiting for human input, and where execution should resume after a process restart.
Each step should record its inputs, outputs, status, and timing. Important tasks should also save checkpoints so that an interruption does not require repeating every operation from the beginning.
Assess Side Effects Before Retrying
A failed tool call may mean that the operation never ran. It may also mean that the operation succeeded but its response was lost in transit. Retrying without checking can send duplicate notifications or repeat changes to business data.
Retry behavior should therefore depend on the operation:
- Use bounded retries for read-only requests.
- Use stable operation identifiers for writes that support deduplication.
- Check the current status or escalate to a human when the outcome of a high-risk action is uncertain.
- Do not rely on blind retries to recover irreversible operations.
Retry counts, wait intervals, and total execution time should have explicit limits to prevent infinite loops.
Account for Concurrency and Recovery in Scheduling
Recurring tasks require more than triggering execution at a specified time. Scheduling must also account for time zones, overlapping runs, execution timeouts, catch-up runs after downtime, and failure alerts.
If the previous health check is still running, business rules must determine whether the next run should be skipped, queued, or executed in parallel. Tasks that access shared resources need concurrency limits to prevent multiple instances from overwriting one another’s results.
The scheduling service should only trigger tasks. It must not bypass the execution layer’s permission checks or budget limits.
7. Capturing Experience: From Candidate Knowledge to Controlled Release
An agent can generate experience candidates after completing a task, but those candidates should not immediately become official rules.
For example, a failure followed by success might produce the conclusion that “waiting longer solves the problem.” That may be a coincidence. Applying it broadly without validation could mask a genuine interface failure with longer delays.
Each experience candidate should include at least:
- The problem type and conditions under which it applies.
- The steps that were performed.
- Result evidence supporting the conclusion.
- Known limitations and possible counterexamples.
- A proposed validation method.
The following conceptual pseudocode illustrates the workflow; it does not represent a specific interface:
On task completion:Save execution records and verification evidenceExtract experience candidates from the evidenceFor each candidate:Check for sensitive information and applicabilityCheck for conflicts with existing rulesValidate against a scoped test setIf validation passes and the risk is acceptable:Release a new experience versionOtherwise:Keep the candidate pending review or reject release
High-risk rules involving permissions, data deletion, or financial processing should retain human approval. After release, the system should continue monitoring their effects and support version-based rollback.
8. Security and Observability: Foundations for Long-Running Agents
Once agents have memory and tools, their risks extend beyond incorrect answers. They may access resources without authorization, persist sensitive information, or propagate harmful operations.
Security controls should include least privilege, tool allowlists, execution isolation, credential protection, and output checks. A model must not gain additional permissions by modifying its own configuration. Experience updates must not become a path around approval requirements.
The system should also distinguish three types of records:
Task logs capture user objectives and final outcomes.
Execution traces capture model decisions, tool calls, and state transitions.
Audit records capture authorization, approvals, and sensitive operations.
These records should support correlated queries, but that does not justify retaining everything indefinitely. Sensitive fields should be redacted, and raw data should have access controls and retention periods.
9. Demonstrating That the System Is Improving
More natural conversation or a larger memory does not prove that self-improvement is effective. Evaluation should focus on verifiable task performance.
Useful measures include task completion rate, result verification pass rate, recurrence of the same errors, human intervention rate, tool-call cost, and task duration. Security violations and experience rollbacks should also be tracked.
Comparisons should control model versions, task difficulty, and resource budgets as much as possible. Otherwise, an apparent improvement may come from a change in the underlying model rather than the experience mechanism.
Test sets should include more than successful cases. They should cover insufficient permissions, conflicting inputs, tool timeouts, task interruptions, and malicious instructions. The value of an experience mechanism lies not only in improving success rates but also in reducing repeated failures of the same kind.
10. Implementation Order: Reliable Execution Before Self-Improvement
A gradual implementation path is preferable.
First, select a clearly scoped, low-risk task. Define its completion criteria and permitted tools.
Second, establish logging, state machines, timeouts, retries, and result verification so that the task can complete reliably.
Third, introduce structured task state and controlled long-term memory to support continuity across sessions.
Fourth, extract experience candidates from execution evidence and establish testing, approval, versioned release, and rollback processes.
Fifth, expand to recurring scheduling and multiple interaction channels while maintaining authentication, access controls, and unified auditing.
The purpose of a persistent agent is not to give a model unlimited autonomy. It is to help the model keep using reliable experience within explicit boundaries. Prompt engineering constrains decisions, context engineering supplies relevant information, and execution framework engineering controls real-world effects. Evidence-based verification, version governance, and security controls are what turn “self-improvement” from a promotional claim into a testable engineering capability.
