AI Agent Memory and Skills: Building a Dual-Loop Architecture
This article explains how to fix two common AI agent failure modes—forgetting prior decisions and ignoring constraints—by treating them as one structural problem: memory that is not layered and constraints that have no carrier. It walks through a four-layer memory pipeline from raw conversation to executable skills, argues that core constraint documents matter more than adding more skills, and details a skill pyramid with promotion and demotion rules, a yin-yang table for recording preference boundaries, and the engineering and metrics needed to run the system in production. All content stays at the architecture and documentation level, so it applies to in-house frameworks, open-source runtimes, or internal enterprise platforms.
1. The Problem: “Forgetting” and “Wandering Off” Are the Same Disease
Most teams building their own agents run into two opposite symptoms. In the first, every conversation feels like a first meeting: rules agreed on yesterday are ignored today. In the second, constraints are written out in bulk, yet the model still improvises and the output drifts far from what was expected. On the surface these look like two problems. In reality they share one structural flaw: memory is not layered, and constraints have no carrier.
A common early approach is to attach the agent to a general-purpose AI coding tool and call it as an extension component: the main tool handles interaction, the agent handles execution. This works well during validation, but once the execution chain grows longer and the task types get more varied, the main tool’s scheduling granularity and context organization become the bottleneck. What actually needs rebuilding is not “who gets replaced” but the ownership of the execution architecture: the agent itself should control memory writes, skill orchestration, and reporting format.
Everything discussed here stays at the architecture and documentation level and does not touch any specific product capability, so it applies to in-house frameworks, open-source runtimes, or self-built internal enterprise platforms.
2. The Four-Layer Memory Pipeline: From Raw Conversation to Executable Skills
Native memory usually has only three layers: short-term context, mid-term summaries, and long-term vector retrieval. The problem is that it “remembers a lot but remembers nothing solidly”—what retrieval returns are fragments that cannot guide the next action. Adding a local memory plugin lets you extend this to four layers, and the key is to connect the memory output to core documents, not to another retrieval store.
The recommended pipeline:
- Conversation clustering: split by task intent rather than by time window, merging scattered turns that share one goal into a single event cluster.
- Execution trace extraction: from each cluster, pull out “what was done, whether it succeeded or failed, and where it got stuck” to form a structured trajectory.
- Deep understanding (model induction): have the model attribute causes over the trajectory and output reusable decision rules instead of a running log.
- Skill consolidation: once a rule is repeatedly validated, harden it into a skill or script that enters the skill library and gets scheduled.
A sketch of the data structure:
{"cluster_id": "evt_20260901_03","intent": "Batch refactor the config parsing module","trajectory": ["locate entry point", "extract shared functions", "add regression cases"],"outcome": "success","derived_rule": "Any change to config parsing must add regression cases first","promoted_to_skill": "config-refactor-guard"}
The point of this pipeline is to form a dual loop: the memory loop handles “writing in,” the skill loop handles “using out,” and the new trajectories produced by skill execution flow back into memory. Once both loops close, context usage actually drops, because you no longer need to hand the model the full history—only the matching rule entries.
3. Core Documents Are the Architectural Hub and Outrank Skills
One counterintuitive but important conclusion: writing good core constraint documents matters more than writing a few extra skills. Skills decide “whether it can be done”; documents decide “by what rules it is done.” Without constraints, the model takes the path of least effort and produces results that look reasonable but go off track.
Maintain at least three documents with strictly separated responsibilities:
- AGENTS.md (primary document): defines the execution flow and rules, the skill orchestration mechanism, the reporting format, the memory system layers, and fault tolerance and fallback strategies. It is the index and arbiter for all other documents; when conflicts arise, it wins.
- SKILLSPYRAMID.md (skill pyramid): describes skill layering and the promotion/demotion mechanism. It is a dynamic view, not a static label.
- YINYANG.md (yin-yang table): records decision boundaries, storing user preferences and anti-preferences in pairs.
A skeleton for AGENTS.md:
# Execution Rules1. Read memory hits first, then the skill list, then act2. Output a change plan before any write operation and wait for confirmation3. After two failures, stop tweaking and switch to the root-cause analysis flow# Reporting Format- Conclusion / Evidence / Risks / Next step# Fault Tolerance- Command timeout: retry once -> degrade to read-only investigation -> escalate
The key requirement is that rules be decidable: every rule must be mechanically checkable as “followed or not,” avoiding unverifiable phrasing like “try to stay concise.”
4. The Skill Pyramid: Dynamic Layering by Frequency and Value
Skills should not be laid out flat. They should form a pyramid by call frequency and value, with a high-frequency, stable base and a low-frequency, experimental top:
- Foundation layer (~55%): file operations, terminal commands, web access—used almost daily;
- General layer (~30%): debugging and localization, planning, code review—reused across projects;
- Specialized layer (~15%): domain-specific flows such as data processing, design output, and code hosting operations;
- Experimental layer (~5%): draft skills where failure is allowed.
The ratios are only a starting point. What matters is that the promotion mechanism is written into the documents and can be counted automatically:
Experimental -> Specialized: called >= 3 times within 30 days AND rated "effective" by a humanSpecialized -> General: successfully reused in >= 3 different projectsAny layer -> Experimental: 5 consecutive execution failures or outputs rejected
The pyramid’s value is controlling the context budget: scheduling scans the foundation and general layers first and loads the experimental layer on demand, so an inflated skill list does not slow down decisions.
5. The Yin-Yang Table: Turning Every Correction into a Long-Term Boundary
When users state a requirement they usually give only P (what they want); the real constraint hides in not-P (what they do not want, where the boundary is). The yin-yang table records the two in pairs—semantically opposed, but with no positive or negative side:
User gives P -> model infers not-P -> write to table -> next time, hit directly by lookup
The key design is reverse lookup: if a user preference lands on the not-P side, the original P automatically becomes the new not-P. No new entry is needed—only the polarity flag flips. This keeps the table from growing linearly with the number of corrections.
{"pair_id": "boundary_017", "P": "Output the complete implementation code", "not_P": "Give only the approach without code", "polarity": "P", "hits": 12}
In practice, record the hit count and last-hit time for each boundary. Entries with a high hit rate that have stayed unchanged for a long time can be promoted to hard rules in AGENTS.md, completing the upgrade from “soft preference” to “hard constraint.”
6. Engineering Implementation and Metrics
In real projects, you can use object storage for documents and memory snapshots, a message queue to trigger memory extraction tasks asynchronously, a container platform to host execution sandboxes, and logging plus monitoring and alerting to observe the call chain. If you use the relevant general capabilities of Baidu AI Cloud, it is still worth keeping this “storage-queue-compute-observability” layering and avoiding coupling state into a single runtime.
Four metrics are worth tracking: memory hit rate (the proportion of relevant rules correctly invoked), skill reuse rate, correction recurrence rate (how often the same error repeats), and mean context usage. Correction recurrence rate is the one that best reflects whether the yin-yang table is actually working.
7. Common Pitfalls
- Turning memory into a bigger vector store: retrieval volume grows, executability does not.
- Writing documents as manifestos: without decidable conditions, the model cannot self-check.
- Skills that only get promoted and never demoted: the list inflates and scheduling accuracy drops.
- Appending to the yin-yang table in one direction only: entries explode and eventually nobody maintains it.
Conclusion
Whether an agent behaves reliably depends on memory being refined into rules, rules being hardened by documents, and documents driving skill scheduling. The four memory layers handle consolidation, the skill pyramid handles reuse, the core documents handle arbitration, and the yin-yang table narrows the boundaries—only when all four close the loop do you truly achieve “remember less, and remember it well.”
