Agent Engineering in Practice: Designing Memory, Skills, and Execution Boundaries
This article explains how to build AI agents that execute reliably rather than merely generate fluent answers. It covers a layered memory model, memory-skill feedback loops, core rule documents, dynamic skill tiers with execution contracts, preference and boundary management, failure handling and reporting, evaluation metrics, and a phased implementation order. The focus is on keeping agents controllable, auditable, and recoverable within clear boundaries.
1. From “Answering” to “Reliable Execution”
Whether an agent is practical cannot be judged only by its ability to produce fluent responses. For developers and enterprise users, what matters more is whether it can understand the task goal, choose an appropriate execution method, complete operations within its permissions, and explain results with verifiable evidence.
Problems in real applications are often not simply a lack of reasoning ability, but an execution architecture that lacks constraints. For example, the same type of task is explored from scratch every time; a problem the user just corrected reappears next time; as skills accumulate, the agent cannot select among them reliably; and after a task fails, only a vague explanation remains, with no traceable execution record.
These symptoms show that an agent needs more than a combination of a model and tools. It also needs an engineering mechanism built around memory, skills, rules, and feedback.
A fairly complete task loop can be summarized as:
Task input → goal and boundary parsing → retrieve relevant memory → select execution skill → permission check → execute and verify → report results → archive experience
Here, the model is responsible for understanding, planning, and generalizing, while programmatic components handle permission control, state management, and result validation. The two should work together rather than handing all responsibility to natural-language prompts.
2. Layered Memory: Not Storing More, but Retrieving More Accurately
1. Separate four types of information instead of stuffing all history into context
An agent’s memory can be organized into four logical layers. This is a general design method and does not mean every system must use the same implementation.
Layer 1: Conversation records.
Retain task requests, key feedback, and necessary context, mainly for traceability. This layer can contain considerable detail, but it should not by default enter the context for all subsequent reasoning.
Layer 2: Execution summaries.
Extract structured facts from conversations and operation records, such as the task goal, the method used, the actual result, the cause of errors, and verification evidence. Compared with raw records, this layer is better suited for retrieval and review.
Layer 3: Stable knowledge and preferences.
Store information that remains valid across tasks, such as user-confirmed output habits, project constraints, environment facts, and verified troubleshooting experience. Information entering this layer should have a source, an applicable scope, and an update time.
Layer 4: Reusable skills.
Turn repeatedly validated execution methods into procedures with preconditions, steps, verification methods, and exit conditions. A skill is not a one-line description of experience, but an executable unit that can be invoked, inspected, and maintained.
These four layers are not a simple one-way promotion chain. A task may only be worth keeping a summary; a piece of experience may be suitable as knowledge but not yet enough to form a skill; and an existing skill may be revised or retired as the environment changes.
2. Build a two-way feedback loop between memory and skills
Memory answers “what happened before,” while skills answer “what should be done now.” Only when the two work together can the cost of repeated exploration be reduced.
For example, if configuration loading fails several times in a row, the execution summary records the failure location and the fix. If it is further found that these problems share the same preconditions, they can be distilled into a diagnostic procedure. Later, running that procedure produces new success or failure evidence, which in turn updates the credibility of the experience.
This mechanism can be expressed as:
Execution records → experience generalization → skill candidates → validated application → feedback revision
Note that model-generated generalizations are not inherently reliable. An incorrect conclusion that enters long-term memory without validation may be repeatedly amplified in later tasks. Therefore, “candidate experience” and “validated experience” should be stored separately.
3. Set write gates for memory
At minimum, check the following conditions:
- Clear source: Is it directly confirmed by the user, detected by a program, or inferred by the model?
- Clear scope: Does it apply to the current task, a specific project, or a broader scenario?
- Reuse value: Is it likely to affect decisions again in the future?
- Resolvable conflicts: When inconsistent with existing records, can the difference be explained?
- Manageable lifecycle: Does it need to expire, be reviewed, or be deleted?
Temporary passwords, access credentials, and irrelevant personal information should not be stored long-term. For data with a genuine business need, apply minimal collection, access control, and retention-period management.
3. Core Rule Documents: Giving Execution a Stable Structure
1. Core documents should describe mechanisms, not pile up wishes
The value of a core rule document lies in making clear how the system works. At minimum, it needs to answer:
- After receiving a task, how are the goal and completion criteria confirmed?
- Under what conditions must the agent ask follow-up questions?
- How are skills selected and dependencies handled?
- Which operations require user confirmation?
- After an execution failure, how are retries, stops, or rollbacks handled?
- What information may enter long-term memory?
- What evidence must be provided when reporting?
Compared with broad requirements like “execute carefully” or “try to avoid errors,” an explicit process more easily produces consistent behavior.
For example, “before modifying an important configuration, first generate a diff list, execute after confirmation, and verify afterward that the configuration took effect” is more actionable than “modify configurations cautiously.”
2. Separate document responsibilities
Rule files can be organized by responsibility:
The master control rule document handles the workflow, rule priority, permission boundaries, and reporting requirements.
The skill governance document handles skill registration, invocation conditions, version management, and promotion and retirement mechanisms.
The preference boundary document handles user habits, applicable scope, exception conditions, and conflict resolution.
The memory governance document handles rules for writing, deduplication, updating, expiration, and deletion of information.
This avoids one file continually bloating and makes it easier to load relevant content per task. Each document should clearly define its own responsibility and avoid redefining the same rule.
3. Document constraints cannot replace program control
Natural-language rules can guide the model but cannot serve as the sole security mechanism.
For example, writing “must not delete production data” in a document does not mean the system already has reliable protection. Real limits must be enforced through permissions, tool-parameter validation, operation approval, and runtime-environment isolation.
For high-risk operations such as external sending, bulk deletion, overwrite writes, and permission changes, an independent check should be performed before the tool executes. The principle is: the model may propose an action, but it cannot bypass the authorization judgment of the execution layer.
4. Dynamic Skill Tiering: Managing Reuse Value, Not Chasing Quantity
1. Organize skills by invocation value and maturity
Skills can be divided into four types: foundational, general, specialized, and experimental.
Foundational skills handle common operations such as file reading, directory checks, and text search. These skills should have stable interfaces, clear failure behavior, and a small permission scope.
General skills cover cross-project processes such as problem diagnosis, task decomposition, code review, and result verification, focusing on abstracting reusable methods.
Specialized skills serve specific domains or scenarios and require clear applicable conditions to avoid misuse on mismatched tasks.
Experimental skills are used to validate new methods; they should limit their impact scope, keep clear records, and allow rapid deactivation.
These tiers do not need fixed proportions. In particular, avoid conflating invocation frequency, share of skill count, and maturity: a specialized skill may be invoked rarely yet carry high business value.
2. Promotion should be based on evidence
For a skill to move from experimental to stable status, it should at least:
- Complete tasks multiple times in matching scenarios;
- Have clear input conditions and failure boundaries;
- Produce output that can be verified by an independent check;
- Have explainable requirements for the environment and implicit dependencies;
- Have a stop or recovery plan when exceptions occur.
Cross-project reuse can serve as evidence of generalization, but promotion should not be decided by usage count alone. Repeatedly executing the same simple task does not mean a skill can adapt to different environments.
A downgrade and retirement mechanism is also needed. When dependencies change, validation keeps failing, permission risks exist, or a more reliable alternative is available, the skill should be re-evaluated.
3. Every skill should have a minimal execution contract
A structure like the following is recommended:
Skill name: Configuration change checkGoal:Confirm the change matches expectations and identify potential impact.Inputs:Configuration file, change scope, expected behavior.Preconditions:Read permission is available; the target file is determined.Execution steps:Read the current state;Generate the change diff;Check format and constraints;Output a risk list.Verification method:Confirm the check covers the intended scope;Distinguish verified items from unverified items.Exit conditions:Stop when permission is insufficient, the file is missing, or rules conflict.Side effects:The original file is not modified by default.
Such execution contracts help reduce ambiguity in skill selection and make automated testing and human review easier.
5. Preference and Boundary Management: Turning Corrections into Queryable Rules
1. Do not treat preferences as a simple binary
When a user says they “want concise answers,” it does not mean “never give a detailed explanation in any scenario”; when a user asks for “automatic handling,” it does not mean permission to perform all high-risk operations.
Therefore, a preference record should not store only “what is wanted” and “what is not wanted.” A more reliable approach is to record conditions, scope, and exceptions together:
Preference:Prefer concise daily progress reports.Applicable scope:Routine task status updates.Exceptions:When a task fails, a risk exists, or the user asks for analysis,add the cause and evidence.Source:Explicitly confirmed by the user.
This form preserves semantic boundaries and avoids expanding a one-time local correction into a permanent rule.
2. Separate inference from confirmation
An agent can propose candidate preferences based on user feedback, but it should not treat unconfirmed inferences as facts.
For example, a user choosing a conservative approach in one task only indicates the decision tendency at that moment. Whether it becomes a long-term preference still depends on task risk, time constraints, and subsequent feedback.
For boundaries that affect permissions, privacy, cost, or irreversible operations, explicit authorization should be preferred over preference inference.
3. Keep an update history instead of directly reversing rules
When a user changes a preference, update the applicable scope, time, and version rather than simply swapping “allow” and “deny.”
The same user may well allow automatic modification in a test environment while requiring item-by-item approval in production. The system needs to preserve this conditional difference and match the correct rule at execution time.
When rules conflict, always honor the non-crossable security and compliance limits first; within the authorizable scope, then judge based on the current explicit instruction, project constraints, and historical preferences.
6. Failure Handling and Result Reporting: Making the System Recoverable and Auditable
The execution architecture must account for exception paths, not just describe the success flow.
For transient failures, use bounded retries; for missing input, request additional information; for insufficient permission, request authorization or stop; for rule conflicts, explain the conflict and do not bypass limits through repeated attempts.
Before retrying, also confirm whether the operation is idempotent. Repeated reads are usually low-risk, while repeated submissions, sends, or resource creations may produce additional side effects. In such cases, check the current state and, when necessary, introduce deduplication and recovery mechanisms.
A post-task report should include:
- The work completed;
- The methods and results actually verified;
- Items not completed or not verified;
- Changes made and their impact;
- Follow-up steps that need user confirmation.
“Operation executed” is not the same as “goal achieved.” Completion can be reported only after the acceptance criteria have been checked.
7. How to Evaluate Whether Architecture Improvements Are Effective
Do not judge optimization results by subjective experience alone. It is recommended to establish a fixed regression task set covering routine, exception, and high-risk tasks, and to record:
- Task completion rate: The proportion meeting predefined acceptance criteria.
- Repeat-correction rate: How often the same type of problem needs user correction again.
- Memory retrieval effectiveness: Whether retrieved results are relevant, accurate, and not expired.
- Skill reuse effect: Whether reuse reduces ineffective steps rather than merely increasing invocation counts.
- Permission violations: Whether unauthorized operations were attempted.
- Recovery capability: Whether state can be preserved and safely continued after a failure.
- Resource overhead: The time, context, and number of tool calls needed to complete a task.
Evaluation should weigh both quality and cost. Reducing context is not necessarily more efficient; if it causes key constraints to be missed, it may ultimately increase rework.
8. Implementation Order: Ensure Control First, Then Pursue Automation
Start with low-risk, high-frequency tasks: define completion criteria and permission scope, and establish execution records and result verification. Then organize the core rules, accumulate a small number of stable skills, and gradually introduce long-term memory and preference management.
In the early stage, there is no need to rush to have the system learn everything automatically. A “generate candidate experience → human review → limited application → feedback revision” process usually makes it easier to catch incorrect generalizations and scope misjudgments.
The core goal of agent engineering is not to make the system remember the most content, own the most skills, or perform the most actions, but to let it complete tasks in a traceable, verifiable, and recoverable way within clear boundaries. When memory has quality gates, skills have execution contracts, rules have programmatic safeguards, and results have verification evidence, an agent truly gains the engineering value needed for sustained use.
