Self-Evolving AI Agent Architecture: Skills, Failure Memory, and Preference Alignment

    This article breaks down the architecture pattern behind self-evolving AI agents, which turn completed tasks into reusable experience instead of discarding it at session end. It covers three independently implementable subsystems—skill distillation, failure path memory, and preference alignment—along with trigger thresholds, skill file structure, retrieval instead of full context injection, directory layout, lifecycle governance, the generic cloud capabilities needed to run the loop as a team-level service, and the metrics that show whether the agent is actually improving.

    1. The Starting Problem: Why Most Agents Forget Everything

    Open-source implementations of AI agents are already plentiful, but the vast majority follow the same paradigm: developers pre-wire the tool chain and prompts, the model executes a task once as instructed, emits a result, and the session ends. This stateless execution model carries a structural flaw—experience cannot be reused across sessions.

    The waste shows up in three forms:

    • Repeated explanation cost: every new session has to re-explain the project structure, code conventions, and dependency management preferences.
    • Repeated trial-and-error cost: the same environment traps (dependency conflicts, malformed configuration, insufficient permissions) get hit over and over.
    • Non-reusable workflows: a complex flow that took seven or eight steps to get working still has to be reasoned and orchestrated from scratch next time.

    A self-evolving agent, at its core, makes these three hidden costs explicit, structured, and persistent. Its design philosophy fits in one sentence: completing a complex task is an opportunity to archive a reusable experience asset.

    Worth stressing: this is not a proprietary feature of any single product, but a general architecture pattern the agent engineering field is converging on. Its core consists of three subsystems that can be implemented independently: skill distillation, failure memory, and preference alignment.

    2. Capability One: Distilling Multi-Step Flows into Callable Skills

    2.1 Trigger Conditions and When to Distill

    A reasonable trigger threshold is “more than 5 steps and a successful convergence.” Too few steps and the payoff of distillation is lower than the maintenance cost; a flow that never converged, if distilled, propagates a wrong path as if it were a best practice.

    A typical example is a codebase architecture migration: the user asks to “split this backend project into modules with clear service boundaries,” and the agent works through a dozen-plus steps—directory identification, dependency graph analysis, boundary partitioning, interface extraction, regression verification. When the task ends, the framework abstracts it into a named skill, for example /module-split.

    2.2 The Three-Part Structure of a Skill

    A high-quality skill should not be a pile of conversation logs. At minimum it should contain three parts:

    1. # ~/.hermes/skills/module-split/skill.yaml (illustrative structure)
    2. name: module-split
    3. trigger: ["split modules", "service boundaries", "monolith refactor"]
    4. preconditions:
    5. - repository builds successfully
    6. - a dependency manifest exists
    7. steps:
    8. - build the dependency graph and identify tightly coupled cycles
    9. - partition candidate boundaries by business semantics
    10. - extract interfaces and keep a compatibility layer
    11. - run the build and regression tests
    12. failure_notes:
    13. - do not force package splits while circular dependencies remain
    14. - sink shared utility modules first to avoid duplicate implementations
    15. artifacts: [dependency-graph.json, migration-report.md]

    trigger decides when the skill is retrieved, steps decides how it executes, and failure_notes decides what makes it smarter than reasoning from scratch.

    2.3 Retrieve, Don’t Inject Everything

    Once the skill count grows, you cannot stuff every skill into the context. The common industry practice is to run a semantic retrieval pass to fetch the top-K candidates, then let the model decide whether to load one. This decouples context overhead from library size, which is the precondition for this kind of architecture to stay usable over time.

    3. Capability Two: Failure Paths Are First-Class Citizens

    Most frameworks record only successful trajectories, which wastes information. The genuinely valuable experience usually hides in the contrast between “failed the first time, succeeded the second.”

    Take workload deployment: the first attempt used declarative batch submission and failed because schema validation on the orchestration file did not pass; the agent then switched to a path of “render and validate locally, roll out canary, verify rollback” and succeeded. What should be distilled is not “what the correct command is,” but:

    • Symptom: the schema validation failure occurred at the submission stage, not at runtime;
    • Detection method: run offline rendering and schema validation first;
    • Avoidance strategy: canary one batch before going full scale;
    • Rollback plan: keep the previous version of the definition file.

    This way, the next time the same skill runs, the agent can proactively flag the risk before acting, turning after-the-fact debugging into advance warning. The engineering recommendation is to maintain a separate failure-notes section per skill and allow later runs to append new entries, forming a mistake log that keeps growing.

    4. Capability Three: Immediate Alignment with User Preferences

    An offhand correction from the user—for example, “use the faster package manager for dependency installs, not the default one”—should be extracted into a preference memory rather than discarded with the session. Preference memory and skill memory belong in separate stores, because their lifecycles differ: skills expire as the environment changes, while preferences stay stable over the long term.

    The recommended minimal field set:

    1. {
    2. "scope": "global | project:<repo>",
    3. "subject": "dependency-install",
    4. "preference": "use pnpm instead of npm",
    5. "confidence": 0.9,
    6. "updated_at": "2026-08-26T18:00:00Z"
    7. }

    Adding the scope and confidence dimensions avoids a common incident: a preference that holds in one project being applied globally by mistake.

    5. Directory Layout and Lifecycle Governance

    A flat “one directory per skill” layout for the skill library is recommended, since it makes version control and human review easy:

    1. ~/.hermes/
    2. ├── skills/
    3. │ ├── module-split/skill.yaml
    4. │ ├── pr-review/skill.yaml
    5. │ └── search-pipeline/skill.yaml
    6. ├── memory/preferences.json
    7. └── runs/ # raw trajectories, for replay and re-distillation

    On the governance side, four things must be in place, or self-evolution degrades into self-pollution:

    1. Effectiveness decay: record the last successful run for each skill; demote or archive entries that go long without a hit or fail repeatedly.
    2. Conflict resolution: when multiple skills share a trigger, rank them by a weighted combination of success rate and freshness.
    3. Human review gate: skills for high-risk actions (deletion, release, permission changes) require human confirmation before they can run automatically.
    4. Rollback: keep both skills and memory under version control so a bad distillation can be reverted in one step.

    6. Generic Capabilities Needed to Run This in the Cloud

    To turn this loop into a team-level service rather than a single-machine script, you generally just combine generic cloud capability categories, with no dependency on proprietary interfaces:

    • Object storage: holds skill packages and run trajectories, with versioning and lifecycle policies for free;
    • Message queue: decouples task execution from experience distillation so archiving does not slow the main path;
    • Container platform: gives each run an isolated and reproducible execution environment;
    • Logging plus monitoring and alerting: tracks skill hit rate, failure rate, and average step count as quantitative measures of evolution;
    • Managed database: stores preference memory and the skill index, with support for semantic retrieval.

    Baidu AI Cloud offers corresponding products in each of these generic categories and can serve as the infrastructure foundation for such a self-evolving loop; the actual selection should still be weighed against your own isolation requirements, data compliance boundaries, and cost model.

    7. Evaluation: How to Prove It Actually Got Smarter

    Self-evolution is the easiest thing to overstate, so it has to be constrained by metrics. At minimum, track four:

    • Average interaction turns: for the same kind of task, the second run should take noticeably fewer turns;
    • First-attempt success rate: once failure notes take effect, the first-attempt success rate should rise;
    • Number of human corrections: the direct signal that preference memory is working;
    • Skill library health: the share of skills with high hit rates and low failure rates.

    If these metrics show no improvement over several task cycles, the problem lies in the distillation or retrieval strategy—not in the model being insufficiently smart.

    8. Conclusion

    The dividing line between an agent as a “tool” and an agent as a “colleague” is not how nicely it finishes a single task, but whether experience can be structurally captured, retrieved, reused, and continuously corrected. Skill distillation solves workflow reuse, failure memory solves risk anticipation, and preference alignment solves collaboration friction; only the three together form a complete learning loop. For developers the path is clear and incremental: start with trajectory retention, then add skill distillation, and finally fill in governance and measurement.