AI Agents That Get Smarter Over Time: Persistent Memory and Skill Capture in Practice

    This article explains why most AI agents start from scratch in every session and how to fix it by externalizing state. It covers three core mechanisms—persistent memory stored as structured files, reusable skills distilled from successful task traces, and cross-session retrieval—and shows how they form a self-improving loop of execute, distill, store, and recall. It also outlines a layered architecture, key engineering details such as write timing, idempotency, observability, capacity governance, and model decoupling, plus metrics for proving the system actually improves, and the main risks and boundaries.

    AI Agents That Get Smarter Over Time: Persistent Memory and Skill Capture in Practice

    1. The Root Problem: Why Agents Always Start From Zero

    Most agent frameworks run stateless by default: every turn is an independent inference, and the model can only see what fits in the current window. This creates three structural weaknesses.

    First, the context window is a scarce resource. The larger the window, the higher the cost and latency per token, while critical information gets diluted by large amounts of procedural output, producing a “lost in the middle” effect. Second, experience cannot be reused. The same data cleaning task done this week is done again next week, and the model still has to probe field formats and retry failed calls from scratch. Third, personalization cannot accumulate. A user corrects the output style once, and has to correct it again next time.

    So “getting smarter with use” is not about swapping in a stronger model. It is about externalizing state: pulling information worth keeping out of the context window, writing it to external storage that is searchable and versionable, and retrieving it precisely when needed. The industry usually calls this memory augmentation plus workflow capture. It turns a “reasoner” into a “reasoner + memory store + skill library.”

    2. Design Principles of the Three Core Mechanisms

    2.1 Persistent Memory: Writing Preferences and Background as Structured Files

    Persistent memory addresses “persona and project consistency across sessions.” A common engineering approach is to carry it in a small number of plain text files—for example, one profile for user preferences and collaboration conventions, and one for project background and tech stack. Plain text over a database is a practical choice: it is readable, diffable, version-controllable, and easy for humans to correct.

    Memory writes need a gate, or the files get flooded with noise. Three admission rules work well:

    1. Write conditions (any one makes a candidate):
    2. 1. A fact the user explicitly corrected or confirmed;
    3. 2. A stable preference affecting multiple later decisions (output format, language, prohibited items);
    4. 3. Background that cannot be derived from the codebase or docs.
    5. Do not write: one-off temporary values, parameters readable from the environment, speculative conclusions.

    Each memory entry should carry metadata to support later eviction and auditing:

    1. - id: mem-0142
    2. type: preference | project | convention
    3. content: Deliverables default to Chinese; code comments stay in English
    4. source: session-2024-11-03
    5. confidence: 0.9
    6. ttl: none # or 90d
    7. supersedes: mem-0098

    Memory layering matters too. Working memory lives in the current context; episodic memory records “how a given task was done”; semantic memory holds stable facts and preferences. The three have different lifecycles, and mixing them in one layer makes the context balloon quickly.

    2.2 Skill System: Turning Solutions for Complex Tasks Into Callable Assets

    Skill capture addresses experience reuse. A practical trigger condition: the task called many tools, went through multiple rounds of trial and error, and eventually succeeded—only that kind of trace is worth distilling. The output is a structured runbook, not a chat log.

    A solid skill document should include: where it applies and where it does not, prerequisites, a step-by-step process, failure modes and fallback strategies, and verification.

    1. # Skill: Tabular Data Quality Validation
    2. Applies to: field consistency checks across one or more tables; does not apply to unstructured text extraction
    3. Prerequisites: read-only access; primary key fields confirmed
    4. Steps:
    5. 1. Sample 200 rows to infer field types
    6. 2. Compute null rates and enum distributions
    7. 3. Generate validation rules for anomalous columns and trial-run them
    8. Fallback: when type inference confidence is low, switch to a manually specified schema
    9. Verification: rule hit rate and agreement rate against sampled manual review

    A skill library needs governance, or it degrades into a document dump. Three actions help: deduplicate and merge (consolidate semantically similar skills, keeping the version with the higher success rate), versioning and deprecation marking (mark a skill deprecated once an interface it depends on changes), and invocation statistics (downweight or archive skills with zero calls over a long period). Skill invocation should also be parameterized, so concrete values are not hard-coded into the document.

    2.3 Cross-Session Retrieval: Making History a Queryable Source of Evidence

    Full-text search is the recall channel for memory. In practice, conversations and artifacts are stored in a local or cloud relational store with a full-text index built on top; retrieval first does keyword recall, then reranks with time decay, source weighting, and semantic similarity.

    1. -- Example: build a full-text index and recall with time weighting
    2. SELECT id, summary, created_at,
    3. bm25(content) AS kw_score
    4. FROM sessions
    5. WHERE content MATCH :query
    6. ORDER BY kw_score * 0.7 + recency(created_at) * 0.3
    7. LIMIT 8;

    The key to the retrieval path is recall first, rerank second, trim last: keep recall loose so nothing is missed, use reranking for relevance, and trim so the context is not blown out. Permission filtering is mandatory, so user A’s sessions are never retrieved for user B.

    3. How the Three Form a Self-Improvement Loop

    The loop has four steps: execute → distill → store → recall. Task execution produces traces; success is distilled into skills or memory; writes perform deduplication and conflict resolution; on the next similar task, memory and skills are retrieved first, and only then is fresh exploration considered.

    Conflict resolution determines whether the loop stays stable. Prefer “new overrides old + keep history + annotate source” over deletion:

    1. If a new memory conflicts with an old one:
    2. if new.confidence >= old.confidence and the source is an explicit confirmation:
    3. mark the old memory superseded; the new one takes effect
    4. else:
    5. keep both; inject both at retrieval time and flag the disagreement

    Also maintain negative memory: record approaches the user explicitly rejected, so the same mistakes are not repeated. The payoff is often higher than for positive preferences.

    4. Reference Architecture and Key Engineering Details

    A practical layered structure:

    1. Access layer (multi-channel sessions)
    2. ↓
    3. Orchestration layer (intent recognition / plan generation / tool dispatch)
    4. ↓
    5. Memory layer (working · episodic · semantic memory + retrieval service)
    6. ↓
    7. Skill layer (skill registry · versioning and permissions)
    8. ↓
    9. Execution layer (tool sandbox · retry and idempotency · audit logs)

    A few engineering details decide success or failure:

    • Write timing: do not write every turn. Trigger distillation at three moments—session end, task success, and explicit user correction—to reduce noise and cost.
    • Idempotency and rollback: tool calls need an idempotency key; a failed skill run must fall back to the last stable version.
    • Observability: log “memory hit/miss,” “skill invocation success rate,” and “before/after reranking differences,” otherwise you cannot tell whether the system is actually getting smarter.
    • Capacity governance: set quotas and TTLs for memory and skills, and periodically archive cold data to low-cost storage.
    • Model decoupling: abstract model access behind a replaceable adapter layer and switch between vendors’ model services via configuration, avoiding lock-in to a single provider; model choice should weigh task type, latency, and cost together.

    5. Evaluation: Proving It Actually Got Smarter

    No measurement, no improvement. Build three tiers of metrics:

    1. Task level: first-attempt success rate for similar tasks, average tool calls, and average elapsed time, tracked as weekly trends.
    2. Memory level: memory hit rate, adoption rate, conflict rate, and volume of expired entries cleaned up.
    3. Skill level: skill reuse rate, the lift in success rate after reuse versus first-time exploration, and average skill lifetime.

    For the experiment, keep a control group with memory and skills turned off and run an A/B test on the same task set. Only then can the gains be attributed to the mechanisms rather than a model upgrade. If reuse produces no significant lift in success rate, skill distillation granularity is usually too coarse or retrieval recall is inaccurate.

    6. Risks and Boundaries

    • Memory pollution: wrong conclusions recalled repeatedly amplify bias. Countermeasures are source annotation, confidence decay, and periodic manual spot checks.
    • Privacy and compliance: conversations and preference data are sensitive; collect minimally, store encrypted, support deletion per user, and enforce hard isolation for cross-user retrieval.
    • Permission drift: long-running skills accumulate excessive permissions, so review them periodically and follow least privilege.
    • Cost blowout: retrieval and long-context injection are the main expenses; set budgets and a degradation strategy (for example, fall back to pure model inference when recall is insufficient).

    7. Conclusion

    “Getting smarter with use” is not a natural spillover of model capability; it is the result of system design: externalize state, solidify experience, turn history into queryable evidence, and keep correcting with a metrics loop. On the cloud, object storage can hold memory and skill files, a message queue can make distillation tasks asynchronous, a container platform can host the execution sandbox, and logging plus monitoring and alerting can support observability—yielding agent infrastructure that is governable, auditable, and continuously evolvable. Baidu AI Cloud offers general product categories across these layered capabilities of memory, skills, retrieval, and observability, which enterprises can combine as needed to build their own long-term-memory agent.