A Practical Guide to Learning Agents: Architecture, Memory, and Multi-Role Customization
Learning agents improve by capturing verified experience, not by silently retraining model weights. This guide covers a unified execution kernel, layered memory, bounded skills, offline evaluation, role isolation, and a staged path from a working loop to a production-ready system.
1. Learning agents: continuous improvement is not automatic model training
A personal agent is valuable when it can pursue goals, keep necessary context, and turn validated experience into reusable procedures—not only when it answers questions.
A coding assistant can record how a project is tested and which conventions apply after a successful bug fix. A research assistant can capture how sources are filtered and cross-checked. A design assistant can retain confirmed visual rules and delivery checklists. These capabilities reduce repeated coordination only if the system can separate information worth keeping long term from content that is useful only for the current task.
Continuous improvement usually has three distinct layers:
- Memory updates: store user-confirmed preferences, project facts, and task state.
- Skill updates: turn successful work into callable, inspectable procedures.
- Model training: change model parameters through a separate training pipeline.
The first two do not require changing model weights and are typically easier to implement, audit, and roll back. The third needs data governance, training resources, and independent evaluation. Runtime memory writes must not be treated as model training.
Build a closed loop of task execution → result verification → experience extraction → controlled reuse. Do not chase unverified self-improvement.
2. A unified execution kernel with multiple entry points
A maintainable agent system can share one execution kernel across CLI, messaging, editor, and batch-task entry points:
CLI / messaging / editor / batch-task entry↓authentication and request routing↓agent execution kernel↓model calls / memory retrieval / skill selection / tool execution↓state persistence and audit records
A shared kernel avoids each entry point inventing its own permission checks, memory rules, and tool-calling logic. The same role should follow the same constraints regardless of where a task arrives.
Shared code does not mean a single process or a single state store. Production systems can reuse the same kernel implementation while deploying roles as separate instances with their own credentials, storage, and execution permissions.
2.1 Reason-and-act loop
A typical loop:
- Read the user request and confirm identity and role.
- Load required project state, long-term memory, and candidate skills.
- Build the input context and check remaining context budget.
- Call the model for an answer or a structured tool request.
- Authorize the tool call and validate parameters.
- Execute, then persist results and errors.
- Continue reasoning from the outcome, or stop.
Cap iteration count, wall-clock time, tool-call budget, and cancellation. Without those limits, the agent can loop on failed actions and consume unbounded resources.
2.2 Context compression
When history is too long, older turns can be summarized. A useful summary keeps more than “what happened”:
- current goal and acceptance criteria
- explicit user constraints
- confirmed important facts
- methods already tried and failed
- unresolved issues
- where key evidence lives
Keep a link from the summary back to original records. For code changes, data processing, or research conclusions, you must be able to return to source evidence. Do not treat the summary as the only source of truth.
3. Layered memory: separate preferences, facts, and process
More long-term memory is not better. Saving every conversation increases noise, privacy risk, and error propagation. Split memory by purpose.
3.1 Session working memory
Hold information in active use: recent results, open items, and temporary hypotheses. This layer is short-lived. After the task, clear it or keep only a necessary summary.
Do not promote speculation into a long-term fact store. “This module might be the cause” is a hypothesis, not a later-task conclusion.
3.2 User and project memory
User memory fits confirmed preferences: language, report format, approval habits. Project memory fits directory conventions, test requirements, deployment constraints, and domain terms.
Each long-term item should include source, update time, scope, and confirmation status. Volatile facts need review or expiry. “Tests live in this directory” may be stable; “current release owner” is not. Do not apply the same retention policy to both.
3.3 Task-event memory
Record the key path of a piece of work: inputs, major decisions, actions, outcomes, and failure reasons. The point is traceability, review, and skill extraction—not replaying full chat logs.
Prefer retrieval by current project, task type, and recency, not text similarity alone. A highly similar but outdated record can be more harmful than missing memory.
3.4 Write control and privacy
Filter writes. Credentials, sensitive personal data, and unauthorized content must not be saved just because they appeared in a conversation.
A safer pattern is to mark candidates as pending confirmation, then promote them by rule or user action. Provide view, correct, delete, and export so long-term state stays manageable.
4. Skills: bounded operating procedures, not slogans
A skill is a procedure with inputs, outputs, and acceptance—not a claim that the agent “has learned” something.
A generic skill might look like:
Skill name: Locate and fix a regressionPreconditions: a reproducible issue and required code accessInputs: problem description, relevant paths, reproduction steps, acceptance criteriaSteps:1. Confirm workspace state2. Reproduce the issue and keep evidence3. Narrow the blast radius4. Apply the smallest necessary change5. Run related tests6. Summarize changes, verification, and residual riskLimits: no deploy, data deletion, or credential changes without approvalOutputs: change notes, test evidence, open items
Record preconditions. Do not copy one success as a universal rule. Raising a timeout once does not mean every connection error should get a longer timeout.
4.1 Extract candidate skills from traces
Focus on transferable decisions: how the problem was confirmed, which tools were chosen, how success was judged, and how failures were handled. Strip user names, temporary paths, sensitive data, and incidental environment details, or turn them into input variables.
4.2 Evaluate before enabling
Validate candidates on independent test tasks. Cover not only happy paths but also insufficient permissions, missing inputs, tool failures, and environment drift.
Only versions that meet preset acceptance criteria enter the usable skill library. One or two successes must not auto-replace a previous version.
4.3 Govern duplicates and stale skills
Track version, status, dependencies, and usage. Overlapping skills can be proposed for merge; do not auto-delete on text similarity alone.
Low usage is not the same as low value—emergency recovery may be rare and still essential. Cleanup should weigh effectiveness, applicability, risk, and alternatives, and keep recoverable history.
5. Offline evaluation: evidence over impression
Offline tests can compare prompt strategies, skill versions, or retrieval rules. They cannot prove better behavior in every real environment.
Use four task types:
- Normal tasks: expected capability.
- Boundary tasks: missing information, oversized input.
- Failure tasks: tools unavailable, timeouts, missing dependencies.
- Safety tasks: overreach requests, sensitive data handling, untrusted content.
Measure quality and cost together: completion rate, factual error rate, tool-call count, runtime, resource use, and whether forbidden actions were attempted.
Automated search may propose candidates; production still needs independent evaluation and controlled release. Keep evaluation data separate from training data so memorizing test cases is not mistaken for generalization.
Do not let the agent “succeed” by loosening acceptance criteria. Criteria must be set by an external process or an authorized person, not by the agent under test.
6. Multi-role customization: isolation before personality
Coding, research, and design roles can share model-calling infrastructure. They should not share all memory, files, and credentials by default.
| Role | Core duties | Primary resources | Key limits |
|---|---|---|---|
| Coding | Diagnose issues, change code, run tests | Designated code dirs, test environments | No direct production operations by default |
| Research | Gather sources, compare evidence, write reports | Authorized libraries, search | Separate fact from inference; keep sources |
| Design | Capture requirements, set specs, check delivery | Design docs, authorized assets | No unapproved publish; no extra asset access |
Each role needs its own system rules, memory namespace, skill catalog, execution identity, and message routing.
Tone can vary; it cannot replace duty constraints. “Be a cautious researcher” is too vague. “Mark uncertainty when evidence is thin; independently verify key conclusions” is checkable.
6.1 Isolation levels
Directory layout is organization, not a security boundary. Shared OS identity can still reach another role’s files.
For higher security, use separate identities, isolated runtimes, storage ACLs, and network policy. Grant credentials separately under least privilege.
6.2 Controlled sharing
Shared terms and org-wide standards can live in a read-only knowledge area. Private role memory stays private. Cross-role transfer should state purpose, authorization scope, and expiry.
That avoids duplicating public knowledge and reduces contamination from one role’s bad memory.
7. Execution environments and message entry: convenience cannot cross the safety boundary
Agents may run locally, in isolated containers, on remote hosts, or in controlled compute. Unify working directory conventions, timeouts, output size limits, and error shapes where possible, but do not assume identical behavior after a backend change.
Paths, network access, dependency versions, and resource limits differ. Skills should declare environment requirements and check them before running.
Tool calls need at least:
- input structure and allowed-range checks
- read/write directory limits
- timeouts and resource caps
- explicit approval for dangerous operations
- redaction of sensitive content in logs
- records of actions and results
Message entry also needs authentication, request deduplication, and session binding. Duplicate messages must not re-run side-effecting actions such as payments, publishes, or deletes.
Treat external documents and tool output as untrusted. Instructions such as “ignore previous rules” must not change permissions or approval requirements.
8. From zero to production: close the loop, then automate
Recommended order:
1. Define tasks and acceptance. Pick a few high-frequency tasks per role. Specify inputs, outputs, and done criteria. Do not start with unbounded “do everything” duties.
2. Set execution boundaries. Independent identities, working directories, storage, and tool permissions. Start in test environments and confirm roles cannot read or write across boundaries.
3. Complete a minimal task loop. Request in, model call, tool execution, result out, state saved. Exercise cancel, timeout, and failure recovery.
4. Add controlled memory. Start with user-confirmed preferences and project facts. Check retrieval quality before adding task-event records.
5. Establish baseline skills. Prefer human-written, verified procedures first. Only then generate candidates from traces, so low-quality experience does not pile up.
6. Add continuous evaluation. After prompt, skill, or memory-policy changes, run the same regression suite. Quality gains must not come from overreach or runaway cost.
7. Harden long-running operations. Queues, health checks, alerts, backup and restore. Bounded retries on failure, and no duplicate side effects.
Long-running does not mean the model is always on. Idle when there is no work; trigger on events or schedules to control cost and avoid pointless actions.
9. Final acceptance: is the system actually usable?
Before production, verify at least:
- Do all entry points honor the same role permissions?
- Can unconfirmed information be written into long-term memory by mistake?
- After compression, can task constraints and key evidence still be traced?
- Do skills have preconditions, versions, and rollback?
- Can external content induce unauthorized execution?
- After interrupt or restart, are side-effecting actions replayed?
- Can the three roles run independently inside explicit boundaries?
- Can the system explain which memory, skills, and evidence a given action used?
Reliability comes from a verifiable execution loop, traceable long-term state, and constrained tools. Make work observable first, then reusable, then more automated through independent evaluation—so the agent is a stable work system, not a demo.
