Agent Memory and Core Document Design: A Practical Guide

    This article explains how to treat agent memory and constraint documents as two sides of the same context governance mechanism. It covers a four-layer memory architecture, hybrid retrieval with time decay and layer weighting, write and forgetting policies, a core document system built around a global contract, a dynamic skill pyramid, paired preference boundaries, and the dual-loop feedback between memory and skills, along with infrastructure needs, observability, and common pitfalls. Readers will find implementation-oriented code and document samples plus a minimal adoption path.

    1. Background: Why Agents Either Forget or Drift

    In the engineering practice of AI coding tools and automation agents, developers run into two problems that are actually a pair of opposites. One is missing memory: agents repeatedly lose context across multi-turn conversations and cross-project work, forcing users to restate the same constraints. The other is behavioral drift: without explicit boundaries, the model generates content along the highest-probability direction that looks reasonable but violates team conventions.

    Looked at together, these two problems lead to one conclusion: the memory system and the constraint documents are not separate modules but two sides of a single context governance mechanism. Memory handles “what happened before”; documents handle “what must be done next.” Missing either one leaves the system either amnesiac or out of control.

    The original practice is worth abstracting: build multi-layer native memory first, then integrate external memory capabilities, and finally couple them with core documents to form a chain of conversation clustering → execution distillation → deep understanding → skill consolidation. The technical point is not which component was used, but how the chain is layered and how results flow back.

    2. Layered Memory Architecture: From Raw Logs to Reusable Skills

    2.1 Intent Behind the Four Layers

    The first layer is the raw conversation layer, which stores complete dialogues and tool-call traces. It holds everything but carries heavy noise. The second is the clustered summary layer, which merges multi-turn fragments of the same task into topics and compresses redundancy. The third is the semantic understanding layer, where a large language model extracts intent, constraints, and conclusions into structured entries. The fourth is the skill layer, which turns repeatedly validated workflows into callable capabilities.

    The value of this layering is the separation of reads and writes: writes stay low-cost and lossless, while reads retrieve level by level according to abstraction, avoiding stuffing massive raw text into the context window.

    2.2 Retrieval Strategy and Sample Implementation

    Retrieval should not rely on vector similarity alone. A hybrid strategy of keyword recall + vector recall + layer filtering is recommended, with different recency weights per layer:

    1. def recall(query, top_k=5):
    2. candidates = []
    3. candidates += keyword_search(query, layer="raw", limit=20)
    4. candidates += vector_search(query, layer="summary", limit=20)
    5. candidates += vector_search(query, layer="semantic", limit=10)
    6. # The skill layer has the highest priority but must pass a hit-count threshold
    7. candidates += skill_index.search(query, min_hits=3, limit=5)
    8. scored = [(c, score(c, query) * layer_weight(c.layer) * decay(c.ts))
    9. for c in candidates]
    10. return sorted(scored, key=lambda x: -x[1])[:top_k]

    Here decay expresses time decay and layer_weight expresses the preference for abstraction level. Engineering also requires deduplication and conflict resolution: when a higher-level conclusion contradicts a lower-level raw record, the more recent entry confirmed by the user wins, and the conflict is written to a review queue.

    2.3 Writing and Forgetting

    The hard part of a memory system is usually assumed to be remembering; in practice, forgetting is harder. Three eviction conditions are suggested: experimental entries not hit for a long time are automatically downgraded; entries explicitly rejected by the user are invalidated immediately; entries on the same topic beyond a threshold trigger a merge. This is how you remember less yet remember reliably.

    3. Core Document System: Constraints Before Capabilities

    3.1 Main Entry Document: The Global Contract

    The main entry document acts as the hub. It should spell out the execution flow, collaboration rules, skill orchestration, reporting format, memory system structure, and fault-tolerance strategy. It is not a pile of manual pages but an executable contract. A recommended structure:

    1. # Global Contract
    2. ## Execution Flow
    3. 1. Parse request → 2. Recall memory → 3. Select skill → 4. Execute → 5. Report → 6. Write back to memory
    4. ## Skill Orchestration
    5. - Invoke on hit; resolve conflicts via the priority table
    6. ## Reporting Format
    7. - Conclusion / Evidence / Changes / Risks / Next steps
    8. ## Fault Tolerance
    9. - Retry limit on failure, fallback paths, scenarios that require human confirmation

    3.2 Layered Skill Documents: A Dynamic Pyramid

    Skill governance is best viewed as a pyramid, and it must be stressed that this is a dynamic analysis result, not a static label. One workable split: the foundation layer is about 55%, covering high-frequency, stable capabilities such as file operations, terminal commands, and web access; the general layer is about 30%, covering debugging and root-cause analysis, planning, and code review; the specialized layer is about 15%, aimed at domain-specific tasks; the experimental layer is about 5%, used for drafts and validating new capabilities.

    The accompanying promotion mechanism matters more than the layering itself. For example, an experimental entry that is invoked effectively more than three times within 30 days with good feedback can move up to the specialized layer; a specialized entry reused across three different projects and abstractable into a general workflow can move up to the general layer. Demotion needs rules too: zero hits over a long period sends an entry back down, which keeps the skill library from bloating.

    3.3 Decision Boundary Documents: Recording Preferences in Pairs

    Recording user preferences as semantically opposed pairs is a low-cost way to manage boundaries. When the user expresses what they want, the system also derives what they do not want, and the two form a pair. If the preference later reverses, a reverse lookup is enough and no new entry is needed. Sample structure:

    1. - id: B-017
    2. want: changes must include a minimal verifiable case
    3. avoid: describing the approach only, without a runnable example
    4. updated: 2026-08-20
    5. hits: 6

    The engineering benefit is a bounded state space: the number of entries grows with topics rather than with conversation turns, keeping retrieval complexity low.

    4. The Dual Loop: Memory and Skills Reinforcing Each Other

    The first loop is memory flowing back into skills: processing steps that recur in clustered summaries are solidified into skills after human or model confirmation, reducing context usage in later runs. The second loop is skills feeding back into memory: skill invocation results are written back in structured form, producing searchable execution experience instead of scattered natural-language notes.

    Three gates should be made explicit in practice: a candidate skill must have reproducible inputs and outputs; there must be a record of failure cases; and it must have an owning layer and an owner. Missing any one of them, the skill library quickly degrades into a pile of unmaintained scripts.

    5. Engineering Implementation and Observability

    In a real system, these mechanisms rely on general-purpose infrastructure: object storage for raw traces, a message queue to decouple writes from index building, a container platform to host retrieval and inference services, and logging plus monitoring and alerting to observe hit rate, recall latency, and skill promotion frequency.

    A minimal viable path forward: first unify the reporting format and the main entry document, then add layered memory and hybrid retrieval, and finally establish skill promotion and demotion rules along with boundary table maintenance. If a team wants a shorter build cycle, it can evaluate the managed capabilities of general-purpose cloud product categories and focus effort on document standards and evaluation sets rather than reimplementing retrieval infrastructure.

    6. Common Pitfalls

    One is equating memory with long context while ignoring compression and eviction. Another is writing lengthy specifications without arbitration rules, which the model cannot execute. A third is skills that only grow and never shrink, raising selection cost. A fourth is having no evaluation set, making it impossible to tell whether a change is an improvement or a regression. The countermeasures are straightforward: prepare fixed evaluation samples for each type of change and validate with two metrics, hit rate and human ratings.