AI Agent Memory Loop Design: A Practical Guide to Long-Term State

    This article breaks down a practical design pattern for persistent AI agent memory: a closed loop built from three cooperating subsystems—memory, skills, and reflection scheduling. It explains why stateless sessions force users to repeat context, why simply appending all conversation history fails, and how a hard character limit turns storage into a filtering mechanism. You will find the two-file layout, snapshot-based consistency model, write rules, skill entry structure, reflection workflow, and a staged rollout plan with common pitfalls to avoid.

    AI Agent Memory Loop Design: A Practical Guide to Long-Term State

    1. The Problem: Why Most Agents Forget Everything After a Chat

    Most agents today run in a stateless session model: once a turn ends, the context is dropped. This approach is simple to build and cheap to run, but it introduces three clear weaknesses.

    First, repeated communication overhead. Users have to restate the environment, project conventions, and personal preferences every single time.

    Second, no accumulation of experience. The same deployment error can resurface across different sessions, because the agent has no ability to “learn once and remember.”

    Third, no behavioral evolution. The agent’s performance stays fixed at its initial level and never becomes better aligned with a specific context as usage time grows.

    Solving this requires persistent state. But persistence alone is not memory—dumping every historical message into storage only produces an archive that keeps expanding while retrieval efficiency keeps dropping. A memory system that is actually usable has to answer three core questions: what to record, how to compress, and when to reorganize. A relatively mature approach in the industry is to split the agent’s capabilities into three cooperating subsystems that form a closed loop.

    2. Overall Architecture: Three Subsystems and One Loop

    An analogy helps explain the overall design:

    • The memory module is like the small notebook an assistant carries, holding objective facts and preferences.
    • The skill module is like the operations manual the assistant accumulates, holding reusable procedural knowledge.
    • The reflection scheduler is like an alarm clock that rings on a timer, periodically reminding the agent to go back and tidy up the other two.

    The three are not peers; they form a loop. Memory and skills supply the basis for current behavior, while reflection scheduling reviews recent interactions, extracts new facts and new steps, and writes them back into memory and skills. Without reflection scheduling, the first two gradually go stale. Without memory, skills lack contextual constraints. Without skills, memory can only “know” and never “do.”

    3. Memory Subsystem: Trading Hard Capacity for Information Density

    3.1 Two-File Structure with Separated Responsibilities

    A minimal design that has proven effective uses two plain text files to hold all long-term knowledge, with entries separated by a consistent delimiter:

    1. ~/.hermes/memories/
    2. ├── MEMORY.md # Environment facts, project conventions, tool behavior traits
    3. └── USER.md # User preferences, communication style, collaboration habits

    Separating responsibilities pays off because environment information changes infrequently and is reused broadly, while user information is highly personalized and shapes both expression and decision-making. Storing them separately means prompt injection can combine them on demand, and each file can have its own capacity limit and update policy.

    3.2 Character Limits: Turning “Can’t Remember” into a Filtering Mechanism

    The key design is a tight character limit—for example, around 2200 characters for environment memory and around 1375 characters for user memory. This looks like a restriction, but it is the core mechanism:

    • Capacity is finite, so value must be judged before writing, which naturally suppresses noise.
    • When a new entry would exceed the limit, low-value older entries must be evicted, giving automatic “forgetting.”
    • Prompt size stays bounded, avoiding the attention dilution and rising cost of long contexts.

    Compare this with the common append-only memory file: it works well at first, then swells to tens of thousands of lines after a few months, and retrieval can only mean reading the whole file, so hit rate and response speed both decline. A hard capacity constraint converts the engineering problem from “how to retrieve a large file” into “how to compress a small set,” and the latter is significantly easier.

    3.3 Dual-State Implementation: Writable Entries and a Frozen Snapshot

    In implementation, maintain two parallel states: a list of live writable entries, and a snapshot frozen at session start. Example code:

    1. class MemoryStore:
    2. def __init__(self, memory_char_limit=2200, user_char_limit=1375):
    3. self.memory_entries: list[str] = []
    4. self.user_entries: list[str] = []
    5. self.memory_char_limit = memory_char_limit
    6. self.user_char_limit = user_char_limit
    7. # Keep a consistent prompt view within the session
    8. self._system_prompt_snapshot: dict[str, str] = {"memory": "", "user": ""}
    9. def freeze(self):
    10. self._system_prompt_snapshot = {
    11. "memory": "\n§\n".join(self.memory_entries),
    12. "user": "\n§\n".join(self.user_entries),
    13. }

    The frozen snapshot solves a consistency problem: if memory is rewritten mid-session and immediately affects the system prompt, the agent’s behavior becomes self-contradictory. Writes affect only the next session, which makes behavior more predictable.

    3.4 Write Policy: Three Decision Rules

    1. Record only stable facts: one-off information that can be read from code or configuration does not belong in memory.
    2. Overwrite on conflict: when a new fact contradicts an existing entry, replace it rather than keeping both, avoiding self-contradiction.
    3. Compress before adding: when over the limit, first try merging similar entries so the same information is carried in fewer words.

    4. Skill Subsystem: Writing Experience as an Executable Manual

    Memory answers “what is,” skills answer “how to do it.” A skill entry should include trigger conditions, prerequisites, operational steps, and failure fallback—for example, “when deploying a container orchestration cluster, step two must push the image first, otherwise the pull stage will certainly fail.”

    Three practical points:

    • Atomic: one skill describes one thing, so it can be reused and retired individually.
    • Verifiable: steps should be confirmable through command output or a state check.
    • Sourced: record which class of failure the experience came from, so its applicable scope can be judged later.

    Skills and memory need a clear boundary: parameters that change with the environment belong in memory; stable method paths belong in skills.

    5. Reflection Scheduling Subsystem: Making the Loop Actually Turn

    Reflection scheduling periodically triggers an organizing task. A typical flow:

    1. Read recent session summaries and the current memory snapshot.
    2. Extract candidate facts, candidate skills, and conflicts.
    3. Deduplicate, merge, and evict so the limits are not exceeded.
    4. Output a change set and persist it at the session boundary.

    Three engineering cautions: the trigger frequency should not be too high, or organizing cost will exceed the benefit; the organizing process should produce auditable change records; and if several consecutive runs produce no changes, the frequency should automatically decrease.

    6. Rollout Advice and Common Pitfalls

    • Pitfall 1: Chasing full retention. Retaining everything equals having no memory, because retrieval cost eats the benefit.
    • Pitfall 2: Making memory take effect in real time. This causes behavior to drift within a single session; stick with the snapshot mechanism.
    • Pitfall 3: Mixing skills and facts in one entry. Mixed entries are hard both to reuse and to retire.
    • Rollout order: ship the two-file memory with capacity limits first, then add skill entries, then wire in reflection scheduling. If multiple instances need shared state, replace the file layer with a general cloud service such as object storage or a configuration center, keeping the interface unchanged for a smooth migration.

    7. Conclusion

    Whether an agent truly “understands you better the more you use it” depends on having a memory loop that can keep evolving. Finite capacity forces compression, dual state guarantees consistency, skills capture executable experience, and reflection scheduling keeps content fresh—combined, these four let an agent stay high-density, low-noise, and highly predictable over long-term use.