Building a Four-Layer Memory and Constraint System for AI Agents

    When an agent moves from a host-plus-plugin setup to owning its own execution loop, three pieces of infrastructure become essential: memory, documents, and skills. This article explains a four-layer memory pipeline with a memory–skill dual loop, three core constraint documents, and a practical rollout order that avoids unused skills and noisy memory.

    1. Starting Point: From Add-On Assistance to Native Execution

    Many teams first connect an agent through a host-plus-plugin path: an existing AI coding tool owns the main workflow, and the newly added agent is treated as an external component that can be called. This is quick to start, but two structural problems appear soon.

    First, capability boundaries are locked by the host. Planning, execution, and reporting all depend on the host’s scheduling logic. The agent cannot define its own execution order, and it cannot degrade gracefully when something fails.

    Second, state does not accumulate. When a session ends, the context is discarded. Similar problems are solved again and again, and correction experience cannot be reused.

    Once the execution architecture is redesigned—task decomposition, tool selection, failure retry, and result reporting all return to the agent itself—the host falls from the main actor to an optional channel. What this article discusses is the infrastructure that must be filled in after that shift: memory, documents, and skills.

    2. The Memory System: Four Layers and a Dual Loop

    A native setup usually provides only three memory layers: short-term session context, mid-term task summaries, and long-term vector retrieval. The problem is that results can be retrieved but not used: what comes back is a raw fragment, not an executable conclusion.

    After a local memory-service plugin is introduced, a fourth layer can be integrated into the following pipeline:

    1. Conversation clustering → Execution distillation → Deep understanding (model induction) → Skill capture

    Each layer has a distinct role:

    1. Clustering layer: Group long conversations by intent, drop small talk and repeated confirmations, and keep only “goal—constraint—result.”
    2. Distillation layer: Extract reusable step sequences from multi-turn execution traces, not conclusion text.
    3. Understanding layer: Have the model induce causality from the distilled result and answer why this approach worked.
    4. Skill layer: Turn stable, effective patterns into callable skill entries.

    This creates a dual loop between memory and skills: memory supplies raw material for skills, and skills in turn compress the volume of memory. That is the path to “remember less, remember firmly”—not stuffing all history into context, but distilling history into a small set of high-value entries.

    In engineering practice, give each memory entry three metadata fields so later retirement is possible:

    1. memory_item:
    2. id: "mem-0421"
    3. layer: distilled # raw | clustered | distilled | skill
    4. confidence: 0.82 # reuse success rate
    5. reuse_count: 7 # hit count
    6. last_used: "2026-08-20"

    When confidence falls below a threshold and last_used is older than a set period, the entry should be archived automatically so the memory store does not degrade into a pool of noise.

    3. Core Documents: Constraints Before Capabilities

    A counterintuitive but important conclusion: at the execution-architecture level, writing constraint documents well matters more than adding skills. Skills decide what the agent can do; documents decide how it will do it. Without constraints, the model confidently produces a pile of irrelevant content.

    Maintain at least three documents.

    1. Entry Convention (the primary document)

    This is the hub that connects the other documents. It should state the execution flow and stage breakdown, skill orchestration and call priority, the reporting format, the memory-system layering, and fault tolerance and degradation. An example skeleton:

    1. # Execution Convention
    2. ## Flow
    3. 1. Parse the goal → 2. Retrieve memory → 3. Select skills → 4. Execute → 5. Verify → 6. Report
    4. ## Orchestration
    5. - Call high-frequency foundational skills directly; specialized skills must first declare their applicability
    6. ## Reporting
    7. - Lead with the conclusion, attach a change list and the verification method, and do not describe only the process
    8. ## Fault tolerance
    9. - If the same approach fails twice in a row, switch plans and write the case into the boundary table

    2. Skill Pyramid

    Organize skills by call frequency and value into a pyramid, not a flat list:

    Layer Share Contents Frequency
    Foundation 55% File operations, command execution, web access Daily
    General 30% Debugging and localization, planning, code review Weekly
    Specialized 15% Data processing, creative design, code-hosting collaboration Specific scenarios
    Experimental 5% Draft skills, patterns awaiting validation Trial and error

    The key point: the pyramid is a dynamic analytical view, not a static set of labels. It needs a promotion mechanism:

    • Experimental → specialized: effectively called more than three times within 30 days, and judged usable;
    • Specialized → general: reused successfully in three unrelated projects, and the logic can be generalized;
    • Any layer → retirement: zero hits across two consecutive periods.

    3. Yin–Yang Boundary Table

    Drawing on the pairing idea of yin and yang together with set theory, record “want / do not want” as pairs:

    1. The user gives P (the expectation) → the model infers not-P (the boundary) → execute and record → next time, a table lookup hits directly

    Three points matter. First, the boundary table is a continuously growing decision record, not a philosophical doctrine. Second, P and not-P are semantically opposed but neither is inherently positive or negative. If the user once prefers not-P, the original P automatically becomes the new not-P; a reverse lookup is enough, and no new entry is required. Third, every human correction should be rolled into the table automatically.

    1. boundary:
    2. positive: "Propose a plan and the impact surface before making changes"
    3. negative: "Do not rewrite files across a large scope directly"
    4. invert_on: "When the user explicitly asks for fast trial and error, invert this pair of constraints as a whole"

    4. Rollout Order and Common Pitfalls

    Advance in the order documents → memory → skills: set constraints first, connect memory next, and expand skills last. Doing it the other way around usually produces a pile of skills that nobody calls.

    Three common pitfalls: treating memory as a log that only grows and is never deleted; treating skills as a selling point so the count inflates while the call rate stays extremely low; and writing the boundary table as a list of bans with no inversion mechanism, which makes the model overly conservative in reasonable situations.

    To support long-running operation, general cloud capabilities can complete the foundation—for example, object storage for memory and document snapshots, and logging plus monitoring and alerts to track skill call rates and failure rates—so the system is observable and can be rolled back.