Self-Evolving Agent Architecture and Runtime Skill Learning
Most agent stacks optimize for task execution, not compounding improvement. This article describes a reproducible design: a single kernel with thin adapters, a synchronous interruptible loop, runtime skill generation and pruning, layered persistent memory, offline evolutionary validation, heterogeneous runtimes, and explicit safety gates.
1. Why “learning” agents are still rare
Most agent frameworks answer “can it do the job,” not “can it get better.” A typical stack looks like this:
- Entry layer: CLI, message gateways, batch runners, and editor plugins each keep their own session and tool logic.
- Kernel: prompt assembly, model calls, tool execution, and context management.
- Persistence: sessions forget on exit; successful experience is not reused.
The real gap is the third layer. For “learning” to mean anything, three capabilities must live in the same framework: runtime skill generation and reuse, cross-session multi-layer memory, and offline policy evolution and validation. Missing any one of them breaks the loop; with all three, compounding returns become possible. The following is a general architecture and engineering practice you can reproduce.
2. First principle: one kernel, many entry points
Self-evolution belongs in the kernel, not in each entry. Otherwise every new channel reimplements memory I/O and skill retrieval, and learning fragments.
Use a single core class plus thin adapters:
# Pseudocode: a single core agent classclass AIAgent:def __init__(self, config):self.memory = MemoryStore(config.memory) # multi-layer memoryself.skills = SkillRegistry(config.skills) # skill libraryself.executor = Executor(config.runtime) # heterogeneous backendsself.optimizer = Optimizer(config.evolution) # offline evolution enginedef run(self, task, interrupt_event=None):while not task.done():prompt = self.build_prompt(task) # 1. build system promptself.maybe_compress(task) # 2. compress context as neededresp = self.call_model(prompt, interrupt_event) # 3. interruptible callif resp.tool_calls:task.observe(self.executor.run_all(resp.tool_calls)) # 4. run toolselse:task.commit(resp) # 5. converge and persist
CLI, messaging, batch runners, and editor integrations are only entry points: they handle auth, session mapping, and rendering. They do not own learning. The payoff is cross-channel consistency—one codebase, shared skills and memory.
3. Main loop: synchronous, interruptible, compressible
The loop alternates reasoning and action in five stages:
- Build the system prompt: identity constraints, tool list, retrieved skills and memory snippets.
- Compression check: before hitting a threshold, fold early turns into a structured summary; keep decisions and constraints, drop long raw text.
- Interruptible model call: expose a cancel signal; keep completed partial state so the whole round is not discarded.
- Tool execution: parallel or serial calls with timeouts, retries, and result truncation.
- Observe and converge: write results back until the task finishes or a stop condition fires.
Synchronous design trades some throughput for predictable state: one active step at a time. Checkpoints, audit, and replay are easier—and offline evolution needs stable, replayable traces.
4. Runtime skill learning: generate, reuse, prune
A skill is a successful solve path turned into a callable capability. Treat it as structured documents with metadata:
name: batch log anomaly clusteringtriggers: ["log analysis", "anomaly aggregation", "error-code stats"]inputs: {source: path, window: time window}steps:- sample and normalize timestamps- cluster by error code and fingerprint- emit Top-N and trendsconstraints: ["do not scan more than the agreed line budget", "do not exfiltrate raw logs"]stats: {uses: 12, success_rate: 0.92, last_used: ...}
Three mechanisms:
- Generate: after convergence, the kernel checks whether a reusable pattern exists; if so, write a candidate skill into a staging area.
- Reuse: on a new task, retrieve by triggers and semantic similarity; inject only Top-K to protect context budget.
- Prune: periodically drop low-value skills—long unused, success rate well below peers, or near-duplicates that are not better. Archive before delete so you can roll back.
Without pruning, the library bloats, crowds context, and adds retrieval noise. Learning becomes a liability.
5. Multi-layer persistent memory
Layer by lifecycle; do not dump everything into one vector store:
| Layer | Content | Lifetime | Retrieval |
|---|---|---|---|
| Working memory | Current task context | Single session | Full context |
| Episodic memory | Historical tasks and result traces | Medium term | Time + similarity |
| Semantic memory | Distilled stable facts | Long term | Structured fields + vectors |
| Procedural memory | Skills and action sequences | Long term | Trigger matching |
Write raw traces and distilled conclusions separately so long-term memory is not polluted. Forgetting matters as much as layering: set capacity caps and aging rules.
6. Offline evolution and validation: improve without regressing
Online learning is for speed; offline evolution is for stability. Maintain a population of candidate policies (prompt templates, skill combinations, tool-selection rules), score them on a fixed eval set, mutate and select, then promote the winner.
Practical rules:
- Stratified eval set: hold out hard samples that do not overlap training prompts to limit overfitting.
- Composite fitness: task success, tool-call rounds, token cost, and latency.
- Regression gate: a candidate must not degrade vs. the previous version.
- Shadow run: execute off-path, log only, then cut traffic after observation.
The pipeline is fully offline and can run on your own hardware with no hosted evolution service.
7. Heterogeneous execution: one code path, many runtimes
Abstract tools as a unified interface plus capability declarations. Config selects the backend: local shell, container sandbox, remote host, serverless, or cluster sandbox. Differences collapse to three things: filesystem view, network policy, resource limits.
runtime:backend: container # local | container | remote | serverless | clusterlimits: {cpu: 2, memory_gb: 4, timeout_s: 300}network: allowlistworkspace: persistent_volume
On cloud, you typically compose generic capabilities: containers for sandboxes, object storage for skill and memory snapshots, a message queue for dispatch, and logging plus monitoring for observability. Generic product lines such as those on Baidu AI Cloud can serve as one reference composition; choose by isolation strength, cold-start latency, and unit cost. Do not assume any vendor’s catalog is globally identical.
8. Safety governance is not optional
Self-evolution means the system rewrites itself; boundaries must be explicit:
- Least privilege: a skill’s tool whitelist is its maximum authority.
- Change history: every skill and prompt change keeps author, supporting trace, and version.
- Injection defense: treat external content as data, never as instructions.
- Secret isolation: credentials are injected by the runtime, never into prompts or memory.
- Human gates: skills that delete, publish, or write externally require confirmation.
9. Rollout path and common mistakes
Four stages: unify kernel and main loop; add memory and skills; add pruning and offline evolution; then expand heterogeneous backends and governance.
Three frequent mistakes: treating learning as “store chat logs”; generating skills without pruning; evolving offline without a regression gate, so versions oscillate.
Conclusion: Self-evolution is not a single algorithm. It is a closed loop of one kernel + runtime skill capture + layered memory + offline validation. With all four, capability compounds with use; missing one, the system is just another conversational tool.
