Self-Evolving AI Agents: Closed Loops, Skill Accumulation, and Controllable Execution

    While large language models possess strong reasoning capabilities, they often struggle with real-world execution, losing context after prompts or failing silently during long tasks. This article explores how to build self-evolving AI agents through a four-step closed loop, white-box execution, skill accumulation, and layered memory. It covers practical implementation strategies, including reference architecture, safe rollout sequences, and metrics to evaluate genuine agent evolution, enabling systems to learn from past interactions while maintaining strict controllability.

    Although models now possess strong reasoning capabilities, they often idle when deployed: losing context when a prompt ends, failing to explain tool call failures, going silent during long tasks, and starting from scratch in the next session. Building an agent like an “automatic transmission” is not about adding another chat interface; it is about allowing the model to grow reusable roots in real task environments—turning a single success or failure into skills, constraints, and preferences that can be invoked next time.

    1. From Single-Shot Generation to Autonomous Loops

    Common intelligent coding tools focus on single-turn completion and repository-level rewriting. A personalized agent needs to fill a different gap: incomplete goals, changing environments, failing steps, and long-term alignment with user preferences. This can be described as a four-step closed loop, rather than some mysterious “self-awareness”:

    1. Execute: Break goals down into observable actions, invoking retrieval, code execution, file I/O, or business APIs.
    2. Observe: Collect structured results, rather than just relying on natural language claims like “I think I’m done.” Success, failure, timeout, and partial completion must all have explicit states.
    3. Learn: Extract reusable fragments from the trajectory—checklists, command templates, troubleshooting orders, and practices the user has vetoed.
    4. Iterate: Write the extracted fragments back to the skill library or memory, and prioritize retrieving them for the next similar task instead of blindly trying again.

    Without observation, learning is a hallucination; without writing back, iteration stops at the current conversation. The minimum acceptance criteria for the closed loop is that the second time a similar task is executed, the steps are shorter, there are fewer failures, and the system can point out “what was changed last time.”

    2. White-Box Execution and Progress Heartbeats

    What hurts trust the most in long tasks is not slowness, but silence. Users cannot distinguish between “still running” and “deadlocked.” White-box execution does not mean dumping the entire chain of thought; it means exposing an auditable state machine.

    It is recommended to at least log these fields: task ID, current sub-goal, last tool name and duration, retry count, blocking reason, next plan, and whether human confirmation is needed. For the user side, sync with short sentences: “Still executing step 3, waiting for test results, 90 seconds elapsed, timeout threshold is 180 seconds.” Internal logs can be more detailed, but the default display should be scannable.

    Heartbeats need an upper limit. Spamming updates on every step will drown out critical failures. As a rule of thumb, proactively report only on state changes, when exceeding a fixed silence threshold, and before entering high-risk actions. Deadlock detection should be based on “no new observations,” not “the model is still generating text.” If a tool returns no output, it should degrade to an explicit failure, offering options to retry or skip, rather than waiting indefinitely.

    An illustrative state does not need to be tied to any specific product:

    1. state: running
    2. step: run_checks
    3. attempt: 2/3
    4. last_observation: tests_failed (3)
    5. next: summarize_failures_then_patch
    6. heartbeat_sec: 45
    7. needs_user: false

    The other side of transparency is control. Actions like deletion, sending external messages, modifying production configurations, or spending quotas should pass through confirmation gates. If a white box only displays but cannot be stopped, it remains uncontrollable.

    3. Skill Accumulation: From Public Recipes to Personal Flair

    Public skill libraries solve the cold start: actions like format conversion, test execution, and log retrieval can be shared. However, long-term value comes from the current user’s trajectory. For the same phrase “make the release secure,” some mean doing a gradual rollout first, while others mean writing documentation first. Relying solely on public recipes will keep the agent stuck at the average user level.

    Skills should be small, testable programmatic instructions, not large blocks of non-executable prose. A skill should at least include: trigger conditions, inputs/outputs, pre-checks, steps, fallback on failure, prohibitions, and the last validated scenario. The storage format can be customized, but it must be stable, versionable, and searchable. After completing a complex task, do not automatically dump “a large pack of skills” into the library; instead, generate candidates, deduplicate them, and only elevate them to default strategies after a replay or human approval.

    Prioritize these signals when extracting skills: the same type of error repeatedly corrected by the user, explicit statements like “always do it this way,” proven effective troubleshooting orders after failures, and project conventions appearing repeatedly across multiple files. Do not turn a single accidental success into an ironclad rule. Skills must include provenance: which task, which observation, and who confirmed it. Skills lacking provenance should be downgraded by default.

    The relationship with public skills should be overriding, not opposing: public skills provide the skeleton, while personal skills provide parameters and restricted zones. During retrieval, match the task type first, then overlay user preferences. In case of conflict, the updated and confirmed personal constraints take precedence.

    4. Memory: Preference Modeling, Not Chat Logs

    Cross-session memory is easily implemented by “stuffing all historical conversations into the context.” This is both expensive and noisy, and it risks treating outdated decisions as current facts. A more robust approach is layered memory:

    • Working memory: Goals, files, and incomplete steps for the current task. Archived when the task ends.
    • Project memory: Repository conventions, build methods, directory responsibilities, known pitfalls. Updated as the project evolves.
    • User preferences: Communication granularity, risk appetite, naming habits, whether auto-commit is allowed. Changes slowly; explicitly ask when conflicts arise.
    • Skill memory: Executable fragments and their validation records.

    Each memory entry should carry a timestamp, scope, and confidence level. If a user says “skip writing tests this time,” it should be recorded with a scope of “this time only,” not as a global preference. Periodically compress memory: condense multiple rounds of conversation into a few verifiable statements. The original text can go to object storage for auditing, while the hot path retains only summaries and indexes. Data involving keys, personal privacy, or undisclosed information should default to being excluded from searchable memory, or be separately encrypted with restricted tool access.

    5. Boundaries of Self-Evaluation

    If “built-in reinforcement learning” is understood as arbitrarily changing strategies online, the risk is very high: if the reward is merely “the user didn’t complain,” the model will learn to do less and report fewer errors. A more engineering-feasible approach is constrained policy optimization:

    • Rewards come from externally observable signals: whether tests pass, whether the user adopts the patch, the number of reworks, and whether manual vetoes are triggered.
    • Update granularity is skill sorting and checklists, not arbitrarily modifying base model weights.
    • New policies enter shadow mode first: providing suggestions in parallel without directly executing high-risk actions.
    • Rollback is retained: skill versions can be compared, and bad strategies can be downgraded to the last stable version with one click.

    Self-evaluation must answer three questions: Was the goal achieved this time? Which step lacked evidence? What check should be added or removed next time? Claims of “I’ve gotten better” without supporting evidence should not be written into default behavior.

    6. Reference Architecture

    A practical personal agent can be logically broken down into these general components, without being locked into a specific cloud vendor’s proprietary interfaces:

    • Orchestrator: Maintains the state machine, timeouts, retries, and human gates.
    • Model Runtime: Planning and summarization; the context only contains currently relevant memory.
    • Tool Layer: File system, retrieval, code execution, and message notifications. All return structured observations.
    • Skill Library: Versioned documents or structured records, supporting retrieval and gradual rollouts.
    • Memory Store: Layered storage; hot data goes to retrieval, cold trajectories go to object storage.
    • Logging and Monitoring: Trajectories, tool durations, failure codes, and heartbeat interruptions, integrated into logging services and monitoring alerts.
    • Policy Gate: Permissions, quotas, data residency, and confirmation rules.

    For deployment, the orchestrator and tools are well-suited for container platforms to isolate execution environments; trajectories and skill snapshots fit well in object storage. Alerts should focus on lost heartbeats, exhausted retries, and abnormal external connections, rather than the model “feeling off.” If using a cloud environment such as Baidu AI Cloud, you should still stick to these general capabilities: separate compute, storage, logging, and alerting to avoid hardcoding secrets into skill text.

    Permissions should follow the principle of least privilege. If it only needs to read logs, do not grant production write access; if it can modify branches, do not allow direct publishing. Each tool declares its side-effect level, and the orchestrator decides whether to ask the user based on this.

    7. From Small Team Exploration to Platform Consolidation

    Individual developers and small teams often get the closed loop running first: transparent execution, skill write-back, and preference memory. Once this usage becomes mainstream, official programming apps will absorb high-frequency capabilities into the main product—progress visualization, project-level rule files, reusable commands, and session summaries. This is not a mockery of failure, but the norm for infrastructure: exploration validates the demand, and platforms productize it with more stable permissions, auditing, and distribution.

    Therefore, self-built systems do not need to pursue “forever staying ahead of all official capabilities.” What is more worthwhile to maintain are the areas platforms cannot yet handle granularly: your project’s restricted zones, your release tastes, your troubleshooting orders, and your cross-tool workflows. If an official branch provides a personalized agent, treat it as a gear on the transmission, rather than discarding your existing skill library. During migration, what you export should be neutral skill descriptions and memory summaries, not the proprietary format of a specific chat product.

    The concentration of resources toward large teams does not mean individual practices have no place. The validation data for skills is in your tasks, which the platform does not have. Leaving trajectories as portable, auditable records is more resilient to change than betting on a specific product name.

    8. Rollout Sequence and Common Failures

    It is recommended to enable features in order of low to high risk, rather than going fully autonomous on day one to write to databases, release code, or send messages.

    1. White-box first: Status, heartbeats, and stoppability. Users will only hand over long tasks if they can see what is happening.
    2. Structured observation next: Tools return unified success/failure/partial completion statuses. Relying solely on the model’s verbal summary is prohibited.
    3. Skills: Manually confirm and store in the library first. After running stably for two weeks, loosen the restrictions on automatic extraction.
    4. Memory: Start with project conventions and explicit preferences. Do not automatically summarize all chat logs.
    5. Policy sorting and shadow evaluation: Do this last, and always keep rollback capabilities.

    Common failures include: treating failure trajectories as successful skills; heartbeat spam causing users to ignore real alerts; memory lacking scope, turning a one-time exception into a permanent rule; tools lacking timeouts, causing the state machine to get stuck in “running” forever; and rewards based only on “longer replies” or “user silence.” Each of these should have corresponding alerts or spot checks, rather than relying on the model’s self-report that “I have optimized.”

    9. How to Judge if It Is Actually Evolving

    Do not use “feels smarter” as a metric. You can run a regression test with a set of stable tasks: the same repository, the same goal, and the same permissions. Record the number of steps, human interventions, first-time pass rate, whether error types are repeated, and whether the agent takes fewer detours after hitting a skill. If metrics do not improve, do not increase automation permissions.

    For the user side, evolution should be explainable: “I ran static checks first this time because you reworked at this step twice last week.” The explanation should map to a specific memory or skill version so the user can correct it. Unexplainable personalization is just drift.

    An engine can be very powerful, but the gears, clutch, and road feedback determine whether the car can complete the journey on a real road. The professional work of a self-evolving agent is to turn execution into evidence, turn evidence into versionable skills and preferences, and use heartbeats, gates, and rollbacks to keep speed within a controllable range. Only a system built this way can be said to understand the user better the more it is used, rather than becoming harder to audit the more it is used.