Agent Memory That Compounds: Engineering Persistent Memory, Skill Capture, and Cross-Session Retrieval
Most AI agents start from zero every session because their context window is volatile and tied to the process lifecycle. This article explains how to move state outside the context window and turn it into durable, searchable, versioned engineering assets. It covers three mechanisms that form a closed loop: layered persistent memory with a deliberate write policy, skill capture that turns solutions into reusable assets, and cross-session retrieval backed by local structured storage and full-text search. It also details how the loop runs, common pitfalls around privacy, context budget, conflict resolution, and observability, plus an evaluation framework for proving measurable gains.
1. The Starting Problem: Why Most Agents Begin From Zero Every Time
As intelligent coding tools and general-purpose agents see broad adoption, one experience problem keeps resurfacing: a task you explained clearly yesterday has to be explained again today. User preferences, project conventions, and records of past mistakes all disappear when the session ends. The root cause is not mysterious — for most agents, the context window is volatile, the session lifecycle is bound to the process lifecycle, and a restart means amnesia.
Changing this requires moving memory out of the context and into something outside it: externalizing state as a persistent, searchable, versionable engineering asset. The three mechanisms discussed here — persistent memory, skill capture, and cross-session retrieval — all serve that goal. They are not three isolated features but a closed loop: memory supplies personalized priors, skills supply reusable solutions, and retrieval supplies long-horizon lookback.
2. Mechanism 1: A Layered Design for Persistent Memory
2.1 Memory Is a Layered Structure, Not One Large File
The more robust engineering choice is to layer memory, so that all information is not crammed into a single document where it bloats and conflicts:
- Identity layer: the user’s role, communication style, and review habits; changes very rarely.
- Preference layer: technology stack choices, naming conventions, commit granularity, testing requirements.
- Project layer: repository structure, module boundaries, build process, known legacy issues.
- Task layer: current iteration goals, temporary constraints, hypotheses still to be validated; shortest lifecycle.
Layering pays off immediately because loading strategies can differ per layer: the identity and preference layers stay resident, the project layer is injected as a summary on demand, and the task layer is mounted only in relevant sessions.
2.2 Write Policy: From Recording Everything to Recording Decidable Facts
Memory quality depends on write quality. A practical rule is to persist only information that is reusable (likely to be relevant again), decidable (an explicit constraint rather than a vague impression), and durable (not expiring within a week). One-off debugging details belong in the retrieval layer, not the memory layer.
Each memory entry should be structured, which makes deduplication and conflict detection easier:
- id: pref-017layer: preferencestatement: Use the "type: summary" format for commit messages, with the body explaining the motivationconfidence: 0.9source: session-2025-03-11ttl: null
Here confidence expresses uncertainty, source preserves a traceable origin, and an empty ttl means the entry is valid indefinitely. When a new memory conflicts with an older one, handle it by overwriting and keeping the previous version, rather than discarding history outright.
2.3 Building the User Model Incrementally
One level above individual memory entries is the user model: the agent’s abstraction of who you are and how you work. It should be aggregated from many lower-level memories and remain open to explicit correction. The key principle is that the user model must be editable and explainable — users need to see why the agent understands them this way. Otherwise personalization slides quickly into misjudgment.
3. Mechanism 2: Skill Capture Turns Solutions Into Assets
3.1 Trigger Conditions and the Boundary of Abstraction
When a task requires many tool calls and spans multiple steps to complete, it usually contains reusable structure, and that is the point at which capture is worth triggering. Watch the boundary of abstraction, though: a skill should describe the steps and checkpoints for solving a problem, not record one specific output. Writing incidental details into a skill turns reuse into a burden.
A sound skill document typically includes: applicable scenarios, prerequisites, execution steps, failure fallback, and verification.
# Skill: Adding unit tests to an existing moduleApplicable scenario: a module lacks tests and its current interface must stay unchangedPrerequisites: a runnable build script, a readable dependency manifestSteps: locate entry points -> map branches -> build minimal cases -> run -> fixFallback: if cases depend on unstable external resources, replace them with injectable test doublesVerification: coverage and assertions on key branches both pass
3.2 Retrieval, Reuse, and Retirement of Skills
Once the skill library grows, two problems must be solved: findability and retirement. Findability relies on hybrid semantic and keyword retrieval. Retirement relies on usage statistics: skills that go unmatched for a long time, or that have a low success rate once matched, should be down-weighted or archived. A skill library needs review and versioning just like a code repository, so that mistaken experience is not reused repeatedly.
4. Mechanism 3: Cross-Session Retrieval and Long-Horizon Lookback
4.1 Local Structured Storage Plus Full-Text Indexing
Writing historical sessions into a local structured database and building a full-text index is the lowest-cost, most privacy-controllable option. The data stays on the machine, retrieval does not depend on external services, and isolating data per project is straightforward.
CREATE TABLE session_msg (id INTEGER PRIMARY KEY,session_id TEXT NOT NULL,role TEXT NOT NULL,content TEXT NOT NULL,created_at TEXT NOT NULL);CREATE VIRTUAL TABLE session_fts USING fts5(content, content='session_msg');
4.2 Retrieval Quality Hinges on Chunking and Reranking
Matching an entire long conversation at once introduces a large amount of noise. In practice, split by intent unit first, then rerank candidate fragments and inject only a few highly relevant ones into the context. On the query side, rewriting helps: expanding a colloquial question into a form that includes project names, module names, and error keywords typically improves recall noticeably.
5. How the Three Work Together: Making the Loop Real
The loop runs in this order: at session start, load the identity and preference layers to form a prior; during execution, retrieve historical fragments on demand to fill in details; after the task completes, write stable conclusions back into memory and capture complex solutions as skills. The next session therefore starts from a higher baseline — which is the engineering meaning of getting smarter with use.
One caveat deserves emphasis: growth does not mean unlimited expansion. A self-improving system without retirement and down-weighting mechanisms will eventually be slowed down by stale information. The loop must include forgetting.
6. Implementation Essentials and Common Pitfalls
- Privacy and boundaries: memory and history involve sensitive information, so support per-project isolation, export, and one-click deletion.
- Context budget: cap resident content, and convert the overflow into summaries or on-demand retrieval.
- Conflict governance: both memory and skills need overwrite and versioning policies to avoid self-contradiction.
- Observability: log which memory was loaded and which skill was matched, so the source of faulty personalization can be traced.
- Evaluation first: prepare a fixed task set and compare completion rate and step count with memory and skills on versus off, validating the benefit with data.
7. Evaluation Framework: Proving the Agent Actually Got Smarter
Three categories of metrics are worth using: efficiency (steps and tool calls needed to finish a task), consistency (whether output style is stable across similar requests), and lookback (whether decisions from weeks earlier can be cited correctly). Only repeated measurement on the same task set turns “this feels smoother” into a verifiable conclusion.
8. Combining With Cloud Capabilities
To productize these mechanisms, general cloud capabilities are usually enough: object storage to keep versioned history of memory and skill assets, a container platform to host the agent runtime for environment consistency, logging and monitoring with alerting to observe matches and failures, and a message queue to decouple asynchronous writes of capture tasks. Baidu AI Cloud offers corresponding capabilities in these general categories, and they can be combined freely to fit your own architecture without binding to a specific implementation.
9. Conclusion
Whether an agent can keep growing depends on whether state is designed as a first-class citizen. Persistent memory solves “remembering you,” skill capture solves “knowing how to do this kind of task,” and cross-session retrieval solves “finding old conclusions again.” Layered together with forgetting and evaluation mechanisms, they turn occasional cleverness into a stable capability curve.
