Self-Evolving Agent Architecture: Memory, Skills, and Trigger Loops

    Most production agents behave like stateless functions: context is complete within a session and discarded afterward. This article describes a self-evolving architecture built from three cooperating subsystems—memory, skills, and triggers—that form an execution-reflection-distillation-retrieval loop. It covers bounded memory files with capacity budgets, snapshot isolation, eviction and merging, executable skill entries with confidence and expiration, and trigger strategies with admission checks. It also discusses two-phase writes, consistency, risks such as memory pollution and privacy, observability and evaluation, and cloud deployment considerations.

    1. The Starting Problem: Why Most Agents Forget After Use

    Common agent implementations in the industry are essentially stateless functions: context is complete within a single session and is entirely discarded when the session ends. This creates two typical symptoms.

    The first is repeated cold-start cost. The same environment facts—dependency versions, build commands, code style conventions—are probed and retried in every session, and users repeatedly answer the same questions.

    The second is one-way context growth. If all history is appended to a single memory file, a few months later it becomes a massive document with tens of thousands of lines. Retrieval then depends on reading the whole document, the noise ratio rises over time, and useful information is diluted.

    Therefore, the key to self-evolution is not “storing more” but storing accurately, compressing effectively, and retrieving reliably. The architecture below is organized around these three points.

    2. Overall Structure: Three Subsystems, One Closed Loop

    A self-evolving agent usually relies on three cooperating subsystems:

    • Memory subsystem: stores “facts” and answers “what the world is like.”
    • Skill subsystem: stores “methods” and answers “how this type of problem should be handled.”
    • Trigger subsystem (Nudge/Trigger): initiates reflection on a schedule or through events, answering “when should a review happen.”

    Together they form a closed loop: execution → reflection → distillation → persistence → retrieval and reuse next time. If any link is missing, the system degrades into a “manual feeding” model, where capability growth depends entirely on rules written by humans.

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

    3.1 Two Files and Role Separation

    One restrained design is to maintain only two plain-text files:

    1. ~/.agent/memories/
    2. ├── MEMORY.md # Environment and project facts: directory conventions, tool quirks, build constraints
    3. └── USER.md # User profile: preferences, communication style, collaboration habits

    Entries are separated by a uniform delimiter such as §, which makes programmatic insertion and deletion possible without introducing a database.

    3.2 Hard Capacity Limits

    The key design is a hard character budget constraint, for example about 2,200 characters for environment memory and about 1,375 characters for the user profile. This is not laziness but a strategy: limited capacity → writes must be selective → low-value entries are naturally pushed out → what remains is high-density facts. It turns “memory governance” from a manual task into an inherent system constraint.

    3.3 Separation of Live Entries and Session Snapshots

    To prevent content written during the same session from polluting the consistency of the system prompt, two parallel states can be maintained: a live writable entry list and a snapshot frozen at session start.

    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. # Freeze at session start to keep the prompt stable within a single turn
    8. self._snapshot: dict[str, str] = {"memory": "", "user": ""}
    9. def render(self) -> str:
    10. return f"[MEMORY]\n{self._snapshot['memory']}\n[USER]\n{self._snapshot['user']}"
    11. def add(self, text: str, kind: str = "memory") -> None:
    12. entries = self.memory_entries if kind == "memory" else self.user_entries
    13. limit = self.memory_char_limit if kind == "memory" else self.user_char_limit
    14. entries.append(text.strip())
    15. self._evict(entries, limit)
    16. def _evict(self, entries: list[str], limit: int) -> None:
    17. # Keep new entries preferentially; when over budget, evict by time decay + hit frequency
    18. while sum(len(e) for e in entries) > limit and len(entries) > 1:
    19. entries.pop(0)

    3.4 Eviction and Merging Strategies

    In engineering practice, a three-dimensional score is recommended: recency, citation frequency, and factual stability (environment constants > temporary state). At the same time, semantic merging should be performed: two records describing the same fact should be compressed into one rather than kept side by side. Merging is the most effective way to control expansion.

    4. Skill Subsystem: Turning Hard-Won Experience into Callable Assets

    The difference between skills and memory is executability: memory consists of declarative statements, while skills are procedural knowledge with preconditions and steps.

    A usable skill entry is recommended to contain five parts:

    1. name: Image-first deployment verification
    2. trigger: Deployment orchestration task with changed build artifacts
    3. preconditions: Image registry reachable, credentials injected
    4. steps:
    5. 1. Build and push the image, record the digest
    6. 2. Verify that the remote digest matches the local one
    7. 3. Run the orchestration update to avoid pulling stale layers
    8. failure_signals: [pull failure, digest mismatch, rollback loop]
    9. confidence: 0.82 # Updated dynamically from successful reuse and failure counts

    Three key points:

    1. Trigger conditions must be explicit. A skill without a trigger description is equivalent to a document that will not be retrieved.
    2. Confidence evolves with reuse. Successful reuse adds points and failures subtract points. Below a threshold, the skill is automatically down-weighted or archived to prevent incorrect experience from becoming fixed.
    3. Skills must be invalidatable. After dependency versions change, old skills should be marked as expired rather than silently reused.

    5. Trigger Subsystem: The Scheduling Problem of Reflection

    Reflection cannot be performed every turn because the cost is too high, nor should it never be triggered because then there is no evolution. There are three feasible strategies:

    • Scheduled triggers: perform a review when the session is idle or during a fixed daily window.
    • Event triggers: trigger immediately when a task fails, a user corrects the agent, or repeated trial and error exceeds N times.
    • Threshold triggers: trigger when the cumulative number of unpersisted observation entries in a new session exceeds a threshold.

    The output of reflection must pass an admission check: whether it can be generalized (removing accidental factors specific to this instance), whether it conflicts with existing entries, and whether it is worth occupying the limited budget. Observations that fail the check are discarded directly. This is the core gate that prevents memory from being overwhelmed by noise.

    6. Closed-Loop Sequencing and Consistency

    It is recommended to make writes two-phase: the reflection phase produces candidate entries → validation and merging → atomic disk write (temporary file + rename) → effective in the next session snapshot. This ensures stable prompts within a single session, visible updates across sessions, and rollback if a write fails.

    In concurrent scenarios, a file lock or single-writer queue is needed to avoid entry loss caused by multiple sessions rewriting at the same time.

    7. Risks and Boundaries

    • Memory pollution: once an incorrect conclusion is persisted, it will be reused repeatedly. Countermeasures include confidence scores, source labeling, and periodic audits.
    • Privacy and compliance: user profiles are sensitive data and should support per-entry deletion, export, and anonymization. Encryption is recommended for both storage and transmission.
    • Observability: record “which memory or skill was hit and changed behavior”; otherwise, improvements cannot be attributed.
    • Evaluation loop: use a fixed task set for regression testing and measure first-attempt success rate, average trial-and-error rounds, token consumption, and the number of repeated manual answers to verify whether evolution is actually happening.

    8. Cloud Deployment Recommendations

    For enterprise deployment, memory and skill files can be placed in shared storage or object storage with versioning; log services and monitoring alerts can track hit rates and eviction rates; container platforms can host reflection tasks, with message queues smoothing peaks; sensitive fields can be managed through key management capabilities. Overall, keep the three layers—storage, scheduling, and observability—decoupled so implementations can be replaced easily.

    9. Conclusion

    The dividing line for self-evolution is not the feature list but the design philosophy: whether capabilities are written by humans or accumulated by the system itself. Bounded memory provides compression pressure, the skill library turns experience into executable assets, and the trigger engine maintains the reflection cadence. Only when these three form a closed loop can an agent become more capable the longer it is used.