AI Agent Engineering Practices: Designing Memory, Skills, and Execution Boundaries
This article explores the engineering practices necessary for building reliable AI agents, focusing on memory systems, core rules, skill frameworks, and execution boundaries. It details how to structure agent memory layers, draft enforceable execution rules, grade skills based on reliability, and manage user preferences. Additionally, it provides a framework for evaluating architecture optimizations and a step-by-step guide for implementing these practices from small-scale loops to full production.
1. Evaluating an Agent: Start with Execution System Reliability
When developers evaluate whether an AI agent is effective, they typically start with intuitive questions: Can it complete tasks? Does it frequently repeat mistakes? Is tool calling stable? Does it require continuous human correction? However, these behaviors are not determined solely by model capabilities; they are also heavily influenced by context organization, tool permissions, execution workflows, and experience reuse mechanisms.
For example, when asked to “fix a code issue,” an unconstrained agent might directly modify the file while ignoring compatibility, testing requirements, and the scope of changes. Conversely, an agent with clear execution guidelines will first confirm the issue, check relevant context, formulate a modification plan, and then verify the results and report back.
Therefore, the focus of agent engineering is not merely stacking more tools, but establishing an execution system capable of coordinating tools, knowledge, and permissions. This system can be divided into four interconnected components:
- Memory System: Stores valuable long-term information and retrieves it at appropriate times.
- Core Rules: Dictate task processing workflows, permission boundaries, and result requirements.
- Skill System: Encapsulates repeatable methods to reduce repetitive reasoning costs.
- Feedback Mechanism: Transforms successful experiences and user corrections into verifiable improvements.
When these four parts form a closed loop, an agent can evolve from a one-off Q&A tool into an execution assistant with stable working methods.
2. Layered Memory: Accuracy Over Volume
1. Distinguishing Records, Experiences, and Skills
Raw conversations, execution logs, and reusable experiences represent different information forms and should not be mixed in the same long-term storage.
Conversations record “what happened”; experiences describe “what works under what conditions”; skills answer “how to repeat this type of task step-by-step.”
An actionable four-layer structure is as follows:
| Layer | Main Content | Primary Role |
|---|---|---|
| Record Layer | User input, tool results, execution logs | Support backtracking and auditing |
| Event Layer | Goals, constraints, actions, and results organized by task | Reduce retrieval noise |
| Experience Layer | Conclusions, preferences, and failure causes with applicable conditions | Support subsequent decision-making |
| Skill Layer | Input requirements, execution steps, validation methods, exception handling | Support workflow reuse |
This is a general design scheme, and not all agents require identical native layers. During actual deployment, layers can be merged appropriately based on task scale and storage costs.
2. From Conversation Clustering to Experience Extraction
Conversation clustering should not rely solely on keyword similarity. Even if two tasks both involve “file processing,” their goals might be document organization versus sensitive data cleaning, representing completely different execution boundaries.
More reasonable archiving dimensions include task goal, work object, constraints, execution environment, and result status. After each task, a brief event summary can be generated:
Task Goal: Adjust data export workflowConstraints: Maintain existing field meanings, do not change external contractsActions Taken: Modify transformation logic, add edge casesValidation Result: Checked both normal inputs and missing value scenariosFailure Experience: First modification missed null handlingReusable Conclusion: When field transformation is involved, list abnormal input types first
Such summaries are easier to retrieve than entire conversations and retain the key information that influences decisions.
3. Model Extraction Needs Evidence Constraints
When using language models to summarize experiences, be careful to prevent guesses from being written as facts. It is recommended to attach source, time, scope of application, and confirmation status to each long-term memory entry.
For example, “user dislikes long reports” is too broad; “in daily progress reports, the user prefers conclusions first, then details on demand” is much more actionable.
Low-confidence conclusions should be marked as pending and should not immediately become default rules for all tasks. Experiences involving security, permissions, finance, or production environments must never be automatically upgraded to execution basis based on a single conversation.
4. Controlling Memory Lifecycle
Long-term memory needs updating and deletion. Project specifications may change, user preferences may shift, and the causes of historical failures may become invalid after system upgrades.
The following governance mechanisms can be established:
- Merge semantically duplicate entries to avoid retrieving the same conclusion multiple times.
- Retain timestamps and context for contradictory records instead of directly overwriting them.
- Set expiration dates for temporary requests to prevent them from solidifying into long-term preferences.
- Implement minimal retention and access control for sensitive information.
- Periodically review expired rules to reduce the misleading impact of historical information on current tasks.
“Less but reliable” memory is not about blindly compressing content, but retaining sufficient evidence and applicable conditions while deleting content that is no longer useful.
3. Core Rules Document: Writing Execution Methods as Verifiable Contracts
1. Core Rules Orchestrate, Not Do Everything
Skill documents typically describe how to perform a specific type of task, while core rules determine when to use skills, which actions require confirmation, and how to handle execution failures.
An effective set of core rules should at least cover:
- Task understanding and clarification conditions.
- Tool usage and permission scopes.
- Plan formulation and execution steps.
- Skill retrieval and combination methods.
- Result validation and reporting requirements.
- Memory read/write conditions.
- Exception handling and human takeover mechanisms.
It must be emphasized that documentation only provides behavioral guidance and cannot replace actual access control. High-risk actions must be validated by the execution layer, not just by relying on the model “remembering not to do it.”
2. Convert Vague Requirements into Specific Actions
Requirements like “operate carefully” or “ensure quality” are difficult to verify directly. These should be broken down into specific behaviors, for example:
When modifying persistent data:1. Clarify the target object and scope of change.2. Check if the current identity has operation permissions.3. Request manual confirmation for irreversible or large-scale changes.4. Retain recovery points or backups when conditions permit.5. Verify actual status after execution.6. Report completed items, unverified items, and remaining risks.
The more specific the rules, the easier they are to test and audit. However, all details should not be crammed into the core document, as this would increase context burden. Core documents should retain stable principles, while specific operations should be loaded on demand via task-related documents.
3. Define Conflict Resolution Order
In actual tasks, security requirements, project specifications, current user instructions, and historical preferences may conflict. Priorities need to be defined in advance:
- Legal, security, and mandatory permission boundaries cannot be overridden by preferences.
- Explicit organizational and project specifications take precedence over general habits.
- Explicit requirements of the current task usually take precedence over historical preferences.
- Auto-inferred preferences cannot override explicitly expressed user instructions.
If a conflict cannot be resolved automatically, the related operation should be paused and clarification requested, rather than choosing a convenient interpretation for execution.
4. Skill Grading: Managing Capabilities by Reliability and Reuse Value
1. Grading is Not a Fixed Ratio Allocation
Skills can be categorized by maturity and scope into basic, general, specialized, and experimental layers, but there is no need to preset fixed proportions. Different teams have vastly different task structures, and fixed ratios easily lead to formalized management.
More attention should be paid to:
- Call Frequency: Is it frequently used?
- Reuse Scope: Is it effective across tasks and projects?
- Reliability: Does it have stable validation results?
- Risk Level: Could failures cause severe impacts?
- Maintenance Cost: Will it easily fail after environment changes?
High frequency does not mean low risk, and low frequency does not mean low value. For instance, a recovery process might be rarely invoked but must possess high reliability.
2. Skills Should Include Validation and Exception Branches
Mature skills should not just be a few operational steps; they also need clear inputs, preconditions, success criteria, and failure handling:
Skill Name: Change ValidationApplicable Scope: Local adjustments to existing programsInput: Change target, related files, acceptance criteriaPreconditions: Can read necessary context, possesses required execution permissionsExecution Flow:- Confirm behavioral changes and impact scope- Check normal and edge scenarios- Execute available validation workflows- Compile results against acceptance criteriaException Handling:- If runtime environment is missing, explicitly mark unverified parts- If scope expands, pause and re-confirmOutput: Validation evidence, known issues, remaining risks
Here, “unverified” must be strictly distinguished from “verified.” This is a crucial constraint to prevent agents from overpromising.
3. Upgrades and Downgrades Must Be Based on Evidence
Experimental skills do not automatically upgrade after multiple uses. It is necessary to check whether the tasks were sufficiently diverse, whether they relied on implicit conditions, and whether failures could be explained.
Upgrade criteria can include cross-scenario validation, input/output stability, repeatability, and clear maintenance responsibility. Conversely, when environments change or failures increase, skills should be downgraded, disabled, or re-verified.
For high-risk skills, manual review and independent validation phases should be set up; agents should not be allowed to publish based solely on their own summaries.
5. Preferences and Boundary Management: Record Opposing Choices but Avoid Absolute Rules
1. Preferences Need Context
Recording “what is wanted” and “what to avoid” in pairs helps reduce repetitive corrections. For example:
- Want short conclusions first, avoid outputting massive backgrounds initially.
- Want minimal necessary modifications, avoid unrelated refactoring.
- Want key evidence explained, avoid conclusions without proof.
However, opposing relationships in natural language are not always strictly complementary in a mathematical sense. There are many intermediate states between “concise” and “detailed,” and “fast completion” and “thorough validation” are not necessarily mutually exclusive. Therefore, it is better to treat such records as decision boundaries rather than absolute binary classifications.
2. Inferred Boundaries Must Be Revocable
A user requesting to “keep the existing structure” can prompt the agent to avoid arbitrary restructuring, but it should not be inferred that the user is permanently opposed to refactoring.
A preference record should at least include the applicable scene, source, confirmation status, and exceptions:
Preference: Prefer local modificationsApplicable Scene: Daily bug fixingBasis: User explicitly requested narrowing change scopeException: Local modifications cannot solve the root cause, or user requests a redesignConfirmation Status: Confirmed
When a user chooses the opposite direction in a new task, it should be determined whether it is a temporary exception, a scene difference, or a long-term preference shift, rather than directly flipping all historical records.
6. Making Memory and Skills Form a Verifiable Dual-Loop
The linkage between memory and skills can be understood as two loops.
The Memory Loop is responsible for converting task processes into event summaries and conditional experiences; the Skill Loop is responsible for organizing stable experiences into execution methods, which are then tested for effectiveness through actual tasks.
The complete workflow can be expressed as:
Task input-> Read core rules-> Retrieve relevant experiences-> Select or combine skills-> Verify permissions and execute-> Validate results-> Report evidence and risks-> Extract experiences-> Review memory or skill updates
The key is to separate the judgment of “execution success” from “experience is worth keeping long-term.” A single success might depend on accidental conditions, and a single failure might stem from temporary environmental issues. Only after attribution, deduplication, and applicability scope checks should an experience enter the long-term system.
Meanwhile, retrieved external text, historical logs, and tool outputs should be treated as data, not as new high-priority instructions. Otherwise, the memory system might introduce untrusted content into the execution chain, causing permission breaches or behavioral drift.
7. How to Judge if Architecture Optimization is Truly Effective
Optimization effects cannot rely solely on subjective experience; a set of evaluation samples covering common tasks, abnormal inputs, and high-risk boundaries should be prepared.
It is recommended to track the following metrics:
- Task Completion: Does it meet acceptance criteria, rather than just generating a result?
- Manual Correction Times: Does the user still need to repeatedly explain the same boundaries?
- Memory Hit Quality: Is the retrieved content relevant, effective, and conflict-free?
- Skill Execution Stability: Can it repeat success under similar conditions?
- Boundary Violations: Are there unconfirmed high-risk actions?
- Execution Cost: Are the context size, tool call volume, and time consumption reasonable?
- Traceability: Can it explain conclusion sources, execution steps, and validation evidence?
When evaluating, fix the task set, acceptance criteria, and controlled environment, and observe the changes after introducing memory, core rules, and skill grading separately. Do not modify all modules simultaneously, or it will be difficult to determine where the improvements originated.
8. Start with a Small-Scale Closed Loop
When implementing, you can first choose a frequent, well-defined task, such as code change review or document organization. Phase 1 establishes execution rules and event summaries; Phase 2 adds confirmed preference memories; Phase 3 consolidates stable skills; Phase 4 improves version management, review, and rollback.
Throughout this process, three principles should be adhered to: unverified conclusions should not be written as facts; unauthorized actions should not enter execution; unvalidated results should not be claimed as complete.
The long-term viability of an agent comes from clear responsibility division, a maintainable knowledge structure, and verifiable execution boundaries. Memory helps reduce repetitive understanding, skills help reduce repetitive exploration, core rules help control behavior, and feedback evaluation helps the entire system continuously improve. Only when these mechanisms work together can an agent perform more stably and reliably in complex tasks.
