Building Agents That Get Smarter with Use: A Closed-Loop Design for Memory, Skills, and Self-Improvement
Most AI agents ship with fixed capabilities and repeat the same mistakes forever. This article breaks down a self-improving agent architecture built on three subsystems—memory, a skill library, and a reflection engine—that together form a learning loop. It covers capacity-constrained memory design, automatic skill extraction, reflection trigger strategies, code examples, and practical engineering tips for making your agent stronger the longer it runs.
Background: Why Agents Never “Learn”
Today’s mainstream agent frameworks share a common weakness: their capability boundaries are fixed at build time. Developers pre-write rule files, prompt templates, and tool descriptions, and the agent mechanically loads these static assets on every run. The pitfalls it stumbles into today will be stumbled into again tomorrow, in exactly the same way. User preferences corrected over three sentences are forgotten by the next session.
A common improvement approach in the industry is the “hand-written knowledge base”: distill domain expertise into Markdown documents and feed them to the agent. The problem is obvious—the agent only knows what you write; if you don’t write it, it doesn’t know it. The maintenance burden of the knowledge base falls entirely on humans, and humans can never organize knowledge faster than the agent generates mistakes.
The truly valuable direction is handing “experience consolidation” to the agent itself. In other words, after finishing a task, the agent automatically distills the lessons learned into reusable knowledge, and invokes it directly the next time a similar problem appears. The longer it’s used, the stronger it gets. This isn’t a difference in features—it’s a divergence in design philosophy: one is fed by humans; the other grows on its own.
This article breaks down this “self-improvement loop,” analyzing how its three core subsystems cooperate and how to implement them in engineering practice.
Overview: Three Subsystems, One Loop
Most agents live a lifecycle of “session starts—execute—session ends,” with all state reset at the end. A self-improving agent, by contrast, builds an internal learning loop supported by three subsystems:
- Memory system: persists “fact-level” knowledge—user preferences, environment constraints, project conventions;
- Skill library: persists “operation-level” knowledge—validated execution steps and hard-won pitfall avoidance;
- Reflection engine (Reflection/Nudge): triggered on a schedule or at key checkpoints, reminding the agent to look back at the current session and check whether anything is worth consolidating.
An analogy: the memory system is the assistant’s pocket notebook, recording facts like “the boss prefers an americano”; the skill library is the assistant’s accumulated operations manual—“always check the image version before deploying a service”; the reflection engine is the alarm that goes off periodically, pushing the assistant to review its work.
The three don’t sit side by side—they form a ring: the reflection engine triggers extraction → extracted results are written into memory or the skill library → later sessions retrieve and apply them → new execution results become fresh material for reflection. Missing any one link breaks the loop.
Memory System: The More You Use It, the Better It Knows You
Two Files Contain the Agent’s Entire Understanding of the User
The first design principle of the memory system is restraint. No database, no vector index, no complex setup required to get started—two plain text files are enough:
~/.agent/memories/├── MEMORY.md # The agent's working notes (environment facts, project conventions, tool quirks)└── USER.md # The agent's understanding of the user (preferences, communication style, work habits)
Entries inside the files are separated by delimiters, with each memory being one short line. The benefits of this design: readable, editable, version-controllable. The user can open the file at any time, delete an unwanted entry, or manually add one—ownership of memory always stays with the user.
The Capacity Limit Is the Most Critical Design Decision
Many people think the hard part of a memory system is “how to remember.” It’s actually “how to forget.” The character limits on the two files are deliberately tight: roughly 2,200 characters for working memory and roughly 1,375 for the user profile. This constraint may look stingy, but it’s the essence of the entire memory system.
Consider the consequences of a pure “append-only” mode: memory files only grow, never shrink, and balloon into monster files with tens of thousands of lines after a few months. At retrieval time, you either stuff everything into the context (token explosion) or do semantic retrieval (dragging in a whole dependency stack of vector databases and embedding models, with unstable recall quality). Once information density is diluted, the agent becomes even more likely to overlook critical facts.
A capacity constraint, on the other hand, forces the agent to perform information compression and eviction: when a new fact arrives and space is insufficient, it must judge which old memory has become stale or is less valuable, and push it out. Stale entries are naturally eliminated, and what remains is high-density fact. This is essentially an eviction strategy smarter than LRU—deciding based on “value for future tasks” rather than “access time.”
Implementation: Live State vs. Frozen Snapshots
There’s an easily overlooked engineering detail: memory during a session must be decoupled from the memory already injected into the system prompt. A typical implementation maintains two parallel states:
class MemoryStore:def __init__(self, memory_char_limit=2200, user_char_limit=1375):self.memory_entries: list[str] = [] # Real-time writable entry listself.user_entries: list[str] = []self.memory_char_limit = memory_char_limitself.user_char_limit = user_char_limitself._system_prompt_snapshot = { # Snapshot frozen at session start"memory": "","user": "",}
At session start, freeze the current memory content into a snapshot and inject it into the system prompt; during the session, the agent can keep writing new entries and modifying existing ones, but these changes don’t affect the current session’s prompt. There are two reasons:
- Consistency: prevents the prompt from drifting mid-session, which would make agent behavior unpredictable;
- Safety: prevents erroneous information written during the session from immediately feeding back into the current reasoning process, forming a self-reinforcing error loop. New memory takes effect from the next session onward, giving bad information an “isolation period.”
The core logic on write is capacity conservation: before appending a new entry, check the total character count; if over the limit, trigger a compression pass—merge duplicates, delete stale entries, rewrite into more compact phrasing. This compression can be done by the model itself, or by a coarse rule-based pre-filter followed by model refinement.
Skill Library: From “Hand-Written Rules” to “Autonomous Growth”
The Essential Difference Between Skills and Memory
Memory records “what is” (facts); skills record “how to do” (procedural knowledge). Their storage formats differ too: memory is a list of short sentences, while skills are structured documents, typically containing trigger conditions, execution steps, caveats, and failure cases.
The traditional approach is for developers to hand-write skill documents. This has a very low coverage ceiling: in real work, agents run into long-tail problems that humans simply cannot write fast enough to cover. The breakthrough of the self-improving architecture is this—skills are automatically extracted by the agent after solving real problems.
How the Extraction Pipeline Runs
A practical extraction pipeline has four steps:
- Trigger: the reflection engine detects a “non-trivial problem-solving process” in the current session—for example, a tool call that failed and then succeeded on retry, a task that took significantly longer than comparable ones, or multiple user corrections;
- Extraction: the agent replays the execution trace and identifies generalizable patterns: which step was the key fork, how a pitfall was circumvented, and which steps are environment characteristics rather than task-specific;
- Generalization: abstract the specific case into a general skill—strip one-off details (file names, timestamps), preserve transferable decision logic, and explicitly state the trigger condition (“when encountering a task of type X”);
- Deduplication and merging: compare against existing entries in the skill library; if a similar skill exists, merge and supplement rather than create a new one, preventing the library itself from bloating.
Written skill entries should carry a “confidence” dimension: a newly extracted skill is marked as unverified; successful reuse in later sessions raises its confidence; failure after reuse downgrades it and triggers a revision. This gives the skill library a self-correction capability, rather than a one-way accumulation of bad experience.
Why “Autonomous Growth” Is Architecturally Superior
The difference between hand-written skills and automatic extraction parallels “static compilation” versus “just-in-time compilation.” The knowledge update cycle in the hand-written mode is measured in days, dependent on developers noticing issues and their willingness to organize them; the automatic extraction cycle is measured in sessions, and what gets extracted is exactly the distribution of scenarios the agent actually encounters—high-frequency pitfalls get consolidated at high frequency, giving coverage far beyond what humans can achieve. More importantly, it turns the marginal cost of knowledge maintenance from “linearly growing human labor” into “near-zero compute.”
Reflection Engine: The Alarm That Keeps the Loop Turning
The first two subsystems are passive storage; what makes the system “alive” is the reflection engine. It solves this problem: while busy executing tasks, an agent won’t spontaneously stop and summarize. Without a triggering mechanism, “distilling experience” simply never happens.
There are three common trigger strategies, usually combined in practice:
- Timed triggers: insert a reflection check after every N rounds of tool calls in a session, evaluating whether anything is worth consolidating;
- Event triggers: capture specific signals—a tool error followed by a successful retry, explicit user correction, task completion—as sentinel events for reflection;
- Boundary triggers: force a lightweight review at session end, scanning the full trace for missed learning points.
The output of reflection must be constrained. Unconstrained reflection produces large volumes of low-value records that pollute memory and the skill library. Reflection prompts should therefore specify explicit “admission criteria”: only patterns with reusable value for similar future tasks may be written, and each reflection should have an upper limit on entries written. Quality over quantity is the baseline of the loop—a skill library filled with junk experience is worse than no skill library at all.
Engineering Practice Recommendations
If you plan to implement this architecture in your own agent, these lessons are worth considering:
- Build memory first, then skills. Fact-level memory is simple to implement with immediate payoff; skill extraction depends on longer execution traces and stable reflection capability, so introduce it after the memory loop is running.
- Keep all persisted knowledge as plain text. Text is readable, diffable, and manually correctable, which keeps the user in ultimate control. Introduce vector databases and complex indexes only after the text-based approach genuinely hits retrieval bottlenecks.
- Annotate every piece of consolidated knowledge with source and timestamp. Source (which session produced it) makes tracing possible; time gives expiry and eviction a basis.
- Separate snapshots from live state (as in the code above). This is the key detail for session behavioral consistency, and the one beginners most easily miss.
- Make the loop observable. Log memory writes, skill extractions, and eviction decisions, and periodically audit the quality of what has been consolidated by hand. The biggest risk of a self-improving system isn’t failing to learn—it’s learning the wrong things with no one noticing.
Closing Thought: Bringing the Loop to People Who Don’t Code
This architecture currently lives mostly in open-source agent frameworks, and the barrier to entry remains high—you need to understand file layouts, reflection mechanisms, and capacity strategies. The natural next step in evolution is packaging “self-improvement” as a capability invisible to ordinary users: users don’t need to know memory files exist; they simply feel, in everyday conversations, that “it understands my project conventions better and better” and “it’s getting more fluent with this kind of task.”
For cloud agent platforms, this means turning memory persistence, skill consolidation, and reflection scheduling into platform-level infrastructure, paired with object storage as the knowledge persistence layer, logging services for auditing learning traces, and monitoring and alerting systems watching quality metrics. Only when “getting stronger with use” shifts from a framework-level technical feature into an out-of-the-box default experience for all users will agents truly cross the threshold from “tool” to “assistant.”
The design divide is clear: for a system fed by humans, the capability ceiling equals human investment; for a system that grows on its own, the ceiling equals usage time. Which path you choose determines what your agent looks like three months from now.
