Designing Agent Memory So Systems Get Better With Use
Most agents forget everything after a session. This article describes a compact long-term memory design: two text files with hard size limits, a skill store for reusable procedures, session snapshots for prompt stability, and a review loop that compresses and prunes what is worth keeping.
The problem: session-level amnesia
Most agent systems drop all context when a conversation ends. A user may say that production uses a specific container runtime version; the next day the agent has no idea. Pitfalls from last week get repeated this week. Session-level forgetting keeps the agent a perpetual beginner: it cannot accumulate experience or a lasting model of the user.
The intuitive fix is to store every past turn and inject it all. That hits three walls quickly:
- Limited context windows: long history consumes the token budget and crowds out the current question.
- Worse retrieval: more irrelevant history makes the model more likely to go off-topic or hallucinate.
- Unbounded storage: months of append-only logs become unmaintainable; finding one old sentence means reading everything.
A sustainable approach is not “remember more” but “remember accurately.” That requires active compression and eviction—the three-subsystem loop below.
Architecture: three subsystems in a learning loop
A solid long-term memory design can be abstracted as three cooperating parts:
- Memory: environment facts, project conventions, tool quirks, plus user preferences and communication style.
- Skill: reusable playbooks, such as “step two of deploying a containerized service must push the image first.”
- Review engine: periodically asks the agent to inspect recent sessions and decide whether new facts or skills should be persisted.
The loop: session information lands in working memory; the review engine extracts on a schedule; results write to Memory and Skill; later sessions inject those artifacts to guide behavior. Analogy: Memory is a notebook of facts (“the boss prefers Americano”); Skill is the operations handbook; the review engine is an alarm that forces a recap.
The point is restraint. Capacity is finite; density should stay high.
Memory: two files as the agent’s model of the user
A minimal store
Memory can stay lightweight: two plain-text files, entries separated by a delimiter such as §:
~/.agent/memories/├── MEMORY.md # agent notes: environment facts, project conventions, tool quirks└── USER.md # model of the user: preferences, communication style, work habits
This deliberately skips databases and vector stores. For facts and preferences that must be precise, inspectable, and editable, plain text has three advantages:
- Auditable: open the file anytime and see what the agent “remembers.”
- Editable: users or operators can delete bad memories without a heavy admin stack.
- Easy to inject: drop the text into the system prompt; no extra retrieval path.
Hard caps as a product constraint
Both files get tight character limits—for example about 2200 characters for MEMORY.md and about 1375 for USER.md. That is philosophy, not a platform limit:
Finite capacity forces the agent to keep what matters; the rest is squeezed out.
Contrast append-only memory files that grow into tens of thousands of lines, where finding a weeks-old note means a full read. Tight caps invert that: capacity pressure drives compression. When a new entry would overflow, the system must merge, rewrite, or drop stale items so what remains is dense.
Benefits:
- Stable context cost: memory tokens stay bounded no matter how long the product is used.
- Less rot: outdated facts (old versions, dead paths) get evicted.
- Write as thinking: each write is a summary, not a dump.
Dual state: writable entries vs. session snapshot
A subtle bug: if memory updates mid-session and the system prompt is rewritten live, the model can “suddenly know” something it did not know earlier in the same conversation.
A robust pattern keeps two parallel states:
- Live writable lists: new memories go here for the next session.
- Frozen snapshot at session start: the system prompt for this session always uses that snapshot.
Sketch:
class MemoryStore:def __init__(self, memory_char_limit=2200, user_char_limit=1375):self.memory_entries: list[str] = []self.user_entries: list[str] = []self.memory_char_limit = memory_char_limitself.user_char_limit = user_char_limitself._system_prompt_snapshot: dict[str, str] = {"memory": "", "user": ""}def begin_session(self):"""Freeze a snapshot at session start; do not change it during this session."""self._system_prompt_snapshot = {"memory": self._render(self.memory_entries),"user": self._render(self.user_entries),}def _render(self, entries: list[str]) -> str:return "\n".join(f"§ {e}" for e in entries)
This also enables change detection: at session end, compare current entries to the snapshot to see what was added or changed. The review engine can reflect only on that delta. The snapshot is a natural rollback point if a session wrote bad memory.
Quality rules for entries
Capacity is not enough. Each item should be:
- Atomic: one fact per entry so it can be dropped independently.
- Verifiable: prefer executable evidence (command output, file paths) over vague impressions.
- Time- and context-scoped: version and environment facts should state when they apply.
- Deduplicated: merge related old and new items instead of stacking near-duplicates.
Skill: turn “can do” into a playbook
Memory stores what is; Skill stores how to. Skills capture procedures, order of steps, preconditions, and common pitfalls. Examples:
- When deploying a containerized service, push the image in step two, or later steps use an old version.
- A build system has special cache-directory rules; keep a subdirectory before wiping cache.
- An internal tool needs a specific init sequence before calls.
Skill items are usually longer and more structured (steps, command examples, caveats) but should still be capacity-bounded. Two sources:
- Explicit teaching: the user says “do it this way from now on.”
- Post-hoc extraction: the review engine finds a successful path that generalizes.
Skills let capability rise with use instead of rediscovering from scratch. Combined with user preferences in Memory, the agent can know both the procedure and the person.
Review engine: make persistence automatic
Memory and Skill answer where to store. The review engine answers when and what. On a fixed cadence (or at session end) it runs a self-review:
- Incremental scan: recent interaction plus new memory candidates.
- Value judgment: is this durable, or only ephemeral context?
- Compress and write: rewrite keepers as dense entries into the right file.
- Prune: merge, overwrite, or delete under the size cap.
This is an engineering analogue of a forgetting curve: repeatedly useful facts stay; one-off noise fades. Triggers can be finer: compact when Memory hits the cap, not only on a timer.
Implementation notes and pitfalls
- Split memory and skills: different lifetimes and usage.
- Freeze in-session, update out-of-session: snapshots prevent context drift.
- Cap single-item length: e.g. a couple of sentences, so one item cannot dominate.
- User-visible view and clear: transparency builds trust.
- Do not persist secrets: credentials belong in a secrets manager, not long-term memory.
- Measure health: recall accuracy, stale-entry rate, and similar metrics.
Common failures: treating memory as cheap chat compression (store facts, not transcripts); no eviction so quality decays; refreshing the system prompt mid-session. Caps plus snapshots address these.
Conclusion
Agents that “know you better over time” need a restrained loop, not infinite logs: small text files of high-density facts, size limits that force compression and eviction, session snapshots for consistent context, and a review engine that writes automatically. The design is simple, auditable, and constant-cost—a solid baseline for long-term memory. The shift in mindset: a good memory system does not record everything; it keeps the most important things in a small space.
