Sub topic 11
Memory and Notes Outside the Window
What this chapter assumes
You should have read the chapters on the token budget, retrieval and just-in-time loading, and compaction. You should be comfortable reading short Python programs. This chapter covers what to do with information that must outlive a single context window, or that does not deserve a permanent place in one.
Why move information out of the window
A context window is working memory. It is rebuilt on every call, it has a fixed size, and everything in it costs tokens. Two situations push you toward storage outside the window:
- The task outlasts the window. A long coding or research session produces more facts than fit. Compaction shrinks history, but a summary is lossy, and each round of summarizing can drop details you later need.
- The facts outlast the session. A user's preferences, a project's conventions, or a decision made last week should not have to be rediscovered. When the session ends, the window is gone.
External memory is anything the model can write to and read from that is not part of the prompt by default. The window stays small, and the storage holds the long tail. This is the same idea as just-in-time retrieval, with one difference: in retrieval you load data that already existed somewhere. In memory, the model or your code creates the data during the run and decides what to keep.
Kinds of external memory
Different jobs need different stores. Picking the wrong one is the most common design mistake.
| Kind | What it holds | Lifetime | Typical format |
|---|---|---|---|
| Scratchpad | Intermediate reasoning, partial results | One task | Text file or in-memory string |
| Progress file | Task list, what is done, what is next | One long task, across window resets | Markdown checklist or JSON |
| Fact notes | Decisions, discovered values, user preferences | Many sessions | JSON records with source and date |
| Searchable archive | Past conversations, large documents | Indefinite | Index queried by keyword or embedding |
A scratchpad and a progress file are read almost in full, because they are small and always relevant to the current task. Fact notes and archives are large, so you read only the entries that match the current step.
The write and read loop
The model does not remember anything between calls. Memory works because your code writes entries to storage during a run and reads a selection of them back into the next context.
Every step in that loop is a decision you control: what to write, how to index it, how much to read back, and when to read.
A minimal note store
The following program implements fact notes in a JSON file. It records the source and time of each note, supports replacing an outdated note, searches by word overlap, and renders results within a token limit. A real system would likely use embeddings for search, but the structure stays the same.
import json
import tempfile
import time
from pathlib import Path
def estimate_tokens(text):
# Rough heuristic: about 4 characters per token for English text.
return max(1, len(text) // 4)
class NoteStore:
def __init__(self, path):
self.path = Path(path)
if self.path.exists():
self.notes = json.loads(self.path.read_text())
else:
self.notes = []
def _save(self):
self.path.write_text(json.dumps(self.notes, indent=2))
def add(self, topic, text, source, replaces=None):
new_id = max((n["id"] for n in self.notes), default=0) + 1
if replaces is not None:
for n in self.notes:
if n["id"] == replaces:
n["superseded_by"] = new_id
self.notes.append({
"id": new_id,
"topic": topic,
"text": text,
"source": source,
"saved_at": time.time(),
"superseded_by": None,
})
self._save()
return new_id
def search(self, query, limit=5):
words = set(query.lower().split())
scored = []
for n in self.notes:
if n["superseded_by"] is not None:
continue # never show outdated notes
haystack = set((n["topic"] + " " + n["text"]).lower().split())
score = len(words & haystack)
if score > 0:
scored.append((score, n["saved_at"], n))
scored.sort(key=lambda s: (s[0], s[1]), reverse=True)
return [n for _, _, n in scored[:limit]]
def render(notes, budget):
lines, used = [], 0
for n in notes:
line = "- [#%d %s] %s (source: %s)" % (n["id"], n["topic"], n["text"], n["source"])
cost = estimate_tokens(line)
if used + cost > budget:
break
lines.append(line)
used += cost
return "\n".join(lines)
if __name__ == "__main__":
with tempfile.TemporaryDirectory() as tmp:
store = NoteStore(Path(tmp) / "notes.json")
first = store.add("database", "staging database listens on port 5433", "config/staging.yaml")
store.add("database", "staging database listens on port 5434", "deploy log", replaces=first)
store.add("testing", "use pytest, not unittest", "user request")
print(render(store.search("database port"), budget=200))Running it prints one line:
- [#2 database] staging database listens on port 5434 (source: deploy log)The first note is kept in the file but marked as superseded, so it is never loaded. The testing note does not match the query, so it stays out of the context.
What to write down
Notes are cheap to write and expensive to read back if they are vague. Good notes share a few properties:
- Self-contained. The note must make sense to a model that has none of the original conversation. "Fixed it like before" is useless. "Login timeout was caused by a 30 second proxy limit; raised to 120 in nginx.conf" is useful.
- Sourced. Record where the fact came from: a file path, a tool call, or "user said". Source lets a later step judge trust and recheck.
- Dated. A timestamp lets you prefer newer notes and expire old ones.
- Small. One fact per note. Large notes are loaded whole, so they spend budget on content that only partly matches.
- Decisions with reasons. A decision without its reason gets reversed by a later step that cannot see why it was made.
Do not write down what is cheap to recompute. A file's contents can be read again, so a note should hold its path and the one fact you extracted from it, not a copy.
Who decides to write
You have two options, and they trade control for flexibility.
- Code decides. Your program saves specific things automatically: every user preference, every failed command, every final answer. This is predictable and easy to test, but it saves noise.
- The model decides. You give the model a
save_notetool and instructions on when to use it. The notes are higher value, but the model may forget to write, or may write too much.
Many systems combine both. Code saves a progress file at each step, and the model saves notes about decisions.
Reading memory back
Loading everything defeats the purpose. Apply the same selection rules as for any retrieved data.
- Always load the small stable part. A progress file or a short list of user preferences is cheap and applies to every step. Place it near the start of the dynamic part of the prompt, after the stable prefix.
- Search for the rest. Use the current question or step as the query. Cap the result count and the token total, as
renderdoes above. - Load at the start of a session and on demand. At session start, read the progress file so the model knows where it stopped. During the session, expose a
search_notestool so the model can look things up when it notices a gap. - Show the identifiers. Including
#2in the rendered note lets the model refer to a note when it wants to correct or replace it.
Notes that you load into the context are now ordinary context. They cost tokens and can distract the model, so everything in the chapters on selection and failures still applies to them.
Failure modes
External memory adds new ways for context to go wrong.
- Stale notes. A fact was true last week and is false now. The superseded flag, timestamps, and a habit of rechecking cheap facts reduce this.
- Poisoned notes. If the model writes a wrong conclusion into memory, every later session loads it as trusted fact. Record the source, and treat notes derived only from the model's own reasoning as weaker than notes copied from a tool result.
- Clashing notes. Two notes disagree and both load. Replacing instead of appending, as
add(..., replaces=...)does, prevents most of this. - Unbounded growth. A store that only grows eventually makes search noisy. Periodically merge duplicates and delete notes that no step has loaded in a long time.
- Untrusted content in notes. If a note stores text copied from a web page or file, that text may contain instructions. Load it as data, label it with its source, and do not let it change the system rules.
Memory compared with compaction
Compaction and external memory both handle information that no longer fits. They differ in what happens to the detail.
| Row | Compaction | External memory |
|---|---|---|
| Where the information goes | Into a shorter summary inside the window | Into storage outside the window |
| Detail after the step | Lost unless the summary kept it | Kept in full |
| Cost to use later | Already in context | Needs a search and a read |
| Best for | The thread of a conversation | Discrete facts and decisions |
They work well together. Compact the conversational flow, and write the facts that must survive exactly into notes before you compact. Doing the notes first matters, because after the summary replaces the messages, the original wording is gone.
When memory is not the answer
If the information is needed on every call, it belongs in the system prompt, not in a store you must search. If it is large reference material that never changes, use retrieval over an index. If one step needs a lot of working material that the rest of the task does not, a subagent with its own window may be better than notes. Memory suits information that is created during the work, is needed later, and is needed only sometimes.
Exercise
An agent works on a migration over several hours and its window is compacted three times. After the third compaction it re-asks the user which database version to target, a decision made in the first hour. What went wrong, and which two changes would fix it?
Show answer
The decision existed only in the early conversation, so repeated summaries dropped it. First, write the decision and its reason as a sourced note (or in a progress file) when it is made, before any compaction. Second, load the progress file and search the notes at the start of each new window, so the decision is back in context without depending on the summary.
Exercise
In the NoteStore above, a user changes a preference from "use tabs" to "use spaces". Why is calling add with replaces better than adding a second note, and what could still go wrong with a search that scores by word overlap?
Show answer
Replacing marks the old note as superseded, so search skips it and the model never sees two clashing instructions. Word overlap can still miss a relevant note that uses different words (for example "indentation" instead of "tabs"), so the current preference might not be found. Using embeddings, or always loading a short fixed list of preferences, covers that gap.