Coding assistants · Research feature

Study Shows How Coding Agents Should Store, Recall, and Forget Experience

A new framework enables coding agents to store, recall, and forget experience more effectively, improving task resolution and reducing costs.

Adapted from research by Xinyi Lisa Chen, Pedro Herrero-Vidal, Xiaohan Chen and colleagues.

arXiv preprint revision · 2026-10-19 · Attribution & reuse
In this article
Editorial illustration of linked workflow.

Editor’s introduction

Researchers compared the performance of REM, a memory framework that makes three explicit decisions—what to store, when to recall, and what to forget—against existing memory systems. REM consolidates each completed task into a phase-structured document, injects it at task start or when a struggle signal is detected, and evicts it after one use. On SWE-ContextBench Lite, REM achieved 68.7% retrieval accuracy and improved end-task resolution by 27.6% at 17% lower cost than prior methods. The results show that experience reuse depends not on retrieval quality, but on how experience is structured and governed over time.

Introduction

LLM agents now run unattended for hours, solving exploratory tasks such as repository-level coding and text-to-SQL through hundreds of think-act steps. Each run produces a detailed trace of exploration, dead ends, and an eventual solution, and a growing ecosystem of memory layers and experience-reuse frameworks promises to make that experience compound. In practice it rarely does.

Most work targets the middle of the lifecycle: retrieving the most relevant past trajectory. Three findings from this literature suggest retrieval is not where reuse fails. First, agents use only a fraction of the context they receive, and retrieval alone is insufficient because they must actively interpret what they are given. Second, irrelevant or poorly placed context degrades performance, as models are distracted by irrelevant material and use long contexts unevenly by position. Third, abstraction transfers better than detail: report negative transfer from detailed trajectories, concentrated on the hard cases where guidance is most needed.

These findings share a cause: retrieval cannot observe the state of the running agent, so what happens to a retrieved experience once it enters a long-running loop is left unmanaged. This is most consequential where an agent runs repeatedly against an evolving codebase, its accumulated experience a standing asset whose compounding is the long-run aim of continual learning for agents. We take one step toward that aim, reusing a fixed pool of past runs within a single new run, and find the state of the receiving agent decisive: naively recalled memories leave resolution unchanged even when an oracle supplies the correct experience, and the same memory that helps mid-capability agents costs the strongest ones (§5.5), while agents reference only about a quarter of the identifiers in a raw trajectory and half of those in a prose summary (§5.3).

Agent memory and experience reuse

Self-improvement frameworks store verbal reflections, distilled insights, workflows, or skill libraries and read them back on later tasks, while production memory layers shred histories into factual items or chunks behind a search interface. How well experience transfers depends on how it is stored, with abstract procedural memories transferring more reliably than detailed trajectories. These stored units sit at the extremes of granularity, either isolated facts that lose connective structure or whole trajectories that bury the identifying tokens, and their recall is eager, delivered at the start of the next task. Structured representations of experience have also been proposed, as distilled reasoning strategies, context-aware guidelines selected for the agent’s current state, and subtask-level memories aligned with software-engineering workflows. REM instead consolidates each trajectory into one phase-structured document that is both the retrieval unit and the injected context, discovers its extraction schema automatically, and evaluates it on the resolution and cost of the receiving run against the memory systems benchmarked on the same tasks.

Deciding when to retrieve and what to keep

Adaptive retrieval learns whether a query needs retrieval at all, and context-curation policies learn to insert and delete material from an agent’s working context under a budget. Concurrent work casts memory operations as a learned control policy over when to retrieve, inject, and forget. The machinery for deciding whether to retrieve is well developed; what happens to retrieved experience after it enters a long-running loop is not. REM addresses that second half, the handling of experience after injection, with the simplest sufficient mechanism, an in-loop gate that withholds costly detail until the run shows struggle and evicts it after one exposure, and reports what each decision is worth in end-task resolution and cost.

Context sensitivity and evaluation

Language models are degraded by irrelevant input and use long contexts unevenly by position, so injected experience is not free. Agentic-coding benchmarks have moved from patch correctness toward measuring reuse, and SWE-ContextBench reports that correctly selected summaries help while unfiltered context does not, concluding that agents must interpret what they receive. We take that as the starting point and quantify uptake directly, measuring which injected identifiers a run references and whether that predicts resolution.

Why a store needs a lifecycle policy

Reusing a trajectory is not mainly about finding it. One repository-level run produces tens of thousands of tokens, most recording abandoned paths. Stored raw, a trajectory fails twice: as a retrieval unit its few identifying tokens are diluted by exploration noise, and as injected context its size displaces the new agent’s own reasoning. Shattering it into factoids removes the noise but also the structure that makes a trajectory a solution. The first decision, what to store, is therefore the choice of a form that keeps the structure of a solution while discarding the search that produced it.

The other two decisions cannot be made by the store. Whether injected context helps depends on the state of the receiving agent: one that has already localized the defect gains little and can be derailed, whereas one that has exhausted its hypotheses stands to gain. That state is invisible at retrieval time and changes as the run proceeds, so injection must be decided while the agent works, by a component inside the loop, the second decision, when to recall. Once injected, context left in place biases every later turn toward another run’s solution, so the policy must also say when to remove it, the third decision, what to forget.

Write path

Each stored trajectory is a transcript of 55K–170K tokens. We flatten it to text, keeping user text, assistant text, and tool-call inputs while dropping tool results, which shrinks it roughly fifteenfold with no truncation. One LLM call extracts a schema of typed fields (for coding: files, functions, root cause, fix approach, tests), and a deterministic renderer lays them out as a four-phase document averaging 270 tokens, more than two orders of magnitude smaller than the transcript. In memory terms this is consolidation from an episodic trace into a semantic one: the solution’s structure survives while the exploration noise does not.

Read path

We embed the pool and the new task’s problem statement with an off-the-shelf text-embedding model, pass the five nearest documents by cosine similarity to one LLM rerank call, and inject the selected document. The reranker never abstains; an unparseable reply falls back to the nearest document by cosine similarity. The stage is deliberately simple: our hypothesis is that structuring what is stored matters more than how it is searched.

Recall node: two tiers, a struggle gate, eviction

The 270-token document is injected at the start of the run to orient the agent. The implementation record, the raw edits and verifications from the same trajectory capped at 12K characters, is injected only on demand, the first time the agent fails a validation, our simplest observable evidence that its own approach is not working (edits to test files are filtered so self-written tests do not count as struggle). After one exposure the record is evicted and does not persist in the cached prefix; the phased document, by contrast, stays in context for the whole run. §5.4 ablates both halves, comparing eager against gated injection and eviction against persistence.

Automated schema discovery and measurement

The extraction schema is the memory’s only domain-specific artifact, and a meta-loop learns it from a few example trajectories (nine trajectories from the experience pool, none of them an evaluation task): an LLM writes a candidate prompt, an LLM judge scores each extraction from 1 to 5 on coverage, specificity, discriminability, conciseness, and structural consistency, and weak dimensions are revised for up to five iterations. Porting to a new domain therefore needs example trajectories, not prompt engineering, and the discovered schema matches or exceeds the hand-written one (§5.2; Appendix G).

Benchmark and agent

SWE-ContextBench Lite supplies 99 repository-level bug-fixing tasks, a pool of 300 solved trajectories, and a label marking the trajectory related to each task, which separates retrieval quality from the effect of the retrieved trajectory. A run is resolved when the benchmark’s held-out tests pass on its patch. Every condition runs the same agent on all 99 tasks, built on the Strands framework with six tools (bash, read, write, edit, grep, glob) in a per-task Docker container, capped at 100 turns and a wall-clock limit. Conversation history is never truncated, so injected-context effects are not confounded with history eviction. Claude Sonnet 4.5 is the agent unless stated; §5.5 varies it across five models.

Outcome measures

Resolution is intention-to-treat over all 99 tasks, so a run ending without an applicable patch counts as unresolved. Match@1 is the fraction of tasks whose top-ranked trajectory is the labeled one, comparable to the benchmark’s reported top-1 rate. Treating the label as uniquely correct understates retrieval quality, so resolution is primary and match@1 secondary.

Discussion and limitations

Coding agents produce far more experience than they reuse, and the field’s response has been to build better stores and retrievers, on the assumption that reuse fails because the right run is hard to find. Our results point elsewhere: once an agent is running, what matters is the form its experience was written in, whether it needs that experience now, and how long it should stay in view. Two insights carry beyond REM. First, the stored form determines how much experience is used: the same run, at the same token cost, is read far more completely when organized by the phases of the work, and what separates a successful run from a failed one is how much of what it received it takes up. Second, more memory is not better memory: the gains from delaying and withdrawing costly context came from avoiding harm, and the same content that helped mid-capability agents cost the strongest ones several points.

Because REM treats memory as a set of swappable policy slots rather than a fixed store, its lessons are not tied to our implementation. The stored form is decoupled from the search algorithm, so a phased document can front existing retrievers; the recall and eviction decisions are model-agnostic and apply to any agent with an observable think-act loop; and because the extraction schema is discovered rather than hand-written, the pipeline extends to other diagnostic domains, such as text-to-SQL repair or incident response, from example trajectories rather than new engineering. Cast as a control policy over three decisions, an experience memory becomes something one can measure, price, and improve one decision at a time. These three decisions are exactly the operations a continually learning agent must eventually automate over its own growing experience—what to consolidate, when to surface it, and what to retire—so a mechanism that measures each in isolation is a prerequisite for memory that safely compounds.

Limitations

REM sets a new state of the art for experience reuse on SWE-ContextBench Lite, improving both retrieval and end-task resolution while lowering cost, and it does so with deliberately simple components, which leaves several promising directions open. REM performs single-pass reuse from a fixed pool; letting an agent’s own completed runs re-enter the store, with staleness and contradiction handled, is the natural path toward memory that compounds over time and, ultimately, toward continual learning for agents. The struggle signal is a single hand-written observable, so a calibrated trigger drawing on richer signals, such as repeated failed edits or lack of progress, that spends a bounded budget of disturbance on runs that would have succeeded unaided is a clear next step. Eviction removes the record itself, but the agent’s own response to it remains in the history, so a stricter variant could also prune that response. The utilization probe establishes presence by substring match rather than causal use, inviting richer attribution. Most conditions beyond REM and its ablations were run once, so several secondary contrasts are directional and invite further replication. Retrieval numbers for existing systems are those reported by the benchmark under each system’s own configuration, so a re-run through a shared embedder and reranker would further isolate the stored unit. Every task’s labeled trajectory comes from the same repository as the task (99 of 99), and we did not measure how closely its patch resembles the gold fix, nor how stored fixes age as a codebase evolves. And while we evaluate end-to-end on repository-level coding, the automatically discovered schema already ports to text-to-SQL (Appendix G), so validating the full pipeline in a second domain is an immediate opportunity.

Conclusion

We recast experience memory for long-running agents as a control problem rather than a lookup problem: a policy over three decisions—what to store, when to recall, and what to forget—each of which can be measured, priced, and replaced independently, and each of which we show is worth something on its own. REM realizes this view with a single phase-structured store, a struggle-gated recall, and one-shot eviction, and attains state-of-the-art retrieval and improved end-task resolution at lower cost on a public benchmark.