Architecture of a Self-Evolving Agent Loop: Memory, Skills, and Nudges

    This article breaks down the architecture of a self-evolving agent loop that lets AI agents accumulate reusable knowledge instead of forgetting everything when a session ends. It explains three cooperating subsystems—Memory for environment facts and user profiles under strict character limits, Skills for reusable procedures generated from valuable execution traces, and a Nudge Engine that triggers retrospectives at the right moments—along with the snapshot mechanism that keeps prompts stable within a session, plus engineering practices and common pitfalls for putting the loop into production.

    Architecture of a Self-Evolving Agent Loop

    1. The Problem: Agents Forget Everything When the Session Ends

    Most mainstream agent frameworks today follow a stateless session model: when a conversation ends, the context is discarded, and the next run starts the agent from scratch when it comes to understanding the environment and the user. This model is simple to implement and easy to scale horizontally, but it carries a structural flaw—capability does not accumulate over time. Users have to repeat the same project conventions, the same tool quirks, and the same style preferences over and over, which artificially inflates interaction cost.

    Two workarounds are common in the industry. One is to stuff the entire conversation history back into the context; the other is to write experience into static documentation files that humans maintain by hand. The first is bounded by the context window and inference cost, and the noise ratio climbs quickly with each additional turn. The second shifts the entire maintenance burden onto people: whatever gets written down is what the agent knows, and whatever is left out is simply lost. Neither actually solves the accumulation problem.

    What is really needed is a loop: the agent automatically produces reusable knowledge while completing tasks, automatically retrieves and applies it in later tasks, and is proactively prompted to run retrospectives rather than waiting for the user to remember to add notes. This article dissects that loop from a general architecture perspective. It consists of three subsystems: Memory, Skills, and a Nudge Engine.

    2. Overall Architecture: Three Subsystems, One Loop

    The three subsystems have clear boundaries of responsibility, which keeps them from contaminating one another:

    • Memory subsystem: stores “facts”—a set of short statements about the environment and the user. It is high-density, overwritable, and capacity-constrained.
    • Skill subsystem: stores “methods”—reusable operational steps and lessons learned from failures. It grows over time, is versionable, and is loaded on demand.
    • Nudge subsystem: stores “timing”—it triggers retrospectives and cleanups at the right moments, converting incidental experience into long-term assets.

    The loop runs in this order: task execution → nudge triggers a retrospective → distillation into a skill or compression into memory → on-demand recall in the next task → higher execution efficiency → new experience. The critical point is that the distillation step is automatic, not hand-written by a person.

    3. Memory Subsystem: Using Capacity Limits to Force Information Compression

    3.1 Two-File Structure with Separated Responsibilities

    A restrained design splits memory into two plain-text files: one records environment facts (project structure, dependency versions, abnormal tool behavior, deployment conventions), and the other records the user profile (communication style, output format preferences, working rhythm). The benefit of keeping them separate is that recall strategies can differ: environment facts apply to all sessions, while the user profile mainly shapes expression and collaboration style.

    Entries are split by explicit delimiters so they can be added, removed, updated, and queried programmatically. An example structure:

    1. ~/.agent/memories/
    2. ├── MEMORY.md # Environment facts, project conventions, tool quirks
    3. └── USER.md # User preferences, communication style, working habits

    3.2 Hard Caps: Making “Forgetting” Part of the Design

    Setting strict character limits on both files (for example, on the order of a few thousand characters) is the core of this design, not a compromise. When capacity is limited, writing a new entry requires an explicit value judgment, low-value information is naturally pushed out, and the files stay dense over the long run. By contrast, a pure append-only mode swells into a long document that is hard to search after a few months; finding one old conclusion means reading the whole thing, which wastes context and lowers the hit rate.

    On the engineering side, an eviction policy is required: when new entries push a file over its limit, score entries by importance, recency, and hit frequency, then evict the low scorers. For contradictory entries, keep the newest one that has been verified rather than letting both coexist.

    3.3 Separating Snapshots from Live State to Keep Sessions Consistent

    If a mid-session memory update takes effect immediately, the system prompt becomes inconsistent within the same session and model behavior drifts. A common approach maintains two parallel sets of state: a live, writable entry list 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. # Frozen at session start to keep the prompt stable within a session
    8. self._snapshot: dict[str, str] = {"memory": "", "user": ""}
    9. def freeze(self) -> None:
    10. self._snapshot = {
    11. "memory": self.render(self.memory_entries),
    12. "user": self.render(self.user_entries),
    13. }
    14. def render(self, entries: list[str]) -> str:
    15. return "\n§\n".join(entries)

    Reads inside a session hit the snapshot; the snapshot is re-frozen when the session ends or when the next session starts. Writes and reads are therefore decoupled.

    4. Skill Subsystem: Turning Lessons Learned into Reusable Assets

    A skill is an “executable method.” It typically includes applicable conditions, pre-checks, steps, failure fallbacks, and verification. The difference from memory is that memory answers “what is the situation here,” while a skill answers “what should be done for this kind of situation.”

    Key implementation points:

    1. Trigger-based generation: after a task completes, if the process contained valuable traces such as retries, detours, or fault localization, distill them into a candidate skill instead of indiscriminately recording the entire process.
    2. Structured template: unified fields (applicable scenario, prerequisites, steps, common mistakes, verification commands) ensure skills can be reliably parsed and retrieved later.
    3. Deduplication and merging: compare a new skill against existing ones by semantic similarity; if similarity is high, merge the incremental information so the library is not flooded with near-duplicates.
    4. On-demand loading: skill bodies do not stay in the resident context; only a summary or the full text is injected at recall time, keeping context cost under control.
    5. Rollback support: skills carry a version and the ID of the source task, so if a skill drives up the failure rate, it can be located quickly and taken offline.

    5. Nudge Subsystem: Making Retrospectives Happen at the Right Time

    The biggest risk of automatic accumulation is recording what should not be recorded while missing what should be. The nudge mechanism addresses timing. Common strategies: trigger when a task ends with obvious retries; trigger when the same class of problem appears a second time; run a lightweight cleanup once token consumption or turn count crosses a threshold; perform batch compression and deduplication during idle periods.

    Nudges should state the retrospective instruction explicitly, for example “summarize the reusable troubleshooting steps from this run,” “decide whether there is a long-term fact that should be written to memory,” or “check whether any entry has gone stale.” A budget cap prevents the retrospective itself from consuming too many resources, and a manual confirm-or-reject entry point prevents incorrect experience from being locked in.

    6. Engineering Practices and Common Pitfalls

    • Prompt stability: keep only the snapshot in the resident context and make writes asynchronous, so behavior does not jitter within a session.
    • Retrieval before full injection: fetch the Top-K by similarity first, then decide whether to load the full text.
    • Observability: log the source of each recall, along with hit and eviction reasons, to evaluate memory quality.
    • Privacy and isolation: store the user profile and project facts in separate domains, and support clearing and exporting per project.
    • Failure protection: a failed memory write must not block the main task; degrade to “skip recording this time.”
    • Cold start: memory can start empty and build baseline facts quickly through a few guiding questions.

    To deliver these capabilities to users who do not write code, you can run the runtime on a container platform, store memory and skill files in object storage, track recall hit rate and failure rate with logging and monitoring/alerting services, and enforce permissions and quotas through a unified gateway. This turns “self-improvement” from a source-code capability into an operable service.

    7. Conclusion

    The breakthrough in an agent’s capability ceiling does not come from being smarter in a single inference pass, but from having a sustainable accumulation mechanism. Capacity constraints drive memory compression, templated skills settle methods into assets, and the nudge engine captures the right moment for retrospectives. Together these three form a loop—and that loop is what lets an agent truly understand you better the longer you use it.