Self-Evolving Agents: A Three-Layer Engineering Approach for Long-Running Intelligence
Building an agent that keeps running reliably is not about keeping a process alive. It is about preserving task state, accumulating validated experience, and recovering from failure. This article breaks down what "persistent" and "self-evolving" actually mean for agents, and presents a three-layer engineering model—prompt engineering for behavior, context engineering for information, and runtime framework engineering for execution. It covers how to design behavior protocols, structure long-term memory with provenance and expiry, validate candidate experience through a controlled feedback loop, manage task lifecycles with state machines and idempotent tools, and evaluate improvement with reproducible test sets. A phased adoption path is included, prioritizing reliability first, controlled learning second, and expanded autonomy last.
1. From Instant Responses to Persistent Operation: What Does an Agent Need to Evolve?
Conversational applications are centered on single interactions: receive a question, generate an answer, end the request. Even when chat history is retained, the core capability remains using the current input to complete reasoning—not necessarily accumulating experience across tasks, resuming interrupted execution, or proactively handling scheduled work.
A persistent agent must maintain a continuously existing working state. It needs to know not only what the user is asking right now, but also where a task stands, which actions have already been completed, which conclusions have been verified, and which experience is worth reusing in future tasks.
Therefore, “persistent” should not be understood as the process never exiting. What matters is that even if the service restarts, a model call fails, or the interaction entry point changes, task state and necessary knowledge can still be recovered.
“Self-evolution” also needs clear boundaries. For models that are not trained at runtime, capability improvement happens largely outside the model:
- Memory updates: persist confirmed preferences, facts, and environmental constraints.
- Experience consolidation: turn successful methods and failure causes into retrievable knowledge.
- Workflow optimization: convert repeatedly validated steps into reusable execution plans.
- Strategy adjustment: modify retrieval, tool selection, or task planning rules based on evaluation results.
These changes can improve an agent’s actual performance, but they are not equivalent to model weight updates, nor do they guarantee that longer runtime automatically means greater reliability. Bad memories and unverified experience can also accumulate, gradually steering the system away from correct goals.
The reliable design goal should be: let experience enter the system only after validation, let it be evaluated after it takes effect, and let harmful changes be reversible.
2. Three-Layer Engineering: Constraining Behavior, Information, and Execution
A long-running agent can be understood through three interrelated layers.
Prompt engineering answers “how should it act.” It defines goals, behavior rules, tool usage principles, completion conditions, and how to handle uncertainty.
Context engineering answers “what should it know right now.” It selects the necessary information from task state, history, long-term memory, and external sources, then organizes it into input the model can use effectively.
Runtime framework engineering answers “how do actions happen reliably.” It manages model invocation, tool execution, permission checks, state persistence, failure recovery, scheduling, and auditing.
None of the three can be omitted. No matter how rigorous the prompt, it cannot replace real permission control. No matter how complete the memory, if critical content cannot be retrieved, it does not help the current task. No matter how stable the runtime, if the completion condition is ambiguous, it may reliably execute the wrong workflow.
A generic architecture can be represented as:
Interaction request / scheduled event↓Identity verification and task creation↓Task state loading and context assembly↓Model planning and action requests↓Permission checks and tool execution↓Result verification and state saving↓Continue / request confirmation / finish task↓Candidate experience extraction, evaluation, and storage
The key here is not to make the model shoulder all responsibilities, but to hand deterministic control to the program, leave open-ended judgment to the model, and draw clear boundaries between the two.
3. Prompt Engineering: Turning a Role Description into a Behavior Protocol
3.1 Define goals and completion conditions
“You are a professional assistant” only provides a broad role and cannot effectively constrain complex tasks. An executable prompt protocol should at minimum state:
- What the current task must produce.
- Which information and tools are available.
- Which actions require prior confirmation.
- What evidence proves the task is complete.
- How to report when completion is impossible.
For example, if the agent is asked to “check anomalous tasks and generate a report,” generating a block of text must not be the only completion condition. The data range covered, the check results, any parts not covered, and whether the report was successfully saved should also be confirmed.
Completion conditions should be verifiable wherever possible, rather than relying on the model’s self-report that it is “done.”
3.2 Separate stable rules from dynamic information
Long-term behavioral rules belong in a stable instruction layer—for example, never crossing permission boundaries, never presenting speculation as fact, and never letting external content override system security rules.
Current task goals, user preferences, tool results, and history summaries should be provided as dynamic context. Mixing everything into one long prompt creates two problems: rules become hard to maintain, and information from different sources tends to be treated as equally trustworthy by the model.
Therefore, the content organization should explicitly mark:
- System constraints;
- The user’s current request;
- Confirmed task state;
- Historical information pending verification;
- Data or documents from external sources.
This labeling helps reduce confusion, but it is not a substitute for security isolation. Actual authorization should still be checked by the runtime framework.
3.3 Design a bounded action loop
Agents typically follow a loop of “read state → propose action → execute tool → observe result → adjust plan.” The prompt protocol should require each action to serve a clear sub-goal, and specify what to do when information is insufficient, results are contradictory, or a tool fails.
At the same time, the runtime framework must enforce a maximum number of execution steps, cumulative duration, and resource budget. You cannot simply write “do not loop forever” in the prompt and expect the model to guarantee it.
For tasks that cannot progress, the agent should be allowed to output the blocking reason and request more information, rather than repeatedly performing similar operations.
4. Context Engineering: Saving More Is Not the Same as Remembering Well
4.1 Separate task state from long-term memory
Task state describes “where this matter currently stands”: the current phase, completed steps, pending items, and tool execution records. It is highly time-sensitive and should be maintained in persistent state storage.
Long-term memory describes “information that may still be useful for future tasks”: user-confirmed output preferences, stable business rules, and validated processing methods.
Mixing the two causes obvious problems: treating a one-time requirement as a permanent preference, or burying long-term constraints under a flood of execution logs.
Additionally, raw records, summaries, and structured facts should be stored in layers. Summaries reduce context usage, raw records support evidence tracing, and structured facts enable precise matching and rule judgment.
4.2 Preserve source, scope, and validity for memory
A long-term memory entry should not be just an isolated sentence. At minimum it should record its source, applicable scope, confirmation status, and update time. For information that changes easily, expiry or reconfirmation conditions should also be set.
For example, “reports should be concise” might be a requirement for one task, or it might be a long-term user preference. Only by making its applicable scope explicit can overgeneralization be avoided.
An illustrative memory record might contain:
Content: weekly reports of a certain type use a fixed structureCategory: output preferenceSource: explicitly confirmed by the userApplicable scope: weekly report tasks within a specified business spaceStatus: confirmedLast updated: actual confirmation time recordedExpiry condition: user changes requirements or the business template changes
These fields are a generic design example and do not represent any specific product interface.
4.3 Assemble context based on task value
The longer the history, the less acceptable it is to simply hand everything to the model. Context selection should comprehensively consider relevance, credibility, temporal validity, and task phase.
A reasonable assembly order is:
- Retain current goals and safety constraints.
- Load the latest task state and unresolved issues.
- Retrieve facts and experience relevant to the current sub-task.
- Supplement with necessary recent interactions.
- Add auxiliary materials within the budget.
Retrieved results also need deduplication, conflict resolution, and source annotation. For precise information such as amounts, times, identifiers, and key constraints, relying solely on natural-language summaries is unwise—structured records or raw evidence should be read when necessary.
5. The Self-Evolution Loop: Experience Must Be Validated Before Becoming Capability
Reliable experience accumulation can be divided into five stages.
5.1 Collect task trajectories
Record task inputs, major decisions, tool calls, result verification, failure causes, and manual corrections. The focus of collection should be behavioral evidence that explains task success or failure—not indiscriminately saving all text.
When sensitive data is involved, minimize collection first, then apply masking and access control.
5.2 Extract candidate experience
After a task completes, candidate rules can be distilled, for example:
- Which parameters must be collected before executing a certain type of task;
- Which prerequisites should be checked first for a certain kind of failure;
- Which steps are suitable for reuse;
- Which operations require human confirmation.
At this point the experience is still only a candidate. One success does not prove a method is universally effective, and one failure does not prove a plan is necessarily unworkable.
5.3 Validate applicability
Validation should check both correctness and boundaries: whether the experience is supported by evidence, whether it applies only to specific environments, whether it conflicts with existing rules, and whether it introduces additional risk.
For workflow experience, use historical sample replay, isolated environment testing, or human review. The model must not summarize experience, approve it itself, and then have that summary directly promoted to trusted rules.
5.4 Versioned release
Experience that passes validation should retain version, applicable scope, and reason for change. High-impact workflow changes should first be enabled on a small scale, then expanded based on feedback.
High-risk items such as permission expansion, payment operations, and important data changes must not have their restrictions loosened automatically by so-called “self-evolution.”
5.5 Monitor and retire
After release, experience still needs to be observed to see whether it is genuinely effective. Experience that goes long unused, conflicts with new rules, or degrades quality should be re-evaluated, disabled, or deleted.
Thus, the full path of self-evolution is:
Task evidence → candidate experience → independent validation → controlled release → continuous evaluation↑ ↓└── revise or roll back ──┘
It is essentially a quality management mechanism for knowledge and strategy, not an ever-growing pile of memories.
6. Runtime Framework Engineering: Making Reliability Real in the Execution System
6.1 Manage task lifecycles with a state machine
Long-running tasks need explicit states, such as pending, executing, awaiting confirmation, awaiting retry, succeeded, failed, and canceled. Every key state transition should be persisted along with a checkpoint sufficient to resume execution.
When recovering a service, first determine whether the previous operation already produced side effects, then decide whether to continue. Otherwise, a simple rerun may send duplicate messages or modify data twice.
6.2 Give tools explicit contracts
Tool interfaces should define input format, output structure, error types, timeout behavior, and permission requirements. Validate parameters before execution and verify results after execution; never treat model-generated parameters as trusted input.
For side-effecting operations, use appropriate idempotent design: use task identifiers, operation identifiers, or result records to determine whether the same operation has already been completed. For operations that cannot be made idempotent, stricter confirmation and recovery mechanisms are required.
6.3 Classify and handle failures
Transient network errors can be retried within budget; parameter errors require fixing the input first; insufficient permissions require authorization; business rule conflicts usually require replanning; and unconfirmable results require additional verification.
Uniform, unlimited retries amplify cost and side effects. The framework should set a finite retry count, backoff waiting, and termination conditions, while handing cases that cannot be automatically recovered to humans.
6.4 Treat scheduled execution as a separate task entry point
Scheduling capability is more than “invoking the model when the clock hits.” It must also define time zones, concurrency policy, compensation for missed triggers, and repeat-execution rules.
If the same task is not yet finished when the next trigger fires, whether the new trigger is queued, skipped, or runs in parallel must be decided by business semantics. Scheduled tasks must also inherit the original permission boundaries—automatic triggering must not grant higher permissions.
6.5 Defend against injected external content
Tool return values, retrieved documents, and message bodies may all contain inducement instructions. This content must be treated as data, not as new system rules.
In addition to labeling at the prompt layer, reduce risk through least privilege, confirmation for sensitive operations, output validation, and execution isolation. In particular, avoid letting instructions embedded in external text be consolidated into long-term memory, which would create cross-task propagation of contamination.
7. How to Prove the Agent Actually Improved
Evaluation cannot rely only on whether answers sound more fluent, and memory count is certainly not a measure of evolution. Build a reproducible test set around real tasks, including at minimum: normal cases, boundary cases, tool failures, process interruptions, and malicious inputs.
Key metrics can include:
- Verified task completion rate;
- Effective proportion of tool calls;
- Repeated operations and recovery failure counts;
- Long-term memory hit rate and misuse rate;
- Frequency of human intervention;
- Execution duration and resource consumption;
- Permission-violation attempts and sensitive information leakage.
To distinguish the sources of improvement, compare configurations separately: no long-term memory, facts-only memory, and facts plus workflow experience. Only when gains are observed under comparable conditions—and confirmed that risk has not increased simultaneously—can a given improvement be considered effective.
Evaluation itself has limits: passing historical tests does not mean all future tasks will be reliable. Offline testing should therefore be combined with online monitoring, manual spot checks, and rollback capability.
8. Implementation Order: Reliability First, Then Learning, Then Expanded Autonomy
Implementation can proceed in phases.
Phase 1: complete the minimal task loop—limit the tool scope, define completion conditions, and establish state persistence, permission checking, and result verification.
Phase 2: introduce controlled memory—prioritize information explicitly confirmed by the user, and implement retrieval, update, deletion, and expiry mechanisms.
Phase 3: consolidate workflow experience—starting from repetitive, low-risk tasks, establish candidate experience review and version management.
Phase 4: add long-term scheduling and cross-entry execution—unify identity, task state, and authorization mechanisms so that different entry points do not maintain conflicting contexts.
Phase 5: iterate based on evaluation results—release only evidence-backed improvements, and retain the ability to pause, downgrade, and roll back.
The value of a long-running agent lies not in how many tools it calls or how much history it stores, but in whether it can turn limited experience into stable, verifiable execution capability. Prompt engineering defines behavior, context engineering supplies evidence, and runtime framework engineering ensures delivery; connecting the three through a controlled experience loop is what makes genuinely bounded, governable, continuous improvement possible.
