AI Agent Memory and Skills: A Practical Dual-Loop Architecture
Build more reliable coding agents with four-layer memory, a governed skill hierarchy, and explicit execution rules. This article explains how to turn task history into reusable skills, capture corrections as enforceable boundaries, and use failure feedback to refine both memory and behavior. It also outlines migration steps, core documents, task execution order, and practical governance metrics.
The longer a coding agent is used, the more familiar its weaknesses become. It retains conversation details but misses critical constraints. It repeatedly calls temporary workarounds without developing stable capabilities. A correction changes the current response, yet the same mistake returns in the next task.
Moving an agent from “able to converse” to “able to deliver consistently” requires more than another add-on. It requires an execution architecture: core documents that constrain behavior, layered memory that controls information density, and skill promotion rules that turn experience into reusable capabilities.
1. Establish a Single Execution Owner
Many teams initially attach a new agent to an existing automation workflow. The workflow handles orchestration, while the agent supplies reasoning or runs a script at selected steps.
This is quick to deploy, but ownership becomes unclear. The workflow and the agent maintain separate contexts, creating two sets of memories and failure-handling policies for the same task. As work expands from one-off questions to projects spanning multiple days, the costs grow: repeated confirmations, conflicting context, and errors that are difficult to attribute.
A more reliable approach is to establish one execution owner. Orchestration, tool permissions, reporting formats, and memory reads and writes should follow the same rules. External capabilities should serve as replaceable storage, retrieval, or compute backends—not independently decide what the agent should remember.
Migrate responsibilities in three stages:
- Routine operations: Transfer file handling, terminal commands, and similar daily tasks first.
- Context-dependent work: Transfer planning, code review, and related tasks next.
- Domain-specific experiments: Integrate specialized experimental capabilities last.
After each stage, remove the parallel memory maintained by the old execution path. Avoid dual writes.
2. More Memory Is Not Necessarily Better
A memory system divided only into recent conversations, long-term summaries, and a few fixed facts can still push noise into long-term storage.
A more useful design has four layers, organized by processing depth. Each layer should retain only what the next layer needs.
Layer 1: Cluster Conversation Records
Group raw conversations by task, repository, time window, and failure type rather than appending them indefinitely in chronological order.
The purpose is to identify recurring patterns: similar errors, preferences, or deliverables. Unclustered casual conversation and one-off debugging output should expire by default.
Layer 2: Distill Execution Traces
Extract reproducible steps from those clusters:
- What were the inputs?
- Which tools were called?
- Which step failed?
- How was the final result validated?
Record the process, not emotional assessments or large blocks of logs. A useful trace answers: “What are the minimum necessary steps when this task occurs again?”
Layer 3: Derive Evidence-Backed Understanding
Use the model to abstract lessons from execution traces, but require every conclusion to reference specific tasks and acceptance results.
Valid conclusions include:
- The user rejects a particular output style.
- A certain category of change requires a plan before implementation.
- A particular directory must not be modified automatically.
Unsupported personality judgments and “best practices” generalized across all projects do not belong here.
Layer 4: Consolidate Skills
Promote knowledge into the skill library only after it has been repeatedly validated and can be expressed as:
- Trigger conditions
- Operating steps
- Prohibited actions
- Acceptance criteria
Skills are the output of memory processing, not copies of memory records.
Connect the Layers with Two Feedback Loops
The forward loop turns conversations into candidate experience, removes noise through process distillation, derives boundaries through deeper analysis, and promotes mature boundaries into skills.
The reverse loop begins when a skill fails in a real task. Rather than changing a prompt and hoping for improvement, write the failure back to the execution-trace and boundary layers, explicitly recording the conditions under which the skill no longer holds.
The goal is not to remember all history. It is to retain less information more reliably. Forget by default, and preserve long-term constraints only when they remain valid across tasks.
For storage, general-purpose object storage can hold raw conversations and process extracts. A retrieval index can store searchable boundaries and skill cards. Logs and monitoring can track write volume, retrieval hit rate, and misuse rate.
These are common cloud capabilities and do not require proprietary interfaces. What matters is preserving a traceable chain:
Raw evidence → distilled conclusion → skill version
3. Core Documents Matter More Than Isolated Skills
Skills and scripts define how to perform work. Core documents define what is allowed, how far execution may go, and how failures must be reported.
Clear constraints guide execution. Vague constraints leave room for fluent but irrelevant output.
Maintain at least three living documents and define their loading order.
3.1 Execution Charter
The execution charter is the central document and references the others. It should specify:
- Task handling: Clarify the objective, retrieve memory, select skills, execute, self-check, and report.
- Skill orchestration: Define when skills run sequentially and when execution must stop.
- Reporting format: Include conclusions, evidence, changes, risks, and items requiring confirmation.
- Memory architecture: Define what each layer stores, retention periods, and who may overwrite records.
- Fault handling: Set retry limits for tool failures, prohibit silent scope changes, and require questions rather than guesses when information cannot be confirmed.
Keep the charter short. Move detailed rules into topic-specific documents instead of loading the entire history into every context window.
3.2 Skill Pyramid Guide
Organize skills dynamically by invocation frequency and transferability, rather than assigning permanent labels.
An illustrative distribution is:
| Tier | Approximate share | Typical scope |
|---|---|---|
| Foundation | More than half | File operations, command execution, web or document reading |
| General-purpose | Around 30% | Troubleshooting, planning, and code review |
| Specialized | A little over 10% | Domain-specific or platform-specific operations |
| Experimental | A small remainder | Draft skills |
These proportions are governance targets, not performance metrics. Recalculate them periodically using the team’s actual invocation patterns.
Promotion rules must be verifiable. Do not move experimental skills into the default execution path based on intuition alone.
For example:
- Experimental to specialized: Require repeated successful use during an agreed observation period, with callers confirming that the results are reproducible.
- Specialized to general-purpose: Require use in multiple independent projects. The steps must remain valid after project-specific terminology is removed.
Demotion is equally important. Skills that repeatedly trigger incorrectly, depend on obsolete interfaces, or frequently fail acceptance checks should return to the experimental tier and stop loading by default.
3.3 Preference and Boundary Table
When a user states a desired outcome, P, record its counterpart, not-P, as well: unwanted styles, prohibited scope, and unacceptable side effects.
Each row should capture a semantic pair, without treating either side as inherently superior. If the user later explicitly prefers what was previously not-P, reverse the lookup direction for that pair rather than creating a contradictory record.
Every correction should be written back with:
- What was rejected
- Whether the constraint applies to one file or the whole repository
- Whether exceptions are permitted
At the start of the next task, check this table and obey matching boundaries immediately. Do not wait for the user to repeat the correction.
The table will grow, but it must remain prunable. Mark expired preferences, tastes relevant only to a single piece of copy, and entries that conflict with the execution charter without human confirmation as invalid.
The underlying method is paired and reversible: update boundaries using evidence rather than treating them as immutable doctrine.
4. Recommended Execution Order for Each Task
When a request arrives:
- Consult the execution charter and boundary table. Identify prohibited actions before doing any work.
- Match skills to the task. Search upward from the foundation tier. Do not enable experimental skills automatically.
- Execute and record selectively. Write only failed steps and key decisions into the execution-trace layer.
- Report in a fixed format. State what was done, what was not done, which boundaries governed the work, which skills were called, and whether any skill should be promoted or demoted.
- Process memory offline. Run clustering and deeper analysis periodically rather than generating endless summaries during interactive turns.
Skill cards can remain plain text and need not depend on a particular framework:
Name: Plan Before Making ChangesTier: General-purposeTrigger: The change affects more than one module, or the user requests a reviewSteps: List affected areas; specify what will remain unchanged; wait for confirmation or proceed under the automatic-execution threshold defined in the charterProhibited: Broad rewrites without a plan; treating experimental skills as default stepsAcceptance: The change description matches the actual diff, and no not-P boundary in the boundary table has been violated
5. Common Failures and Governance Metrics
A full context window does not guarantee relevant behavior. When an agent retains extensive context but still answers the wrong question, raw conversations may have entered long-term memory without clustering.
A large skill library does not guarantee usable capabilities. If nobody trusts the default skill set, missing promotion and demotion rules may have allowed experimental skills to contaminate the general-purpose tier.
Repeated mistakes often mean corrections remained in the current conversation instead of becoming reversible boundary pairs.
Track process metrics rather than invented model scores:
- Is the number of long-term memory entries decreasing?
- Is rework decreasing after relevant boundaries are matched?
- Is the default-loaded skill set stable?
- Is the share of unattributable, improvised behavior decreasing?
Ordinary logs and task records are sufficient to measure these trends.
If the team already runs agents on a container platform, uses message queues for offline distillation, and relies on logging and monitoring to detect abnormal writes, release document versions and skill versions alongside prompts—not prompts alone.
General-purpose compute, storage, and observability services on cloud platforms such as Baidu AI Cloud can support this pipeline. The business team must still define and audit the memory policy, boundary table, and skill promotion rules. Infrastructure cannot replace behavioral constraints.
The practical order is straightforward: establish a single execution owner, implement four-layer memory, maintain three core documents, and govern a skill pyramid that supports both promotion and demotion.
Remembering every conversation is not intelligence. Making fewer of the same mistakes on the next task is the real value delivered by the memory-and-skills dual loop.
