AI Agent Memory and Skills: A Practical Guide to the Dual-Loop System

    This article presents a practical dual-loop framework for building AI agents that remember effectively, stay aligned with team standards, and reuse proven workflows. It explains the inner execution loop and the outer evolution loop, a four-layer memory architecture with metadata and retrieval rules, a constraint-first documentation layer, a tiered skill pyramid with promotion and demotion criteria, and a P / non-P decision boundary table for capturing user preferences. It also covers rollout steps, key metrics, and common pitfalls, helping teams create a stable, observable, and continuously improving agent system.

    1. The Problem: Why Agents Forget, Drift, and Fail to Reuse Experience

    In engineering practice with AI coding tools and automation agents, teams repeatedly run into three problems. The first is memory bloat: dumping the entire conversation history into the context raises token costs while diluting the information that actually matters. The second is execution drift: without clear constraints, the model improvises and produces output that does not match team standards. The third is lost experience: a successful troubleshooting path or a preference corrected by the user disappears when the session ends, so the next run starts from scratch.

    Solving all three at once requires upgrading memory and skills from two isolated modules into a mutually reinforcing loop system. Memory captures what has been done, corrected, and verified. Skills codify reusable sequences of operations. Core documents constrain how the two are combined, when they are invoked, and how results are reported.

    2. Overall Architecture: The Memory and Skill Dual Loop

    The dual loop rests on two circuits:

    • Inner loop (execution circuit): task input → constraint validation → skill orchestration → execution → result validation → reporting.
    • Outer loop (evolution circuit): execution traces → clustering and distillation → deeper understanding → write to memory or promote to a skill → refine the constraint documents in reverse.

    The inner loop ensures the current task is done correctly; the outer loop ensures the next run costs less. The two are decoupled through a shared document layer and storage layer, which keeps business logic from being hardcoded into prompts.

    A sample directory layout and its responsibilities:

    1. agent/
    2. AGENTS.md # Master constraints and orchestration hub
    3. SKILLSPYRAMID.md # Skill tiers and promotion rules
    4. YINYANG.md # Decision boundaries (P / non-P) log
    5. skills/
    6. basic/ # Basic tier
    7. general/ # General tier
    8. specific/ # Specific tier
    9. experimental/ # Experimental tier
    10. memory/
    11. raw/ # Raw conversations and traces
    12. clustered/ # Cluster summaries
    13. distilled/ # Distilled execution process
    14. semantic/ # Deep understanding entries

    3. Memory System: Consolidating Three Layers into Four

    A common industry approach splits memory into working memory, short-term memory, and long-term memory. In engineering, adding a semantic understanding layer produces a four-layer structure that moves memory from “what was stored” to “what was understood.”

    1. Raw layer (conversations and traces): stores original inputs, tool calls, and results, applying only redaction and truncation, with no semantic processing.
    2. Cluster layer (session clustering): groups entries by task goal, time window, and error type, compressing duplicated information.
    3. Distillation layer (execution process distillation): extracts key steps, failure points, and repair actions into searchable structured entries.
    4. Semantic layer (deep understanding): the model generalizes over distilled results and outputs preferences, boundaries, and causal relationships for skills and constraint documents to reference.

    The point of the four-layer consolidation is not to store more, but to store less and store it accurately. Attach metadata to each memory entry to support retrieval and eviction:

    1. {
    2. "id": "mem_0421",
    3. "type": "preference | failure | success | constraint",
    4. "scope": "global | project | task",
    5. "confidence": 0.86,
    6. "created_at": "2025-01-01T10:00:00Z",
    7. "last_used_at": "2025-01-05T12:30:00Z",
    8. "ttl_days": 90
    9. }

    For retrieval, filter by scope and type first, then rank by semantic similarity. Down-weight or archive entries that have not been hit for a long time to avoid memory expansion.

    4. Core Documents: Constraints Before Skills

    Many teams pour their effort into writing skills and neglect constraint documents. In practice, constraint documents take priority: clear constraints make skill combinations converge naturally, while missing constraints make a larger skill set more prone to conflicts.

    1. Master constraint document (AGENTS.md): the hub that spells out the execution flow, skill orchestration mechanism, reporting format, memory architecture, and fault-tolerance strategy. Include must / must-not / default clauses, each with a decidable criterion.
    2. Skill pyramid document (SKILLSPYRAMID.md): defines tiers, invocation frequency, value assessment, and promotion/demotion rules, and emphasizes that it is a dynamic view rather than a static label.
    3. Decision boundary document (YINYANG.md): records user preferences and boundaries as paired semantics, forming a lookup mechanism that keeps growing.

    A fragment of the master constraint document:

    1. # Execution Rules
    2. - Validate input legality and permission boundaries before any write operation.
    3. - Default to least privilege; for delete/overwrite, output the impact scope and wait for confirmation.
    4. - Reporting format: conclusion → evidence → risks → next steps.
    5. # Fault Tolerance
    6. - If the same skill fails twice in a row, switch to the fallback skill and report it.
    7. - If a tool times out three times, stop retrying and output diagnostic information.

    5. The Skill Pyramid: Tiers, Promotion, and Demotion

    Skills are tiered by invocation frequency × value, forming a pyramid:

    • Basic tier (~55%): high-frequency, stable capabilities such as file operations, terminal commands, and web access.
    • General tier (~30%): cross-scenario capabilities such as debugging, planning, and code review.
    • Specific tier (~15%): domain-specific workflows such as data processing, visualization, and operations on a particular platform.
    • Experimental tier (~5%): drafts and experimental skills where failure is allowed.

    Promotion and demotion need quantifiable rules to avoid arbitrary decisions:

    1. Experimental → Specific: invoked ≥ 3 times within 30 days and rated "useful" by human review
    2. Specific → General: reused across ≥ 3 different projects and the interface can be generalized
    3. General → Basic: high-frequency invocation for 60 consecutive days with a failure rate < 2%
    4. Any tier → Experimental: not invoked for 45 consecutive days, or failure rate > 15%

    Each skill should carry meta-information to support orchestration and auditing:

    1. name: code_review
    2. layer: general
    3. inputs: [diff, repo_meta]
    4. outputs: [findings, severity]
    5. permissions: [read]
    6. sla_ms: 8000
    7. fallback: static_lint

    6. The Decision Boundary Table: Recording Preferences as P and non-P

    Model user preferences as paired semantics: the user states P (what they want), the system infers non-P (what they do not want, or the boundary), and once recorded, the next run simply looks it up. The key points are:

    • Paired by construction: P and non-P are only semantically opposed, with no positive or negative value attached.
    • Reversible: if the user prefers non-P on some occasion, the original P automatically becomes the new non-P, with no new entry needed.
    • Continuously growing: every correction is summarized and written back automatically, forming a boundary library that understands the user better over time.

    Example entries:

    1. P: Output includes a minimal reproducible example
    2. non-P: Output with lengthy background and large blocks of irrelevant code
    3. P: Lead with the conclusion
    4. non-P: Lay out the process first and give the conclusion at the end

    7. Rollout Steps and Metrics

    1. Write the master constraint document first, defining the flow, reporting, and fault tolerance; run a constraint regression test with 3 real tasks.
    2. Set up the four-layer memory and the metadata specification, and connect the clustering and distillation pipeline; validate the retrieval hit rate within a single project first.
    3. Initialize the skill pyramid by classifying existing scripts into the four tiers; fill in meta-information and fallback strategies for each skill.
    4. Introduce the decision boundary table, extracting P / non-P pairs from the last 20 human corrections.
    5. Metrics: first-pass task success rate, average rework rounds, memory hit rate, skill reuse rate, average token consumption, and failure switchover success rate.

    8. Common Pitfalls

    • Adding memory without eviction: leads to context expansion and rising noise.
    • Too many skills with unclear tiers: orchestration conflicts and maintenance costs that grow exponentially.
    • Constraints written as slogans: no decidable criteria, so the model cannot execute them.
    • A boundary table written once: without a reverse-update mechanism, it cannot evolve with preferences.

    9. Conclusion

    Make memory a “small and solid” four-layer structure, make skills a pyramid that can be promoted and demoted, and connect the two with the master constraint document and the decision boundary table. Together they form a stable dual loop: execution is constrained, experience is captured, and capabilities are reusable. For teams that want agents that stay useful over the long term, the payoff of this approach lies not in any single technique but in a sustainable engineering order. Combined with general-purpose cloud capabilities such as object storage, message queues, logging services, and monitoring and alerting, the memory and skill pipelines can become a standardized system that is observable, replayable, and governable.