Sessions, Memory & Compaction

Agentic AI · L-Memory

How an agent built on a stateless model remembers: the session and its compaction, long-term memory and its selection, and the choice of who decides what is kept.

Learning Objectives

  1. Explain why memory must be managed (the model is stateless, → L-ReAct), and describe a memory design as a choice of write · manage · read.
  2. Distinguish short-term (context) vs long-term (persisted) memory, and name the four memory modules (working / semantic / episodic / procedural).
  3. Explain session persistence as JSONL (append-only, streamable), and separate the session log from working memory.
  4. Classify each compaction operation as a choice of $W$ or $P$, and derive the order of a compaction pipeline from which operations the stored record can undo.
  5. Describe each long-term module as a choice of $W$, $P$ and $R$: semantic memory by extraction and consolidation, episodic memory by scored recall (recency · importance · relevance) and reflection.
  6. Explain how skills externalise procedural memory, and compute the context cost of progressive disclosure.
  7. Compare harness-driven and self-directed memory management and a context reset by who computes $W$, $P$ and $R$.
  8. Distinguish end-to-end from stage-wise memory evaluation, and name the operation a measured failure belongs to.

Overview

Memory is a service of the runtime, not a property of the model. Part I fixes the vocabulary — three operations and four memory modules — and every later part applies it to one store:

Part The question it answers Sections
I · Memory Operations and Modules What does an agent built on a stateless model store, and which operations act on the store? Runtime Memory: Short-Term & Long-Term · Memory Modules: Working, Semantic, Episodic, Procedural
II · Short-Term Memory How is a session kept within the context window, and what remains recoverable after compaction? Session Log · Compaction
III · Long-Term Memory What is kept beyond the trial, in which module, and how is each module written, managed and read? Semantic Memory · Episodic Memory · Procedural Memory
IV · Memory Control Which party computes $W$, $P$ and $R$ — the harness, the model or a fresh agent? Context Reset vs. Compaction

Memory Evaluation and privacy close the lecture, and both are organised by operation as well.

Part I — Memory Operations and Modules

A language model keeps no state between two calls, so whatever an agent remembers has been stored by the runtime and placed back into the context. Memory is a component of the harness, described along two independent axes: by operation — what the harness does to a store (write, manage, read) — and by module — the role a store plays for the agent (working, semantic, episodic, procedural). Every mechanism in the later parts is a choice of the three operations, applied to one of the four modules.

Runtime Memory: Short-Term & Long-Term

Each model call re-sends the whole context box of the agent loop — everything placed into one model call — so "memory" is whatever the runtime stores and re-assembles into that box, and it is either short-term or long-term:

  • Short-term: the running conversation of the current session, one persisted conversation, which the lecture treats as one trial (Narrow and Broad Memory). The context holds a rendering of it; the session log holds it in full.
  • Long-term: facts, preferences and past experiences persisted beyond the session and placed back into the context by a read — a similarity search (→ L-RAG), a score over several terms, or the agent model opening an entry of an index.

Memory Operations: Write, Manage, Read

An agent's memory is the information it retains from its interaction with the environment — from the current trial, from earlier trials, and from external knowledge — and three operations act on it in every step: writing stores what the agent perceived, management processes what is stored so that it stays usable, and reading selects what the next action is based on (Zhang et al., 2025, §3). The boundary between short-term and long-term memory is an observable event: the end of a trial, one attempt at a task that consists of steps (Zhang et al., 2025, §3.1).

  • A task $\mathcal{T}_k$ is the goal the agent has to achieve, such as book a flight for Alice. An agent meets a sequence of tasks $\mathcal{T}_1, \dots, \mathcal{T}_K$, and $k$ indexes them.
  • A step is one action of the agent followed by the environment's response to it: $a_t$ is the action and $o_t$ the response, the observation, at step $t$.
  • A trial is one complete attempt at a task, from the first action until the attempt ends. A task may take several trials — a failed attempt followed by a new one — and the $j$-th trial of $\mathcal{T}_k$ is the sequence $$\xi^{k,j} \;=\; (a_1, o_1, a_2, o_2, \dots, a_T, o_T),$$ with $T$ its length in steps. Where one trial is meant, the superscripts are dropped.

Narrow and Broad Memory

Narrow memory is derived only from the current trial: before step $t$ it is the history $\xi_t = (a_1, o_1, \dots, a_{t-1}, o_{t-1})$, and it is emptied when the trial ends (Zhang et al., 2025, §3.2). The subscript counts steps, so $\xi_t$ is a prefix of the current trial. Broad memory for the $j$-th trial of task $\mathcal{T}_k$ is derived also from earlier trials, the set

$$\Xi^{k,j} \;=\; \{\xi^{i,m} : i < k\} \;\cup\; \{\xi^{k,m} : m < j\}$$

of all finished trials of the tasks $\mathcal{T}_1, \dots, \mathcal{T}_{k-1}$ and of the earlier attempts at $\mathcal{T}_k$, and from external knowledge $D$, information the agent did not obtain by acting (Zhang et al., 2025, §3.3); $\xi^{k,j}_t$ is the history of the current trial with its superscripts written out. A lowercase $\xi$ is one trial or a prefix of one, a capital $\Xi$ a set of trials. This lecture calls a store the agent does not write a knowledge base.

Narrow memory Broad memory
Derived from $\xi_t$ $(\xi^{k,j}_t,\ \Xi^{k,j},\ D)$
Survives the end of the trial no — emptied yes — across trials and tasks
Usual name (Zhang et al., 2025, §5.1.2) short-term — the inside-trial information long-term — the information from earlier trials; external knowledge is a third source

This lecture treats a session — one persisted conversation — as a trial. Short-term and long-term memory therefore differ by an observable event, the end of a trial, and not by duration: long-term memory is produced by the same operations $W$, $P$ and $R$, with $P$ acting across trials.

Memory Writing

Writing turns the raw outcome of a step into what is actually stored (Zhang et al., 2025, §3.4):

$$m_t \;=\; W(a_t,\, o_t)$$

$W$ is a projection: it maps the action $a_t$ and the observation $o_t$ of step $t$ to the record $m_t$, which is meant to be more informative and more concise than the raw pair. The record is natural-language text or a structure derived from it — a fact, a triple, an embedded passage — stored outside the model. Zhang et al. (2025, §5) also admit a parametric record, written into the model's weights by fine-tuning or knowledge editing; that form lies outside this course, which treats the weights as given. $W$ decides what is worth storing, and in what form — a verbatim turn, an extracted fact, a summary of the step.

Memory Management

Management processes what is already stored, so that it remains useful (Zhang et al., 2025, §3.4):

$$M_t \;=\; P(M_{t-1},\, m_t)$$

$M_{t-1}$ is the content of the store before step $t$, and $P$ combines it with the new record $m_t$ into the store $M_t$ after it. Zhang et al. (2025) write one store $M_t$ for all memory. An agent usually keeps two: working memory $M_t$, the records of the current trial from which each prompt is rendered, and a long-term store $L_t$ of records that survive the trial. The equation is written for $M_t$; the long-term store is managed by the same equation with $L$ in place of $M$, $L_t = P_L(L_{t-1},\, W_L(a_t, o_t))$, where the subscript names the store. In the trial notation, $M_{t-1}$ holds the records of the history $\xi_t$, on which the action $a_t$ is based, and $M_t$ those of $\xi_{t+1}$. $P$ is applied again at every step, and it is where the store is improved rather than merely extended:

  • summarising — deriving higher-level statements from many records, which makes the agent generalise;
  • merging — joining similar records, which removes redundancy;
  • forgetting — removing unimportant or irrelevant records, which removes their negative influence on later steps.

Management changes what is stored, and it treats the new record like any other: it may merge $m_t$ into an older record, let it replace one, or discard it as already known. §3.4 of Zhang et al. (2025) defines management as processing "the stored memory information to make it more effective", and $P$ receives $m_t$ as an argument. Mem0's update step decides for each new fact whether to add it, to merge it into an existing record, to delete a record it contradicts, or to discard it (Chhikara et al., 2025, Alg. 1). Where $P$ performs none of these operations, it adds $m_t$ and leaves $M_{t-1}$ unchanged — $M_t = M_{t-1} \cup \{m_t\}$, or, for a store kept in order, $m_t$ placed after the last record — and the store grows by one record per step without being managed. An append-only log is a store of exactly this kind.

The reach of $P$ is what separates the two definitions of memory. For narrow memory, $P_M$ acts on working memory $M_t$, which is emptied when the trial ends. For broad memory, $P_L$ acts in addition on the long-term store $L_t$, across trials and tasks, and takes in external knowledge.

Memory Reading

Reading selects from a store what the next action needs (Zhang et al., 2025, §3.4). The prompt is filled by one read per store, and the two results share one context window of $T_{\max}$ tokens:

$$\hat M_t \;=\; R_M(M_t,\, c_{t+1}), \qquad \hat L_t \;=\; R_L(L_t,\, c_{t+1}), \qquad \lvert c_{t+1}\rvert + \lvert \hat M_t\rvert + \lvert \hat L_t\rvert \;\le\; T_{\max},$$

where $c_{t+1}$ is the context of the next action — the task and the situation at step $t+1$ —, $\lvert x\rvert$ is the length of $x$ in tokens, and the subscript of $R$ names the store that is read; Zhang et al. write one read $R(M_t, c_{t+1})$ for their single store. Both reads receive $c_{t+1}$ and differ in what they do with it: $R_L$ selects the $n$ records most similar to $c_{t+1}$, because a long-term store holds more records than one prompt; $R_M$ usually ignores $c_{t+1}$ and renders working memory whole and in order, so the bound on $\hat M_t$ is enforced by compaction (Compaction), whose management steps $P$ shorten or remove records of $M_t$.

The selected records become part of the prompt that produces the next action, so a read decides which records the next action gets; a record that is stored but never selected has no effect on the agent. Without a subscript, $R$ denotes either read — a statement about $R$ holds for $R_M$ and $R_L$ alike, and where only one store is meant, the context names it; $W$ and $P$ are written the same way.

The Memory Loop

The three operations compose into the agent loop, from the outcome of step $t$ to the action of step $t+1$:

$$a_{t+1} \;=\; \mathrm{LLM}\bigl(c_{t+1},\ \hat M_t\bigr), \qquad \hat M_t \;=\; R\bigl(P(M_{t-1},\, W(a_t, o_t)),\; c_{t+1}\bigr)$$

Here $\mathrm{LLM}$ is the model, read as a map from a prompt to the next action. The model reads one token sequence: the harness writes the selected records $\hat M_t$ as text and places them in one sequence with the context $c_{t+1}$, so the two arguments name the two sources of that sequence. They are written apart because they differ up to that step: $c_{t+1}$ belongs to the current step, the store persists from step to step and changes through $W$ and $P$, and $\hat M_t$ is selected by $R$ against $c_{t+1}$, so the context exists before the read. Read from the inside out: the step is written as a record, the record is managed into the store, the store is read against the next context, and the model acts on the context and what was read. Applying the loop at every step reproduces the whole interaction between agent and environment. With a long-term store as well, the model receives both reads, $a_{t+1} = \mathrm{LLM}(c_{t+1},\ \hat M_t,\ \hat L_t)$, and $W$, $P$ and $R$ act on each store separately.

A knowledge base read by retrieval-augmented generation adds a further argument to $\mathrm{LLM}$; it is not part of $M_t$, because the agent does not write it.

Whatever the store is made of, an agent does these three things to it, so a memory design is specified by its choice of $W$, $P$ and $R$, and published systems differ in that choice.

Memory Modules: Working, Semantic, Episodic, Procedural

Everything an agent knows sits in one of four memory modules — one short-term, three long-term. The decomposition comes from Soar, a cognitive architecture — a program that models human problem solving with separate memory stores — and was carried into language agents by CoALA (Cognitive Architectures for Language Agents, Sumers et al., 2024), a framework that describes a language agent by its memory modules, its action space and its decision cycle.

Type Stores In practice
Working (short-term) the current decision cycle (one pass of observe, decide, act) — perceptual input, knowledge just retrieved or reasoned, the active goals the context box and the runtime's own state; each prompt is synthesised from it, each output parsed back into it
Semantic facts — "knowledge about the world and itself": user preferences, facts the agent has inferred, and — in CoALA's reading — a corpus loaded from outside a user profile (JSON) or a collection of facts (LangChain, 2026, Core Concepts); recalled by similarity
Episodic experiences — "experience from earlier decision cycles" (CoALA); LangMem narrows it to successful interactions (LangChain, 2026, Core Concepts) dated records of past steps or sessions, such as the memory stream of Generative Agents; in LangMem, successful interactions kept as few-shot examples ("how I did this before")
Procedural how-to — two stores at once: the model weights, and the agent's own code the system prompt and skill files; self-refinable via reflection (→ L-ToT) / prompt optimisation (→ L-Eval)

Working memory is not the context. Sumers et al. define it as "a data structure that persists across LLM calls"; the context, the token sequence the model reads in one call, is one rendering of it, produced by the read $R_M$. A session is therefore kept within the context window in two ways: by rendering only part of working memory, which leaves the store unchanged, or by replacing records of working memory with a summary, a management step $P$ (Compaction). The turns removed from working memory remain in the session log.

Part II — Short-Term Memory

Short-term memory is kept in two stores, the session log and working memory, and compaction manages only working memory. Both are derived from the current session alone, as narrow memory is (see Narrow and Broad Memory), but only working memory is emptied when the session ends:

  • the session log on disk records every step verbatim and may grow without limit; its write is an append, and nothing manages it; it stays on disk as the record from which a removed message is recovered, and no later session reads it as memory;
  • working memory $M_t$ is, in a chat agent, a list of typed messages — system prompt, user and assistant turns, tool calls, tool results — from which each prompt is rendered; it is emptied when the session ends.
Store $W$ $P$ $R$
session log (JSONL) append every step verbatim none — nothing is rewritten only to recover or to audit
working memory $M_t$ the record $m_t$ of each step, shortened by persist when an observation is too large the other forms of compaction renders $M_t$ into the prompt
W: appendW: record m_tP: compactionR: renderstep t: action a_t,observation o_tsession log · JSONLcomplete, unboundedworking memory M_tboundedprompt (c_t+1, M̂_t)model call

The context window bounds the rendering, not the list, and a rendering that fits the window is not necessarily used in full: in multi-document question answering, GPT-3.5-Turbo answers less accurately when the document that holds the answer stands in the middle of its context than with no document at all, from its weights alone — below its closed-book accuracy of 56.1 % (Liu et al., 2024). Accuracy depends on where the relevant text stands in the context. Trimming and compaction keep the rendering within the bound. Trimming leaves the list unchanged and lets the read $R_M$ render its longest suffix that fits, starting at a user turn so that no tool result appears without its call. Compaction shortens the list itself, for example by a rolling summary into which the messages leaving the window are folded (Packer et al., 2024). A record removed from $M_t$ remains recoverable exactly as long as the log still holds it.

Session Log

A session log is stored one record per line and written only by appending. A session — one persisted conversation, one trial — is stored as JSONL (JSON Lines): one JSON object per line, one line per event, and the log is written by a single operation, append. JSONL is a convention in wide use for logs, event streams and growing conversation histories. The records below are a simplified example from the session files of the agent toolkit on which OpenClaw is built (Völkl, 2026a); their field names belong to that implementation.

{"type":"message","role":"user","content":"Hi","id":"c3","parent_id":"a1"}
{"type":"message","role":"assistant","content":"Hello!","id":"e5","parent_id":"c3"}
{"type":"compaction","summary":"user greeted","id":"g7","parent_id":"e5"}
  • Append-only. A new turn is one new line; nothing already written is rewritten. A crash can damage at most the last line, which a reader detects and discards.
  • Streamable. A reader processes the file line by line, without parsing it as a whole — which a single JSON array would require.
  • A tree, not a list. Each record names its predecessor in parent_id. Editing an earlier message or retrying a turn appends a new record with the same parent, which creates a branch; the conversation currently continued is the path from the latest record (the leaf) back to the root.
  • Compaction is logged, not applied to the log. The third line records the output of $P$ — a summary that replaces the earlier turns in working memory — while the log still holds those turns.

Compaction

Compaction keeps the rendering of working memory within the context window by removing or shortening records: a write $W$ when it shortens the record of a step before the record enters $M_t$, a management step $P$ when it changes records already in $M_t$. The forms that replace whole records — the sliding window and the summary — replace the records before a cut point by one record and keep the records after it verbatim. With the record $m_t$ of step $t$ written by $W$,

$$M_t \;=\; P(M_{t-1},\, m_t) \;=\; \bigl(\,s_\ell,\; m_{\ell+1}, \dots, m_t\,\bigr), \qquad s_\ell \;=\; \sigma(m_1, \dots, m_\ell),$$

where $\ell < t$ is the cut point and $\sigma$ maps the records up to it to the single record $s_\ell$ that stands in for them; the sliding window and the summary differ in the choice of $\sigma$, and the remaining forms act on single records (see Forms of Compaction). Between two compactions $P$ only appends $m_t$; each compaction moves $\ell$ forward, and $\sigma$ then receives the earlier $s_\ell$ in place of the records it already replaced — so a second summary summarises the first.

Forms of Compaction

Each form of compaction is either a write $W$, which shortens the record of a step before it enters working memory, or a management step $P$, which changes records already in it. The forms differ in what they remove, whether they call a model, and whether every record left in $M_t$ is still text from the log. A harness applies the forms that keep every record verbatim or as a marker first, and summarises only if the context is still over budget: a removed record is restored by reading the log only while every record of $M_t$ is text from the log, and a summary is new text that the log does not contain.

Under compaction, $R_M$ selects nothing: $\hat M_t = R_M(M_t, c_{t+1}) = M_t$, so every record in $M_t$ is in the next prompt, and which records of the session reach the prompt is decided by the management steps $P$; persist sets how much of a new observation enters $M_t$.

Form Operation What it does Removed from $M_t$ Model call Every record in $M_t$ is verbatim from disk or a marker
persist $W$ if the observation $o_t$ exceeds a size limit, $o_t$ is written to a file, and $m_t$ holds the file path and the first lines of $o_t$ instead of $o_t$; records already in $M_{t-1}$ are not changed the full $o_t$ — it never enters $M_t$ no yes
sliding window $P$ keeps the last $N$ records and deletes all earlier ones: $\sigma$ returns the empty record whole steps $m_1, \dots, m_{t-N}$ no yes
placeholder (also called pruning) $P$ replaces the content of every observation older than the last $n$ by a one-line marker — Old output omitted (101 lines) in SWE-agent (Yang et al., 2024) — or by the file path saved by persist; the action, the tool call, stays in $M_t$ at its position the content of old observations no yes
token deletion $P$ a small language model (Alpaca-7B or GPT2-Alpaca in the experiments of Jiang et al., 2023) computes, for each token $x_i$ of a record, the probability $p(x_i \mid x_{<i})$ given the tokens before it; the tokens with the highest probability carry the least information, $-\log p(x_i \mid x_{<i})$, and are deleted until the text reaches a target length (Jiang et al., 2023) single tokens inside records a small model no — records are shortened token by token
summarise $P$ a model call writes one text $s_\ell$ that replaces $m_1, \dots, m_\ell$ old steps yes no — $s_\ell$ is new text

A placeholder keeps the record and removes only its content. Model APIs reject a tool call whose result is missing, so the result record of a call has to remain; the marker in it states that the call returned output, how much, and — where it holds a path — where the agent can read that output again with a tool. For the same reason a sliding window never places its cut between a tool call and its result.

Extraction to long-term memory removes nothing from $M_t$. It is a second write $W_L$ applied to the same step $(a_t, o_t)$: a model call derives facts from it — a preference, a name, a decision — and stores them in the long-term store (Extraction), while $m_t = W_M(a_t, o_t)$ enters $M_t$ as before. It changes what a later compaction loses: after a window or a summary has removed the step from $M_t$, the facts extracted from it return to the prompt when the long-term read $R_L$ selects them.

Restoring is a lookup only while working memory is a sub-selection. After a persist, a window or a placeholder every record in $M_t$ is verbatim, or a marker at its original position, so the lost content is recovered by reading the log. A summary is new text written by a model: it is not in the log, undoing it means reading the turns again, and any error it contains has entered $M_t$ as if it were established.

Part III — Long-Term Memory

Long-term memory consists of three modules — semantic, episodic and procedural — and each module is one choice of $W$, $P$ and $R$, as The Memory Loop states for every memory design.

Module $W_L$ — what is stored $P_L$ — how it is managed $R_L$ — how it is read
Semantic — facts facts extracted by a model call, admitted by a scope test consolidation: duplicates merged, contradictions resolved similarity to $c_{t+1}$
Episodic — experiences the steps, verbatim and dated; in Generative Agents with an importance rating by one model call reflection: insights derived from episodes, stored as new records recency · importance · relevance
Procedural — how-to skill files, by a designer; a revision only after validation versioning in stages: description first, body on a match
W: record m_tW: extract factsW: store verbatimP: reflectW: write skillR_M: wholeR_L: n most similarR_L: n most similarR_L: on a matchsession stepsworking memory M_t(this session)semanticepisodicdesignerproceduralprompt of the next call

The current session reaches the prompt through working memory, read whole by $R_M$; the three long-term stores contribute records from earlier sessions, selected by $R_L$. The edge from episodic to semantic memory is reflection in the classification of Sumers et al. (2024), who count the reflections of Generative Agents as semantic memory; Park et al. (2023) store them in the same memory stream as the observations (Reflection).

Semantic Memory

Semantic memory stores what an extractor concludes from the conversation, not the conversation. Its write $W$ is a model call that returns short facts; each fact is embedded and stored under the user's id, and the read $R_L$ is a similarity search restricted to that id (Mem0, 2026). The design has to settle which candidate facts are admitted (Extraction) and how a stored fact is replaced when a later turn contradicts it (Consolidation). Similarity is not relevance: a record about the user's favourite cuisine can outrank one about an allergy, because both concern food.

Extraction

The write is a filter: after a turn a model proposes candidate facts, and a candidate is stored only if it holds beyond the current trial — in the re-implementation of shareAI-lab (2025), each candidate carries the scope persistent or current_task, and only persistent candidates are admitted. The record is a markdown file, an embedded sentence or an instance of a schema:

Record Store Instance
one markdown file per fact, listed in an index MEMORY.md files, read through the index Claude Code's auto memory (Anthropic, 2026)
one embedded sentence per fact a vector store scoped by user_id / run_id mem0 (Mem0, 2026)
an instance of a schema — text, a triple, a profile a key–value store; a record is patched by its id LangMem (LangChain, 2026)

Relative expressions are resolved at the write. "Last week", stored verbatim and read a month later, names the wrong week, so $W$ replaces it by an absolute date and a pronoun by a name. Removing the compression stage of SimpleMem, which performs both conversions together with the extraction, lowers its F1 on LoCoMo's temporal questions from 58.62 to 25.40 (Liu et al., 2026, Table 5); the ablation removes the stage as a whole and does not measure the date conversion alone.

Consolidation

Consolidation removes what is redundant from a semantic store: once the store exceeds a size threshold, a model merges duplicate, contradictory and stale records, on a copy that is restored if the merge fails (shareAI-lab, 2025). A contradicted fact is replaced when the new fact is written, kept beside the new fact and resolved when the store is read, or marked invalid and kept:

Policy Mechanism Trade-off
replace at write time a model patches the record by id (LangMem: LangChain, 2026, How-to Guides) one current value; the old one is lost
append, resolve at read time the new record is added beside the old; dates decide when reading (Mem0, 2026) nothing is destroyed; every read must decide
invalidate the old record is marked invalid and kept (Zep: Rasmussen et al., 2025) history and a current value, at the cost of timestamps

Episodic Memory

Episodic memory keeps the record of what happened, as it happened. The steps are stored verbatim and tagged with their session and date; no model rewrites them, so the record keeps what an extractor would discard, such as a confirmation number. Many questions about episodes are predicates on their structure — the last turns of a session, the sessions of a week, the sessions with a tool call — which a relational table answers exactly and a similarity search only approximates. The memory stream of Generative Agents (Park et al., 2023) — one dated natural-language record per observation, with an importance rating that one model call assigns at the write — is such a store: it is read by a score (Scored Recall) and managed by reflection (Reflection).

Scored Recall

$R_L$ ranks by more than similarity, because the most similar record may be old or trivial. Park et al. (2023) score each record $m$ of the memory stream against the query $q = c_{t+1}$ and place the top-ranked records that fit:

$$\textit{score}(m) \;=\; \alpha_{\text{rec}}\cdot \text{recency}(m) \;+\; \alpha_{\text{imp}}\cdot \text{importance}(m) \;+\; \alpha_{\text{rel}}\cdot \text{relevance}(q, m),$$

each term min–max normalised over the candidates (smallest value $\mapsto 0$, largest $\mapsto 1$), all weights $\alpha = 1$.

Term Computed as Computed
recency $0.995^{h}$, $h$ hours of simulated time since the record was last retrieved per query, no model call
importance the model's 1–10 rating, from "purely mundane" to "extremely poignant" once, at the write
relevance cosine similarity of record and query embeddings per query

The weights are the memory policy. With $\alpha_{\text{rec}} = \alpha_{\text{imp}} = 0$ the score is plain similarity, which ranks by wording, not by how recent a fact is: for "Where does Anna live?", the outdated "lives in Berlin" outranks "moved to Hamburg".

Reflection

Reflection turns episodes into records that no single observation contains — the answer to "who would you spend an hour with?" generalises over many events. In Generative Agents (Park et al., 2023, §4.2):

  1. Trigger — the summed importance of the latest records exceeds 150, in practice two or three times per simulated day.
  2. Questions — given the 100 most recent records, the model is asked: "Given only the information above, what are 3 most salient high-level questions we can answer about the subjects in the statements?"
  3. Retrieval — for each question, records are recalled by the score of Scored Recall, earlier reflections included.
  4. Synthesis — the model is asked for "5 high-level insights", each citing its evidence: "Klaus Mueller is dedicated to his research on gentrification (because of 1, 2, 8, 15)".

Each insight is stored in the stream with pointers to the records it cites, and a reflection may cite earlier reflections, so the store grows trees of reflections: observations at the leaves, increasingly abstract insights above them, each checkable against its evidence. CoALA counts these insights as semantic memory (Sumers et al., 2024); in Generative Agents they are records of the same stream as the observations they cite.

Procedural Memory

Procedural memory is the part of the agent that decides how it acts, and in an agent built on a fixed model it is largely prompt text — a system prompt, a skill, the rules of a tool loop. It is initialised by the designer, and writing it is "significantly riskier than writing to episodic or semantic memory, as it can easily introduce bugs or allow an agent to subvert its designers' intentions" (Sumers et al., 2024, §4.1). Keeping each version under its own key makes every change an explicit, reversible write, and a revision produced from trajectories by a prompt optimiser is promoted only after a validation check (Belikova et al., 2026). Skills are the form in which such text is stored and read.

Skills as Files

A skill is procedural memory read in stages, so its prompt cost grows with the number of skills, not with their length. A skill is a directory containing a SKILL.md — YAML frontmatter with name and description, then a Markdown body — and optional scripts/, references/, assets/ (Agent Skills specification; Anthropic, 2026). The format is an open standard, published at agentskills.io. A designer writes it; the model reads it (progressive disclosure):

at startupnoyesn skills on disk1 · Discoveryname + description onlyTask matches adescription?nothing further loads2 · Activationthe full SKILL.md body3 · Executionscripts/ · references/ ·assets/

With $n$ skills, $d \approx 100$ tokens of metadata and $b \lesssim 5000$ tokens of body each, the resident cost is $n\,d$ — $4\,000$ tokens for $n = 40$ — plus $a\,b$ for $a$ activated skills, against $n\,b \approx 200\,000$ tokens for loading every body (→ L-Att). A skill supplies instructions and does not enforce them; a rule for every call belongs in a hook (→ L-Gateway). A procedure whose steps must all run, in order and verifiably — test, write release notes, wait for approval, deploy — belongs in a workflow whose steps the engine checks, and the skill is used inside one step: "The skill says how; the workflow says what, in which order, with what proof, and where I come in" (guregodevo, 2026, a practitioner's essay). (Sources: Anthropic, 2026; Sabherwal & Agarwala, 2026.)

Part IV — Memory Control

Memory control — which party computes $W$, $P$ and $R$ — is a design decision of its own (Sumers et al., 2024): the harness by fixed rules, the model by emitting memory operations as actions, or a fresh agent from a handoff.

Design $W$ $P$ $R$
compaction pipeline harness harness; the summary by a model call harness
Mem0 (Mem0, 2026) harness, add after every exchange exact-duplicate check only harness
LangMem (LangChain, 2026) model, by tool — or a background manager background manager model, by tool
MemGPT (Packer et al., 2024) model, by function call harness, at the flush model, by function call
MemLLM (Modarressi et al., 2025) model emits MEM_WRITE none needed — a triple is unique model emits MEM_READ
context reset the ending agent writes a handoff working memory is emptied the new agent reads the handoff

A rule cannot anticipate what a task will need, a model may omit its memory calls, and a handoff carries only what was written into it.

Context Reset vs. Compaction

A context reset empties working memory and starts a fresh agent from a handoff $\mathcal{H}$ written by the ending session, $M_t \leftarrow \mathcal{H}$ (Rajasekaran, 2026). The handoff is not a message but a set of files in the environment, which the new agent reads with its tools: in the harness of Young (2025), a progress file of what has been done, the git history with descriptive commit messages, a JSON feature list in which each feature carries a passes flag, and a setup script init.sh. A new session reads the progress file, the git log and the feature list, starts the application with init.sh and runs one end-to-end test, and then selects the highest-priority feature not yet passing. The test detects a defective state left by the previous session before new work depends on it.

Compaction Context reset
The history summarised in place; the same agent continues cleared; a new agent starts from $\mathcal{H}$
Costs whatever the summary dropped orchestration, tokens and latency of a second agent start; $\mathcal{H}$ must carry enough state

A reset costs a second agent start. The harness must decide when to end the running agent, launch the next one and pass it $\mathcal{H}$ — the orchestration — and the new agent spends tokens and time rebuilding its working state from $\mathcal{H}$ before it continues the task; Rajasekaran (2026) names these costs "orchestration complexity, token overhead, and latency".

A reset removes context anxiety; compaction does not remove it reliably. Context anxiety is the behaviour of a model that "begin[s] wrapping up work prematurely as [it] approach[es] what [it] believe[s] is [its] context limit", and after compaction it "can still persist" (Rajasekaran, 2026). The report states no mechanism and no measurement; it is a practitioner's report.

Evidence. Resets were essential in a harness of an initializer agent and a coding agent on Sonnet 4.5. The author removed them from a later harness, with a planner and an evaluator, on Opus 4.5, and attributes the change to the model: "Opus 4.5 largely removed that behavior on its own" (Rajasekaran, 2026). Model and harness changed together, and no run varies one of them alone.

Design rule. A reset inherited from an earlier model or an earlier harness is tested again.

A second reason for a reset is independent of context anxiety. An agent that starts from a high-level prompt and works over several successive contexts, each within the context window, with compaction alone does not finish a production-quality web application, on Opus 4.5 as well, because the summary "doesn't always pass perfectly clear instructions to the next agent" (Young, 2025); the handoff files state these instructions outside the context.

Memory Evaluation

A memory benchmark hides questions inside a long conversation history, spread over many sessions, and scores the answers — so an end-to-end score, computed on the final answer alone, says whether a memory system failed, not which operation failed.

Benchmark Setting Question types
LoCoMo (Maharana et al., 2024) 10 conversations, ~600 turns, up to 32 sessions each single-hop · multi-hop · temporal · open-domain · adversarial (unanswerable)
LongMemEval (Wu et al., 2025) 500 questions in histories of ~115 K to ~1.5 M tokens extraction · multi-session · knowledge updates · temporal · abstention

Evidence. When the context window of gpt-3.5-turbo grows from 4 K to 16 K tokens, its overall F1 on LoCoMo (partial-match F1 against the gold answer, ×100) rises from 23.9 to 35.9, while its F1 on the adversarial questions, whose correct answer is an abstention, falls from 34.8 to 14.8 (Maharana et al., 2024): the longer context contains more text that resembles an answer, and the model answers where it should abstain. With the correct records retrieved, changing only how the model reads them — a note on each record first (Chain-of-Note), or the records in a structured format — changes LongMemEval accuracy by up to 10 percentage points across three models (Wu et al., 2025).

Design rule. The score is reported per question type, because the types can move in opposite directions, and the answer is scored, not only the retrieval.

The full-history baseline — the whole history placed in the context, with no memory system — is the reference a memory system must exceed, not an upper bound: on LoCoMo, whose histories fit the window, GPT-4.1-mini with the full history reaches an average F1 of 18.70, against 43.24 for the memory system SimpleMem with the same model (Liu et al., 2026, Table 1). Chhikara et al. (2025), who exclude the adversarial questions, report the baseline highest, so the comparison depends on the question types included.

Evaluation by Operation

Stage-wise evaluation locates an error at the operation that made it, where LoCoMo and LongMemEval score only the final answer and cannot tell whether the write, the management or the read failed. HaluMem — a benchmark of hallucinations in memory systems (Chen et al., 2025) — annotates a gold standard for each operation: the memory points a dialogue should cause to be stored, the old → new pairs it should cause to be updated, and the answers:

Operation Compared Failure it isolates
write extracted records vs. gold memory points a fact never stored, or one invented
manage applied updates vs. gold old → new pairs an update omitted or applied wrongly
read + use answer vs. gold answer a wrong recall, or an unsupported answer

The failures start at the write: four of five measurable systems extract fewer than 60 % of the gold memory points, most omit more than half of the updates, and none answers more than 70 % correctly — an update cannot be applied to a fact that was never written.

⚖️ Responsible AI — Memory & Privacy

What a persistent agent stores about its users, for how long, and whether they can delete it, is decided by the three operations.

  • $W$ decides what — a scope check that admits only durable facts also excludes incidental personal detail.
  • $P$ decides how long — and a store that keeps every version for auditing retains exactly what a deletion request asks to remove.
  • $R$ does not delete — a down-ranked record is still stored.

The Memory Write as a Privileged Operation

For security the dangerous operation is $W$. In a demonstration of Greshake et al. (2023), a prompt injection — delivered "via any injection method", for example in content the agent retrieves with a tool, the paper's indirect prompt injection — makes the model call its memory tool and store part of the payload in a key-value store; the model cannot distinguish instructions from data in its context. After a session reset the agent behaves correctly until it reads its notes, when "it re-poisons itself". A reset empties working memory, not the long-term store, and a stored record is read back indistinguishable from a legitimate one — so the check belongs at the write. The same holds for a wrong generalisation written by consolidation or reflection.

In Practice / This Week's Lab

lecture-Memory-exercises.ipynb: the session log as a JSONL tree; the operations $W$, $P$ and $R$ and the forms of compaction; the memory modules and contradicted facts; scored recall by hand; the context cost of progressive disclosure; memory control and the context reset; locating a memory failure at its operation.

lecture-Memory-lab.ipynb: three tutorials on scripted models, each closed by comprehension questions — the session as a message history written to a JSONL log, compaction as a history processor, and scored recall over a memory stream.

Summary

  • The model is stateless; memory is a store managed by the runtime through write · manage · read ($W$, $P$, $R$), and long-term memory is whatever survives the end of a trial.
  • A session is an append-only JSONL log plus a bounded working memory; compaction — a write $W$ or a management step $P$ — applies the forms that keep every record recoverable first and the summary last.
  • Long-term memory is three modules, each a choice of $W$, $P$, $R$: semantic — extracted facts, consolidated; episodic — verbatim records, read by recency · importance · relevance and condensed by reflection; procedural — skills, read in stages.
  • Memory control: the harness, the model or a fresh agent (context reset) computes the three operations.
  • Evaluated per operation, memory fails first at the write — also where privacy and security checks belong.

References

Peer-reviewed papers

  • Greshake, Kai, et al. "Not what you've signed up for: Compromising Real-World LLM-Integrated Applications with Indirect Prompt Injection." Proceedings of the ACM Workshop on Artificial Intelligence and Security. 2023. arXiv:2302.12173. — an injected payload written by the agent's own memory write and read back after a session reset.
  • Jiang, Dongming, et al. "MAGMA: A Multi-Graph based Agentic Memory Architecture for AI Agents." Proceedings of the 64th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers). 2026, pp. 36848–36865. arXiv:2601.03236. — a full-context baseline on LoCoMo, adversarial questions included, below every memory system tested.
  • Jiang, Huiqiang, et al. "LLMLingua: Compressing Prompts for Accelerated Inference of Large Language Models." Proceedings of the 2023 Conference on Empirical Methods in Natural Language Processing. 2023, pp. 13358–13376. arXiv:2310.05736. — token deletion by surprisal under a small language model.
  • Lewis, Patrick, et al. "Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks." Advances in Neural Information Processing Systems. Vol. 33. 2020. arXiv:2005.11401. — parametric and non-parametric memory.
  • Liu, Jiaqi, et al. "SimpleMem: Efficient Lifelong Memory for LLM Agents." International Conference on Machine Learning. Vol. 306. 2026. arXiv:2601.02553. — a full-context baseline on LoCoMo below a memory system, and the effect of resolving relative time at the write.
  • Liu, Nelson F., et al. "Lost in the Middle: How Language Models Use Long Contexts." Transactions of the Association for Computational Linguistics, vol. 12, 2024. arXiv:2307.03172. — accuracy over the position of the relevant document, below closed-book accuracy in the middle of the context.
  • Maharana, Adyasha, et al. "Evaluating Very Long-Term Conversational Memory of LLM Agents." Proceedings of the 62nd Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers). 2024, pp. 13851–13870. arXiv:2402.17753. — LoCoMo: very long multi-session conversations, five question types, scored by partial-match F1.
  • Park, Joon Sung, et al. "Generative Agents: Interactive Simulacra of Human Behavior." Annual ACM Symposium on User Interface Software and Technology. Vol. 36. 2023. arXiv:2304.03442. — the memory stream, retrieval by recency, importance and relevance, and reflection.
  • Sabherwal, Arpit, and Subhangi Agarwala. "AI Agent Skills: Architecture, Taxonomy, and Distribution Strategies in Enterprise Ecosystems." International Research Journal of Modernization in Engineering Technology and Science, vol. 8, no. 5, 2026. ResearchGate. — the anatomy of a skill.
  • Sumers, Theodore R., et al. "Cognitive Architectures for Language Agents." Transactions on Machine Learning Research, 2024. arXiv:2309.02427. — CoALA: the four memory modules, working memory as a data structure, and the write to procedural memory as the risky one.
  • Wu, Di, et al. "LongMemEval: Benchmarking Chat Assistants on Long-Term Interactive Memory." International Conference on Learning Representations. Vol. 2025. 2025. arXiv:2410.10813. — LongMemEval: five memory abilities, and the effect of the reading strategy when the right records are retrieved.
  • Yang, John, et al. "SWE-agent: Agent-Computer Interfaces Enable Automated Software Engineering." Advances in Neural Information Processing Systems. Vol. 37. 2024. arXiv:2405.15793. — the placeholder that keeps a collapsed observation at its position.
  • Zhang, Zeyu, et al. "A Survey on the Memory Mechanism of Large Language Model-based Agents." ACM Transactions on Information Systems, vol. 43, no. 6, 2025, pp. 155:1–155:47. arXiv:2404.13501. — memory as the operations write, manage and read, defined over trials and steps (§3).

Preprints & other non-peer-reviewed papers

  • Belikova, Julia, et al. "Managing Procedural Memory in LLM Agents: Control, Adaptation, and Evaluation." arXiv preprint arXiv:2606.23127 (2026). — skills evolved from traces, and the validation-gated, versioned rewrite. ⚠ 288 of 382 benchmark tasks LLM-drafted.
  • Chen, Ding, et al. "HaluMem: Evaluating Hallucinations in Memory Systems of Agents." arXiv preprint arXiv:2511.03506 (2025). — gold standards per memory operation, and failures that begin at extraction. ⚠ The authors develop one of the evaluated systems.
  • Chhikara, Prateek, et al. "Mem0: Building Production-Ready AI Agents with Scalable Long-Term Memory." arXiv preprint arXiv:2504.19413 (2025). — cited for the mechanism only: the ADD / UPDATE / DELETE / NOOP update step (Alg. 1). ⚠ A vendor paper; its full-context baseline, scored without the adversarial questions, ranks highest, unlike later studies.
  • Cochran, Theodore O. "Single-Round Vector RAG vs an LLM-Compiled Wiki: A Preregistered Comparison on a Small Multi-Domain Research Corpus." arXiv preprint arXiv:2605.18490 (2026). — the query-token cost of an agent that reads a compiled wiki by tool, against single-round retrieval.
  • Gao, Victor, et al. "GVS5H: Zero-Shot Self-Orchestration with Ledger-Based Control Improves Coding in Language Models." arXiv preprint arXiv:2608.26480 (2026). — a context reset at every model call, with a capped file ledger as the handoff.
  • Modarressi, Ali, et al. "MemLLM: Finetuning LLMs to Use Explicit Read-Write Memory." arXiv preprint arXiv:2404.11672 (2025). — memory as MEM_WRITE / MEM_READ calls over a triple store with structural deduplication.
  • Packer, Charles, et al. "MemGPT: Towards LLMs as Operating Systems." arXiv preprint arXiv:2310.08560 (2024). — virtual context management: the 70 %/100 % thresholds, the recursive summary, and paging by function call.
  • Rasmussen, Preston, et al. "Zep: A Temporal Knowledge Graph Architecture for Agent Memory." arXiv preprint arXiv:2501.13956 (2025). — cited for the mechanism only: a contradicted fact invalidated rather than overwritten (§2.2.3). ⚠ A vendor paper.

Blogs, documentation & other web sources