---
title: "Total Recall: The Context Window as a Cache Over the Session Record"
author: "Oscar Serra · Independent Research"
date: "12 October 2026"
version: "v8.0"
---

## Abstract

Think of the colleague you trust with a long job. On Monday you tell them the server name, the one command they must never run in daytime, and the fix you already tried. On Friday they still know all three, and if a detail has slipped they look it up in their notes instead of asking you again. We would like to hand an AI agent work that runs for days in the same way.

But an agent reads only what fits in its context window, and when the window fills, something has to leave. Today a model usually writes a summary of the old part and throws the old part away. The summary becomes the only copy, and it keeps the gist while dropping exactly what a long job needs: the exact strings, the cause of a failure, the attempt that did not work, the owner's own words. The agent also often does not own its window: a provider's tool or API decides when to compact, and writes the summary itself.

Here we propose Total Recall, a design for the first stage of an agent's memory, keeping. The full session record, every turn word for word, is the ground truth, and the context window is a cache over it. Compaction never deletes: it leaves a small marker that names the evicted range, carries its exact strings and the owner's instructions word for word, and points back into the record, so any line can be read again. Whoever owns the window, the memory layer acts through the owner's own hooks, and it never compacts a copy the model does not read.

For the agent you run, this means an owner's instruction survives every compaction, a hash or a host name from three hours ago can be read back exactly, and the cost of each compaction is priced before it happens. The design is not yet built; we give the tests that will decide whether it works. If it holds, an agent could carry a week of work without ever having to ask what you already told it.

**Keywords:** AI agents, agent memory, context window, compaction, prompt caching, session transcript, agent harness.

---

## 1. Introduction

### 1.1 Friday's question

An owner and an agent spend an afternoon on a broken certificate on a web server. Early on, the owner gives three things that matter: the path where the certificates live, a commit hash that last worked, and an instruction: never restart the production database during the day. The agent tries a renewal command, which fails with an error about a rate limit, and they leave the key rotation for later. Three hours and many tool calls on, the context window is full.

The agent's harness compacts. A model reads the first two hours and writes a paragraph: "Worked on the TLS setup; fixed the certificate." The paragraph is accurate and almost useless. The path, the hash, the rate-limit error, the open key rotation and the instruction about the database are gone. Later that evening the agent proposes a database restart to clear a cache, and the owner has to say again what he said at two o'clock.

Nothing in this story needs a bad model. The model that wrote the summary did what summaries do. The failure is in the design: the only copy of the afternoon was replaced by a description of it.

### 1.2 Why a bigger window does not settle it

Context windows have grown to a million tokens, so it is tempting to say the problem is going away. Two things stand in the way. First, models do not read long inputs evenly. Detail in the middle of a long context is used less well than detail at the start or end (Liu et al., 2024), and accuracy falls as input grows even on simple tasks (Hong et al., 2025). A full window is a worse window. Second, a long-running agent fills any window. A day of tool output, file reads and logs runs to millions of tokens, and a week does not fit anywhere. So compaction stays, and the question is what it should leave behind.

### 1.3 What summaries lose

A summary keeps the shape of the work and drops its substance. Four kinds of information are lost first, because a summary is written to be short and to read well:

| Kind | Example | Why a summary drops it |
|------------|-------------------|-----------------------|
| Exact strings | a path, a hash, a host name, an error line | a summary paraphrases; the characters are what matter |
| Causes | "it failed because the cron job reset the config" | several steps collapse into "it failed" |
| Negative results | "we tried the renewal and it hit a rate limit" | summaries lean toward what worked |
| Time anchors | "the deploy at 14:32 succeeded" | times look like noise to a summarizer |

There is a fifth kind that matters more than the four: the owner's own words. An instruction, a preference or a correction given during the session is the one thing the owner expects never to repeat. In a summary it becomes "the user gave some guidance", or it vanishes.

Repeated compaction makes this worse. When each new summary is written from the previous one, detail erodes at every round. Zhang et al. (2025) name this "context collapse" and show it in agents that rewrite their own context.

### 1.4 Who holds the pen

There is a second obstacle, newer and less discussed. In many deployments the agent's runtime does not own the context window. A provider's command-line agent decides when to compact and writes the summary itself. A provider's API may clear old tool results or compact on its servers, and one of them returns the compacted state as an encrypted item the client cannot read (OpenAI, 2026). A memory layer that assumes it builds every model call will compact its own copy of the conversation while the model goes on reading the provider's version. That work changes nothing the model sees.

So a design for keeping has to say what is kept, where the ground truth lives, and how the memory layer acts when someone else holds the pen.

### 1.5 The claim

**The context window is a cache over the session record, and compaction is eviction from that cache, not rewriting of history.** The full record of the session is kept word for word and never edited; the one exception, a deletion for privacy or poisoned content, leaves a tombstone (§4.4). What leaves the window is replaced by a marker that carries the evicted range's exact strings and the owner's instructions verbatim, and points back into the record. Whoever owns the window, the memory layer acts through that owner's hooks.

The brain name of this stage, ENGRAM, is the physical trace a memory leaves in neural tissue: the change that makes later recall possible. We use it as a reminder of what the stage is for, a durable trace that outlives the moment, and not as a model to copy.

The contributions, each with the section that argues it:

1. The session record as ground truth (§4): every turn appended with its author, the owner's words stripped of the harness wrapper, and a stable address; the memory layer indexes the record and never keeps a lossy copy of its own.
2. A marker that is a pointer, not a summary (§5): what it carries word for word, what it reduces to one line with a pointer, what it leaves behind a pointer alone, and the rule that each compaction is written from the record and never from the previous marker.
3. An owner contract (§6): three owners of the window (the runtime, a provider's tool, a provider's API) and what the memory layer does in each, including never compacting a copy nobody reads.
4. A price for compaction (§7): a trigger that reads the call actually sent, and a closed-form break-even that says when an elective eviction pays under prompt caching.
5. Invariants and the tests that decide them (§4.3, §8, §10): every marker resolves; the record has no supersede and no hide, and loses content only through a tombstone.

---

## 2. Related Work

This is one of four designs for an agent's memory: keeping (J1, this paper), writing (J14), finding (J2) and learning (J5). Keeping owns what survives the context window. How things are ranked and pushed into the window belongs to finding, what becomes a long-term fact belongs to writing, and turning experience into rules belongs to learning. Each appears here in one line, with a pointer.

**MemGPT and Letta** (Packer et al., 2023) treat the context window like a computer's main memory and let the model page information in and out through function calls, with the full message history kept in a searchable "recall" store. Total Recall keeps the hierarchy and the full history. It differs on who decides: eviction is a decision of whoever owns the window (§6), so the model does not spend attention on managing its own pages, and the marker it leaves carries the exact strings a later search needs (§5.1).

**Provider context management** has made the provider an owner of the window. Anthropic's context editing clears the oldest tool results once a threshold is crossed and leaves a placeholder saying a result was removed; the caller can name tools whose results are never cleared and a minimum amount to clear, so the cache is not broken for a small gain, and the client keeps the full history because the clearing happens before the prompt reaches the model (Anthropic, 2026d). Its memory tool lets the model keep files outside the window in storage the developer controls (Anthropic, 2025a), and its server-side compaction replaces earlier turns with a summary block (Anthropic, 2026a). OpenAI's compaction returns an opaque, encrypted item that carries prior state forward (OpenAI, 2026). Clearing tool results first is the same eviction order we propose (§5.3), reached independently. The placeholder is a marker with nothing in it to search with; our marker (§5.1) is that placeholder with the exact strings added. The summaries are the narrative baseline our tests compare against (§10). An opaque item is the strongest argument for keeping the record on the runtime's side: if nobody can read what was kept, the runtime must keep its own copy of what was said (§6.4).

**Claude Code's hooks** (Anthropic, 2026b) are the levers a memory layer has when a provider's tool owns the window: an event before compaction (which can block it), an event after, a session-start event that fires after a compaction and adds text to the new context, and the path to the tool's own transcript. **claude-mem** (thedotmack, 2026) is a widely used plugin that uses these levers to capture what an agent did, compress it with a model and inject it into later sessions. We use the same levers (§6.3). We differ on what is kept: claude-mem's memory is the model-compressed observation, while ours is the record itself, with compression used only as a map that points back into it.

**Manus** (Ji, 2025) reports the lessons of a production agent: treat the file system as unlimited context, compress only in ways that can be restored (drop a page's content but keep its URL), keep the prompt prefix stable because the cache hit rate drives cost and latency, keep the context append-only, and leave failed attempts in view. Total Recall takes "restorable" from tool outputs to the whole conversation, adds the owner's words as something never to be compressed, and puts a price on moving the prefix (§7.2).

**headroom** (Headroom Labs, 2026) compresses tool outputs, logs and files before they reach the model, caches the originals, and gives the model a tool to retrieve them. It compresses only content as it enters the window, so the cached prefix is never rewritten; that avoids the one-time cost of §7.2, at the price of deciding before anyone knows whether the content will be needed again. It keeps a smaller, lossy version in the window; we remove the span and leave a pointer. The two compose. For a span likely to be read again, a compressed copy in the window can be cheaper than a pull; for a span unlikely to be read again, a pointer is. §7.2 gives the rule that chooses.

**Agentic Context Engineering** (Zhang et al., 2025) shows two failures of agents that rewrite their own context: brevity bias, where summaries drop domain detail, and context collapse, where iterative rewriting erodes detail over time. Its cure is small incremental updates. Our version of the cure is that every compaction is written from the record (§5.4). Their evolving playbook of strategies is learning, the subject of J5.

**Zep** (Rasmussen et al., 2025) keeps raw conversation "episodes" beneath the entities and facts it extracts, so every derived fact points back to its source. Total Recall applies the same layering to the context window: the raw record underneath, and everything derived (markers, maps, summaries) pointing back into it (§4). Extracting facts from the record belongs to J14.

Two older ideas frame the rest. Belady (1966) showed that the best page to evict is the one needed furthest in the future; no runtime knows that, so §5.3 uses what is cheapest to recover as the proxy. And the prompt cache now prices every edit to the prefix (Anthropic, 2026c), which turns "when to compact" from a matter of taste into arithmetic (§7.2).

To our knowledge no shipping system combines all five of our contributions, but each of them has close relatives above, and we claim the combination and the contract, not the parts.

---

## 3. The Design in One Page

![The four moves of keeping. Every turn is appended to the session record word for word; the context window holds a copy of part of it; when the window fills, an old span leaves and a small marker with its exact strings and the owner's instructions takes its place; the agent follows the marker's pointer to read the exact words back. Who owns the window decides where compaction runs (Figure 3), never what the record keeps.](images/fig-1-overview.png){width=82%}

Figure 1 shows the whole design. Four parts carry it:

- The session record. An append-only log of the session: owner messages, agent replies, tool calls and tool results, each with its author, its time and an address that never changes. It is the ground truth. Nothing edits it.
- The context window. What the model reads on this call. It is a cache: a copy of part of the record, plus markers standing in for parts that left.
- The marker. A short block that replaces an evicted range. It names the range, carries its exact strings and the owner's instructions word for word, lists decisions and open items as one line each, and points back into the record.
- The range read. It takes a marker's range and returns the exact entries, word for word. It is not a tool of its own: J2's pull (J2 §6.6) offers it as a range mode next to its search.

Around them sit three rules that keep the design honest:

1. One owner per window. The memory layer finds out who owns the window (§6) and acts only where its action changes what the model reads.
2. Priced compaction. A forced compaction happens because the window is full. An elective one happens only when its price, measured on the call actually sent, is lower than keeping the span (§7).
3. Checked invariants. Every marker resolves to entries in the record (§8); nothing leaves the record except through a tombstone (§4.4). These are checks in code, not sentences in a prompt (why a check and not text: J5 §1.2).

---

## 4. The Session Record

### 4.1 What goes in, and with whose name

Every entry in the record has an author, and the author is one of five kinds: the owner, the agent, a tool, the harness (time stamps, injected instructions, system text) or another agent. This is the most important field in the record, because every later stage depends on it. When a marker says "owner: never restart prod by day", it must be the owner's sentence. A harness that wraps the owner's message with a time stamp and a block of injected instructions, and stores the whole as "user", will later quote its own wrapper back as the owner's wish. So an owner's entry gets a second field when it is appended: the owner's words, with the wrapper stripped. One function does the stripping, once, at append time, and the field is never rewritten. Anything a later stage quotes as "the owner said" comes from this field. J2, J14 and J5 read the owner's words only from this field.

Tool results go in whole when they cannot be reproduced: the output of a command at a moment in time, a web page as it was fetched, an API's answer. Tool results that can be reproduced exactly, such as the contents of a file that is still on disk at the same version, go in as a reference with a content hash. Reading the file again is the recovery path, and the hash says whether the file has changed since.

### 4.2 Addresses that never move

Each entry gets an address made of the session and a sequence number. A range of entries is written as the session and two numbers. Addresses are assigned once, at append, and never reused or renumbered, so a pointer written today still resolves next month. Ids that sort by time are convenient, but the sequence number is what makes a range well defined.

### 4.3 Never edited, never superseded

The record is append-only. No compaction or clean-up ever edits or deletes an entry, and the record has no supersede at all: a turn that was said stays said, even after what it said stops being true. Supersede happens one stage later, in the fact files, where a judge closes a fact line and leaves it in place, struck through, with a pointer to the line that replaced it (J14 §7.3). The record entry the fact was drawn from is not touched. Which facts are closed is J14's call (J14 §7); what a default search hides, and its per-query counts, are J2's (J2 §8.1).

### 4.4 Forgetting: the tombstone

Two cases justify removing content: the owner asks to forget something about a person, or a line is shown to have been injected. J14 decides when either applies and removes the content from the fact files, leaving a tombstone there (J14 §7.7). The same content is almost always in the session record as well, because someone said it or a tool returned it. If the record kept it, the deletion would not hold: J2's text index covers the record (J2 §4.1), so the next search would find it again, and a range read would return it word for word.

So the record entry is redacted, and this is the only edit the record allows. The entry keeps its address, author and time. Its text, its owner's-words field and any tool result it holds are replaced by a tombstone that says content was removed, when, for which of the two reasons, and points to J14's receipt for the deletion. The tombstone holds no part of the content, not even a hash, because a hash of a short string such as a phone number can be confirmed by guessing. The redaction is also appended to the record as a harness entry, so the record still shows that something left, and when.

Everything derived from the entry is rebuilt from the redacted record. The text index drops the entry's rows and indexes the tombstone. Every marker whose range covers the entry is written again from the record (§5.4), which drops any exact string or owner's sentence that came from it. Where one session has two transcripts (§4.5), both are redacted. A copy the runtime cannot edit, such as a provider's opaque compacted state, is named in J14's receipt as out of reach. Addresses do not move, so every pointer into the range still resolves, now to a tombstone (§8).

### 4.5 One record, not copies

Most deployments already have a lossless record: the runtime writes a transcript of every session, and a provider's command-line tool writes its own. The memory layer should not add a third, partial copy. A copy that keeps only some kinds of entry, say the agent's replies, is worse than none, because a range read against it returns an answer that looks complete and is not. The design is therefore an index over the transcript the serving runtime already writes, with addresses that resolve into that transcript. The memory layer writes its own entries only where no transcript exists: when an API's compaction leaves nothing readable (§6.4), and for the markers and maps it derives.

Where two transcripts exist for one session (the runtime's and the provider tool's), the one the model actually read is the ground truth for what the model saw, and the runtime's is the ground truth for what the owner said. The index keeps both addresses.

---

## 5. Compaction That Leaves Pointers

### 5.1 The marker

![Two ways to free the context window. On the left, a model summarises the old span and the summary becomes the only copy; the next compaction summarises the summary. On the right, the span is already in the session record, so it leaves the window and a marker takes its place, carrying the range, the exact strings, the owner's instruction word for word, the failed attempt and the open item; the next compaction is written again from the record.](images/fig-2-compaction.png){width=80%}

A marker is a pointer with a short, fixed shape. Figure 2 sets it beside a narrative summary of the same span. A marker carries, in this order:

1. The range: the session and the first and last sequence numbers.
2. The owner's words: every instruction, preference and correction the owner gave inside the range, verbatim.
3. Exact strings: the paths, hashes, host names, identifiers, numbers, error lines and times that appear in the range, copied character for character, most-referenced first.
4. Decisions and negative results: one line each ("chose X over Y", "tried Z: failed with E"), each with the address of the entry that shows it.
5. Open items: what was started and not finished, one line each with an address.

There is no narrative in it. A sentence like "we made good progress on the setup" gives the model nothing to act on and nothing to search with, and it can be mistaken for a fact. Everything in a marker is either a quote or a line that points at a quote.

The exact strings are there for two readers. The model reads them and can often act without pulling anything: the hash is right there. And the search that later looks for the span finds it by the same strings the owner will use when he asks ("the nginx path", "that hash"). The strings are what an index can hold on to.

### 5.2 Word for word, one line, or a pointer

Each kind of content gets one treatment when its range is evicted:

| Content | Kept in the marker | Why |
|------------------|-----------|---------------------|
| Owner's instructions, preferences, corrections | word for word | the owner should never have to say them twice; a paraphrase changes what was asked |
| Exact strings (paths, hashes, hosts, errors, times) | word for word | a paraphrase of a string is a different string |
| Decisions, failed attempts, open items | one line each, with an address | the line says that it happened; the address gives how |
| Agent's reasoning and replies | pointer only | recoverable from the record when needed |
| Tool output that can be reproduced (a file on disk) | pointer and content hash | read the file again; the hash says if it changed |
| Tool output that cannot be reproduced | pointer only | the record holds it whole |
| Harness text (time stamps, injected rules) | nothing | the harness injects it again; it is not memory |

The owner's words have a budget, because in a long session they can grow. In a working session the owner writes much less than the tools do, so the budget should rarely bind; when it does, the instructions and corrections stay verbatim and the rest of the owner's text becomes a pointer. Deciding which of the owner's sentences are instructions needs a cheap judge; a sentence the judge is unsure of is kept verbatim, because the cost of keeping a sentence is a few tokens and the cost of losing an instruction is the owner's trust. The judge is one classifier of owner sentences shared by three stages: it picks the instructions here, finds corrections for J5's detector (J5 §3.1) and stamps a fact "told by the owner" in J14 (J14 §8.1). J5 owns it. Whether these corrections later become standing rules is learning, J5's stage; this stage only makes sure they survive the session.

### 5.3 What leaves first

When the window must shrink, the cheapest content to recover leaves first. In order:

1. Tool output that can be reproduced (files still on disk).
2. Tool output that cannot be reproduced but is in the record.
3. The agent's own reasoning and replies.
4. The owner's messages, except the instructions, which become part of the marker.

Never evicted: the system text, the always-loaded files, the markers themselves, and the current task's own short statement. Within each class, older content leaves before newer, since recent content is the best available guess at what will be needed next.

This order is cheapest-to-recover first, which is the practical stand-in for Belady's rule: we cannot know what will be needed furthest in the future, but we can know what costs least to get back. The same order arose independently in the provider world, where context editing clears the oldest tool results first (Anthropic, 2026d).

The selector reports what it evicted, by class, and the bytes in each class add up to the total it removed. It chooses from the window as the model will read it on the next call, after every other step that moves content out (a store for large tool output, a provider's clearing), so each class it names is a class that is still in the window.

### 5.4 Written from the record, never from the last marker

When a range that already contains a marker is evicted again, the new marker is built from the record entries the old marker pointed to, not from the old marker's text. This is the rule that stops context collapse. A summary of a summary loses detail at every round; a marker written from the record has the same detail on the hundredth compaction as on the first.

### 5.5 Merging markers

Adjacent markers merge: two markers covering consecutive ranges become one covering both, with their owner's words, exact strings and lines combined. The combined lists are capped by count, and what falls off the end is still in the record and still reachable through the merged range. Each merge is another compaction, so §5.4 applies: the merged marker is written from the record.

---

## 6. Who Owns the Window

![Three owners of the context window. When the agent's own runtime builds every model call, the memory layer compacts with pointers itself. When a provider's command-line agent decides when to compact, the memory layer acts through that tool's hooks. When a provider's API clears tool results or compacts on its servers, the memory layer keeps its own session record and puts the markers back after each compaction. In all three, the session record is the ground truth and every marker points into it.](images/fig-3-owners.png){width=62%}

### 6.1 Three owners

The owner of a context window is whoever decides, on each call, what the model reads. There are three cases, shown in Figure 3, and one agent can move between them as it switches models or tools during a day:

- The runtime owns the window. The agent's runtime assembles every call to the model API from its own state. Compaction is the runtime's to do.
- A provider's tool owns the window. The runtime drives a provider's command-line agent, which keeps its own conversation, decides when to compact, and writes the summary. The runtime sees what goes in and what comes out, but not every call the tool makes inside.
- A provider's API owns part of the window. The runtime builds the calls, but the API clears old tool results or compacts on its servers once a threshold is crossed, and returns either a readable summary or an opaque item.

The memory layer starts every session by noting which case it is in, and it re-checks when the model or tool changes. Everything else in this section follows from that one field.

### 6.2 When the runtime owns the window

This is the case §5 describes. The runtime builds markers, evicts by the order of §5.3 and places markers where the evicted range was. It also chooses when, by the price rule of §7. Nothing else is needed.

### 6.3 When a provider's tool owns the window

The runtime cannot compact a window it does not build. It acts through the tool's hooks, which current tools expose (Anthropic, 2026b):

- Before compaction. The hook makes sure the record is complete up to this moment: it appends anything the runtime has not yet recorded, reading the tool's own transcript where needed (the tool writes it in the background, so the hook waits for it to catch up or reads the stream it already has). It then builds the markers for the range the tool is about to summarise, from the record. The hook could block the compaction, but blocking a full window stalls the session, so the default is to let it run.
- After compaction. The session-start event that follows a compaction adds text to the new context. The hook adds the markers and the owner's words for the compacted range. The tool's summary stays; the markers sit beside it and give the model what the summary dropped, with pointers to get the rest.
- Every turn. Text the runtime injects at the start of each turn does reach the tool's model, so the push of relevant memory (J2's stage) works here as anywhere else.

The tool's own summary is not wasted: it is a readable account of the gist, and for many turns the gist is enough. What the markers add is the part a gist cannot hold.

### 6.4 When a provider's API owns part of the window

Here the runtime builds every call but the API may change the conversation after it is sent. Two moves cover it. First, the runtime keeps its own record of everything it sent and everything that came back. With tool-result clearing this is easy, since the client still holds the full history; after a server-side compaction the runtime's record may be the only readable copy, and when the compacted state is opaque, it is certainly the only one. Second, the runtime uses the API's own controls to protect what must stay: it names the tools whose results must never be cleared and sets the minimum amount to clear at once, so a small clearing does not break the cache for a small gain. After each compaction event, it re-sends the markers and owner's words for the compacted range, in the same place every time so the prefix stays stable.

### 6.5 Never compact a copy nobody reads

A runtime that keeps a mirror of a conversation that a provider's tool owns will see the mirror grow and will be tempted to compact it. That compaction costs time and changes nothing the model reads. The rule: in the provider-tool case the runtime does not compact its mirror at all; it writes a compaction receipt for each of the provider's compactions (§7.4) and builds markers for them (§6.3). A compaction is counted only when it changed what the model reads.

---

## 7. When to Compact, and What It Costs

### 7.1 Forced and elective

A compaction is forced when the next call would not fit the window: there is no choice about whether, only about what to evict (§5.3) and what to leave (§5.1). A compaction is elective when the window still has room but keeping a span costs more than evicting it, or when a smaller window would be read better (§1.2). Context editing that clears tool results long before the limit is elective. Elective compaction is where the price matters, because it is the one we can decline.

### 7.2 The price of moving the prefix

With prompt caching, the part of the context that did not change since the last call is read from cache at a fraction of the input price, and anything after the first changed token is written to cache again at a premium (Anthropic, 2026c; Ji, 2025). Evicting a span from the middle of the window changes everything after it. So eviction has a one-time cost (rewriting the suffix into the cache) and a running saving (no longer reading the span on every turn), minus the cost of the pulls the eviction will cause.

In J2's notation and prices (J2 §7.1), a cache read costs $r$, a cache write $w$ and an output token $g$, as multiples of the base input price. Let the span have $S$ tokens, the marker $m$ tokens, and let $A$ tokens follow the span in the window. Reading an evicted span back is a pull, which costs a full turn: it re-reads the $L$ tokens of cached context, writes the $R$ tokens it returns, and produces $o$ output tokens,

$$C_{\text{pull}} = rL + wR + g\,o .$$

If the evicted span is pulled back on a fraction $q$ of the remaining turns ($q$ as in J2 §7.3), evicting it pays after $N^*$ more turns, where

$$N^* = \frac{(m + A)(w - r)}{(S - m)\, r - q\, C_{\text{pull}}} .$$

The numerator is the one-time rewrite of everything after the span: J2 §7.4's suffix-rewrite term $\Delta C = (w - r)(L - P)$ with $P$ at the start of the span, so $L - P = m + A$, paid once here instead of on every turn. The denominator is the per-turn saving, net of expected pulls. When $q\, C_{\text{pull}} \ge (S-m)\,r$, the denominator is not positive and an elective eviction never pays: the span is read back too often, and it should stay (or be compressed in place, as headroom does).

![Turns a session must still run before an elective eviction pays, against how often the evicted span is pulled back. Prices are the published cache multiples of J2 §7.1 (write $w = 1.25$, read $r = 0.1$; dashed line: read 0.05) with output at $g = 5$; the marker is 300 tokens, $A = 100$K tokens follow the span, and a pull re-reads $L = 150$K tokens of cached context, writes $R = 2$K returned and adds 500 output tokens. Large spans pay back within tens of turns; small spans almost never do, and each curve rises without bound once pulls cost more than the span.](images/fig-4-breakeven.png){width=72%}

Figure 4 puts in the published prices. With a cache read at 0.1 and a write at 1.25, a 40K-token span pays back after about 29 turns if it is never pulled and about 39 if it is pulled on one turn in twenty; it never pays if it is pulled on more than one turn in five. A 100K-token span pays back after about 12 turns. A 10K-token span needs about 119 turns even with no pulls. Cheaper cache reads make eviction pay later, not sooner: at a read price of 0.05, the 40K span needs about 61 turns.

Three design rules follow. First, elective eviction should take large spans at once, since the rewrite cost is paid per eviction and the saving grows with the span. Many small evictions pay the rewrite many times. Second, the best candidates are spans that are large and rarely pulled, which is what §5.3's order selects. Third, the markers should sit at a stable place, so that the next eviction does not move them and pay the rewrite again.

The arithmetic leaves out one benefit: a shorter window is read better (§1.2). That benefit is real but unpriced, so we leave it to a test (§10, T7) and do not add it to the formula as a guess.

### 7.3 A trigger you can trust

Every compaction decision starts from a number: how full the window is. That number must come from the call actually sent, and from nothing else. A usage figure that sums several internal calls of one turn can be many times the window and will fire compaction far too early; a figure that misses a block of the prompt, because the counter does not recognise that block's role, will fire it too late. Both errors are easy to make and silent once made.

So the trigger reads a per-call snapshot: the blocks of the prompt, each attributed to a kind (system text, always-loaded files, tool schemas, history, markers, tool results, the new message), plus a slice for anything it could not attribute. The slices must add up, within the tokenizer's tolerance, to the input count the provider reports for that call. Unattributed content is an error that is reported, never a zero that is assumed. A snapshot that does not add up blocks elective compaction and is logged; forced compaction still runs, because the provider will reject a call that does not fit whatever our counter believes.

A guard against thrashing completes the trigger: an elective compaction does not run again until the window has grown by at least the amount the last one freed. A compaction that frees almost nothing and runs again a minute later is a sign that the trigger is reading the wrong number.

### 7.4 One compaction receipt per compaction, whoever ran it

Every compaction, by every executor (the runtime, the provider's tool, the API), writes one compaction receipt: when it started and ended, who ran it, the owner case of §6, what triggered it (forced or elective, and the snapshot it read), tokens before and after as measured on the next call, and the outcome. A decision not to compact writes a receipt too, under the series rule that a zero means zero (J5 §9.1).

The receipt holds these fields:

| Field | Meaning |
|-----------|---------------------|
| session, started, ended | which session, and when |
| executor | runtime, provider tool or provider API |
| owner case | the §6 case the session was in |
| kind | forced, elective, or a decision not to compact |
| decision | ran, declined on price, blocked on snapshot, did not run |
| snapshot | attributed slices, unattributed slice, provider-reported input count |
| tokens before / after | as measured on the call before and the call after |
| markers | ranges written, and whether each resolved |
| outcome | completed, failed (with reason), interrupted |

---

## 8. Getting It Back

The range read takes a range and returns the record's entries in it, verbatim, with their authors and times; an entry under a tombstone (§4.4) comes back as its tombstone. J2's pull tool offers this read as one of its modes, next to a search over the record (J2 §6.6). How that search ranks, when the agent should be handed something without asking, and whether the pull tool is offered at all are J2's. This stage guarantees one thing about the search: it runs over the same record the markers point into.

A marker that names entries in a store the range read cannot reach is a broken promise, and the design forbids it with a check: for every marker written, resolving its range must return at least one entry, and the exact strings it carries must appear in the entries returned. The check runs when the marker is written and again in the nightly tests.

---

## 9. Conclusions

### 9.1 In short

A long-running agent forgets in one way that matters: compaction replaces the only copy of its past with a description. Total Recall changes what compaction is. The session record is kept word for word, with authors and fixed addresses, and never edited except by a tombstone; the context window is a cache over it; compaction evicts from the cache and leaves markers that quote the owner and the exact strings and point back into the record; and each new marker is written from the record, so detail does not erode with repetition. Because the agent often does not own its window, the memory layer works through whoever does: it compacts itself where the runtime builds the calls, works through hooks where a provider's tool compacts, and keeps its own record where an API compacts out of sight. A trigger read from the call actually sent and a break-even derived from cache prices decide when an elective compaction is worth it. If this holds, the owner's Friday question about Monday's instruction does not arise, because Monday's instruction is still in the window, word for word.

### 9.2 Limitations

- Markers depend on extraction. Which strings are "exact strings" and which owner sentences are instructions are judgements made by code and a cheap judge. A missed string is still in the record, but the marker no longer advertises it, so the agent has to search to find it.
- Hooks are the provider's to change. In the provider-tool case the design relies on hooks the provider chose to expose. If a provider removes the event after compaction, the markers can only reach the model on the next turn's injection.
- Opaque compaction cannot be checked. When an API keeps its compacted state encrypted, we cannot measure what it dropped, only what the model later fails to use.
- The record grows without bound. Append-only storage grows with every session. Storage is cheap next to an owner's time, but a deployment with years of sessions will need tiered storage for old records; the design does not cover it.
- The price rule assumes a pull rate. $N^*$ needs $q$, the rate at which an evicted span is pulled back, and no one has measured it for conversation history. Until it is measured, elective eviction should be conservative.
- Recoverable is not recovered. Every guarantee here is about what can be read back. Whether the agent asks for it when it should is J2's question.

---

## 10. Next Steps

### 10.1 Tests that would settle what we do not know

Each test names the claim it decides and what result would change the design.

| # | Test | Decides | What would change the design |
|--|---------------------|-------|---------------|
| T1 | Needle survival. Seed exact strings, owner instructions, failed attempts and times early in long synthetic sessions; force 1, 3 and 5 compactions; ask for each. Arms: the provider's own summary, truncation, pointer compaction, pointer compaction with markers but no range read. | §5: markers and the range read keep what summaries lose | If markers without the range read already match markers with it, the read matters less than the marker; if the provider summary matches pointers, §1.3's premise is wrong for that provider |
| T2 | Back-reference replay. Collect real moments where an owner refers to earlier in the session ("the hash from before", "what I told you"). Replay them after compaction and score whether the agent answers from the record. | §4, §5 in real use | If range reads from the record do not beat the summary by a clear margin, the record's cost is not paid back |
| T3 | Forget-cue rate. Count owner messages that repeat an earlier instruction or ask "did you forget", per 100 owner messages, split by whether a compaction happened in the previous ten turns. | the outcome the whole design serves | No difference across compactions means the owner's memory pain lies elsewhere (in finding or learning), and §1's motivation must be rewritten |
| T4 | Marker coverage. For each evicted range, the share of its exact strings and owner instructions present in its marker; then rerun T1 with search over markers only. | §5.1, §5.2 | Coverage below half means the extraction, not the design, is the weak part |
| T5 | Every marker resolves. Property test over generated sessions plus the nightly check of §8: every marker's range returns entries and contains its strings. | §8 | Any failure is a defect to fix, not a trade-off |
| T6 | Trigger validity. For each call, attributed slices plus the unattributed slice against the provider's reported input count; evicted bytes by class against the total removed; a session that thrashes must trip the guard; a provider-tool session must show zero runtime compactions. | §5.3, §6.5, §7.3 | A snapshot that cannot be reconciled means the trigger cannot be trusted, and elective compaction stays off |
| T7 | Price and quality. Measure price-weighted tokens per resident turn and per pull, and $q$ for evicted conversation; compare elective eviction at $N^*$ with no elective eviction on task success. | §7.2 | A measured $q$ above the break-even for typical spans means elective eviction should be rare; a quality gain from shorter windows would argue for earlier eviction than price alone |
| T8 | Forgetting reaches the record. Seed a string in an owner turn and in a tool result, compact over both, then run a J14 deletion for it. Search J2's text index, range-read the span and resolve every marker that covered it. | §4.4 | Any hit, or any marker that no longer resolves, is a defect |

T3 is the measure the design should be judged by: if keeping works, the owner repeats himself less.

### 10.2 Building it

Total Recall will be built in TinkerClaw in the order the tests need it: the record index and its addresses first, then the marker builder and the resolve check, then the owner contract for the provider-tool case, the tombstone with J14's deletion, the trigger snapshot and the compaction receipt, and the price rule last, once T7 has measured $q$. An updated version of this paper will report the results.

---

## References

- Anthropic (2025a). Managing context on the Claude Developer Platform (context editing and the memory tool). 29 September 2025. <https://claude.com/blog/context-management>
- Anthropic (2026a). Compaction. Claude Platform documentation. <https://platform.claude.com/docs/en/build-with-claude/compaction>
- Anthropic (2026b). Hooks reference. Claude Code documentation. <https://code.claude.com/docs/en/hooks>
- Anthropic (2026c). Prompt caching. Claude Platform documentation. <https://platform.claude.com/docs/en/build-with-claude/prompt-caching>
- Anthropic (2026d). Context editing. Claude Platform documentation. <https://platform.claude.com/docs/en/build-with-claude/context-editing>
- Belady, L. A. (1966). A study of replacement algorithms for a virtual-storage computer. *IBM Systems Journal*, 5(2), 78–101. <https://doi.org/10.1147/sj.52.0078>
- Headroom Labs (2026). headroom: compress tool outputs, logs, files and RAG chunks before they reach the LLM. GitHub, Apache-2.0. <https://github.com/headroomlabs-ai/headroom>
- Hong, K., Troynikov, A., & Huber, J. (2025). Context rot: how increasing input tokens impacts LLM performance. Chroma technical report. <https://research.trychroma.com/context-rot>
- Ji, Y. (2025). Context engineering for AI agents: lessons from building Manus. 18 July 2025. <https://manus.im/blog/Context-Engineering-for-AI-Agents-Lessons-from-Building-Manus>
- Liu, N. F., Lin, K., Hewitt, J., Paranjape, A., Bevilacqua, M., Petroni, F., & Liang, P. (2024). Lost in the middle: how language models use long contexts. *Transactions of the ACL*, 12, 157–173. <https://arxiv.org/abs/2307.03172>
- OpenAI (2026). Compaction. OpenAI API documentation. <https://developers.openai.com/api/docs/guides/compaction>
- Packer, C., Wooders, S., Lin, K., Fang, V., Patil, S. G., Stoica, I., & Gonzalez, J. E. (2023). MemGPT: towards LLMs as operating systems. arXiv:2310.08560. <https://arxiv.org/abs/2310.08560>
- Rasmussen, P., Paliychuk, P., Beauvais, T., Ryan, J., & Chalef, D. (2025). Zep: a temporal knowledge graph architecture for agent memory. arXiv:2501.13956. <https://arxiv.org/abs/2501.13956>
- thedotmack (2026). claude-mem: persistent context across sessions for every agent. GitHub. <https://github.com/thedotmack/claude-mem>
- Zhang, Q., Hu, C., Upasani, S., Ma, B., et al. (2025). Agentic context engineering: evolving contexts for self-improving language models. arXiv:2510.04618. <https://arxiv.org/abs/2510.04618>

---

## Appendix A. The Loop in Pseudocode

### A.1 Appending to the record

```
APPEND(session, entry):
  entry.seq    <- next_sequence(session)   # once, never reused
  entry.author <- owner | agent | tool | harness | other_agent
  if entry.author == owner:
      entry.words <- strip_wrapper(entry.text)  # once; J2, J5, J14 read only this
  if entry.kind == tool_result and reproducible(entry):
      entry.content <- reference(path, content_hash)
  record.append(session, entry)            # no update, no supersede
  index.add(session, entry.seq, entry)     # derived, rebuildable

TOMBSTONE(session, seq, reason, receipt):  # only for a J14 deletion
  record.redact(session, seq, removed(reason, now, receipt))  # the one edit
  record.append(session, harness("redacted", seq, reason))
  index.reindex(session, seq)
  rebuild_from_record(markers_covering(session, seq))         # as in 5.4
```

### A.2 Building a marker and evicting

```
COMPACT(window, session, forced):
  snap <- snapshot(last_call_sent)   # per call, attributed
  if not snap.reconciles and not forced:
      receipt(decision = "blocked: snapshot"); return
  span <- choose_span(window, order = [reproducible_tool, tool, agent, owner_rest])
  if not forced and not pays(span, snap):
      receipt(decision = "declined: price"); return
  entries <- record.read(session, span.first, span.last)  # never old markers
  marker <- {
      range:   (session, span.first, span.last),
      owner:   verbatim(instructions(entries), budget),
      strings: exact_strings(entries, cap),
      lines:   decisions_and_failures(entries) + addresses,
      open:    open_items(entries) + addresses }
  assert resolves(marker)            # the check of 8
  window.replace(span, marker, at = stable_position)
  receipt(executor = "runtime", owner_case, snap, before, after, outcome)
```

### A.3 Acting by owner case

```
ON_SESSION_START(session):
  note_owner_case(session, detect_owner(session))  # runtime | provider_tool | provider_api

ON_PRE_COMPACT(session):         # provider_tool case
  flush_record(session)          # catch up with its transcript
  pending <- build_markers(session, range_to_compact)

ON_SESSION_START_AFTER_COMPACT(session):   # provider_tool
  add_context(pending)           # beside the tool's summary
  receipt(executor = "provider_tool", ...)

ON_API_COMPACTION(session):      # provider_api case
  resend(markers_for(compacted_range), at = stable_position)  # from our own record
  receipt(executor = "provider_api", ...)

# never: compact the runtime's mirror of a provider_tool session
```

---

_J-series paper J1 | Version 8.0 | 2026-10-12_
