AI Agent Memory and Core Document Architecture: A Practical Guide

    This guide explains how to fix two common AI agent failures—context amnesia and behavior drift—by combining a four-layer memory system with a constraint-first core document architecture. It covers layered memory design, the dual memory and skill loops, a master document, a tiered skill pyramid with promotion and demotion rules, a paired decision-boundary table, a suggested rollout order, key metrics, and common pitfalls. Readers will learn how to make agent memory retrievable, verifiable, and reversible instead of relying on long context windows.

    1. The Problem: Why Agents “Forget” and “Drift”

    In real-world coding assistance and automated operations, teams typically run into two recurring problems.

    The first is context amnesia: preferences that were corrected repeatedly in one project are forgotten in the next session, and the model proposes a solution that was already rejected. The second is behavior drift: without explicit constraints, the agent improvises, produces large amounts of speculation unrelated to the task, and even modifies files it should not touch.

    The root cause is not model capability but execution architecture. The memory system determines whether the agent can recall; the core documents determine whether it follows the rules. Optimizing the two in isolation usually yields only local improvement. A stable loop emerges only when memory output feeds back into the documents and document constraints reshape memory.

    2. A Four-Layer Memory System: From Raw Conversations to Reusable Skills

    2.1 The Layered Design

    Single-layer vector retrieval suffers from a familiar weakness: it recalls a lot but little of it is useful. A workable approach is to split memory by abstraction level and compress information entropy layer by layer:

    1. Conversation clustering layer: group raw sessions by topic, drop small talk and repeated confirmations, and keep only task goals, key decisions, and conclusions.
    2. Execution distillation layer: abstract multi-turn tool calls into “step sequence + failure points + repair actions,” producing process memory that can be replayed and reviewed.
    3. Deep understanding layer: use the model to summarize the output of the first two layers into preferences, taboos, and scenario applicability conditions. This layer is semantic rather than textual.
    4. Skill layer: once a class of process is repeatedly validated as effective,固化 it into an invocable skill, upgrading from “memory” to “capability.”

    2.2 How the Dual Loops Run

    The memory loop handles writing: when a session ends, entries are archived automatically and preference items are updated. The skill loop handles usage: at task start, skills are retrieved first, then preference constraints. Both loops share one index, avoiding duplicate storage. The practical payoff is a significant drop in context usage—instead of stuffing entire history into the prompt, you inject a small number of high-value entries, achieving less memory but stronger retention.

    A simplified entry structure looks like this:

    1. {
    2. "scene": "frontend project scaffold initialization",
    3. "preference": "prefer the directory structure given in the task",
    4. "boundary": "do not install dependencies automatically, do not modify build config",
    5. "evidence": ["summary of the rejected proposal from session 3"],
    6. "confidence": 0.82,
    7. "skill_ref": "scaffold.init"
    8. }

    The confidence field drives decay-based ranking: low-confidence entries are down-weighted at retrieval time so that early misjudgments do not pollute decisions over the long term.

    3. Core Documents: Constraints Before Capabilities

    A counterintuitive but important conclusion: in an execution architecture, writing good constraint documents takes priority over adding new skills. Skills raise the ceiling of capability; documents set the floor of behavior.

    3.1 The Master Document

    The master document acts as the hub and needs to state explicitly: the execution flow and phase breakdown, skill orchestration and invocation order, reporting format, the layered structure of the memory system, fault tolerance and rollback strategy, and the list of prohibited operations. The recommended order is “prohibitions first, then process,” because models follow constraints placed earlier more reliably.

    3.2 The Skill Pyramid Document

    Skills should not be laid out flat but tiered by invocation frequency and value, and the tiering must come from dynamic analysis, not static labels:

    • Foundation tier (~55%): everyday capabilities such as file read/write, command execution, and network access; these must be stable and idempotent.
    • General tier (~30%): cross-project reusable capabilities such as problem localization, solution planning, and code review.
    • Specialized tier (~15%): scenario-specific capabilities such as data modeling, creative generation, and code hosting platform operations.
    • Experimental tier (~5%): draft skills and newly validated ideas, where failure is allowed.

    Quantify the promotion mechanism: an experimental entry that is invoked effectively more than three times within 30 days and receives a positive retrospective review can be promoted to the specialized tier; a specialized entry that proves effective across three unrelated projects can be abstracted into the general tier. Demotion needs rules too—for example, two consecutive cycles with zero invocations triggers a rollback—so the skill library does not bloat.

    3.3 The Yin-Yang Decision Boundary Document

    Drawing on the idea of unity of opposites and complementary sets, maintain a boundary table of paired entries: when the user expresses what they want, that becomes a positive entry, and the model reasons out what they do not want and where the boundary lies, forming a negative entry. The two are semantically opposed but equal in standing, with no primary or secondary side.

    The key design is reverse lookup: when a user preference falls on the negative side, the original positive entry automatically becomes void—no new record is needed, only a reverse lookup. Every correction is summarized automatically and written back to the table, so boundaries keep growing with the project instead of piling up into a list of mutually contradictory rules.

    1. Positive P: present a plan and impact scope before making changes
    2. Negative ¬P: no unconfirmed bulk refactoring
    3. Correction event: user asks for direct small-step edits → table lookup hits ¬P, ¬P governs this turn

    4. Rollout Order and Metrics

    The recommended sequence has four steps: first write the master document and the prohibition list; then connect the layered memory and archiving flow; next build the skill pyramid with promotion and demotion reviews; finally introduce the boundary table and enable automatic correction write-back. Three metrics are worth tracking: repeat mistake rate, share of ineffective context, and the distribution of skill reuse counts. If cloud hosting is needed, object storage can hold memory snapshots, a message queue can decouple archiving jobs, and logging plus monitoring with alerting can track invocation quality. These are all general capability categories, so select on the principle of replaceability and portability.

    5. Common Pitfalls

    One is treating memory as long context, which raises cost without improving results. Two is skills that only grow and never shrink, so retrieval noise overwhelms useful entries. Three is documents written as manifestos rather than executable rules, missing decision conditions and priorities. Four is a boundary table that records only positive preferences and loses its correction value. The unified remedy is a single principle: every entry must be retrievable, verifiable, and reversible.