Context engineering: window budgets, caching, compaction, memory files, subagents

What the model sees on each call of an agent, and how to choose it: the window as a budget, assembly order and the prompt-cache bill, tool outputs, compaction, memory files and skills, subagents, notes and memory layers that outlive a session, and how recall decays as the window fills. Every lever pulled on purpose in 31 recorded Claude Code sessions, 119 needle-test calls and a twelve-session memory-layer experiment (Mem0, Graphiti, Letta). A child of Topic: agentic-harnesses. Recorded 6 October 2026; data as of November 2026. Reading: 40 min, plus 26 in closed details.

Context engineering in one picture

A model reads nothing between calls: on every step of an agent the harness rebuilds the whole request, so context engineering is choosing what goes into that one request, in what order, and what stays outside it, so that it fits, stays cacheable, and holds what the next step needs.

Fig. 1 lays the request out as a tray of layers in the order it is sent, stable parts first and the growing history after them, against the 200,000-token window of Claude Haiku 4.5, to scale (a layer under about 1,200 tokens is drawn longer so it shows). Sizes from /context and the per-call usage of recorded Claude Code sessions with six tools; the section that owns each lever is named in its step.

  1. Startup context, before you type. Tool definitions (6,300 tokens) and the system prompt (6,300) come first; the project's CLAUDE.md is read from disk and loaded into every session (45 tokens here). Stable parts first is what makes the rest cacheable (sections 2 and 5).
  2. The history grows at the end, call by call. Every call appends the model's reply and the tool result it triggered: the 15 calls of the running example grew the request from 13,545 to 18,986 tokens. The newest message is last, the only place for anything volatile (sections 1 and 3).
  3. The cached prefix is read, not recomputed. On that last call 18,277 tokens came back from the prompt cache at a tenth of the input price, 699 were written and 10 were fresh: everything up to the previous call is an exact prefix of this one (section 2).
  4. One turn of big reads fills the window. Five 75 KB logs read in one turn added 112,953 tokens, and /context then said 130.7k of 200k. The budget is checked between calls, so a single turn can overshoot it (section 1).
  5. Compaction swaps the history for a summary. In a separate run of the same task with automatic compaction, 127,242 tokens were summarised into 1,971 by one extra model call, and the next call held 15,760: the startup prefix, the summary and a little new history (section 4).
  6. Everything else lives outside the window. A subagent reads in its own window (43,503 tokens at its end) and hands back one short result, leaving its parent at 16,351; notes on disk and a memory layer keep state across compactions and sessions and are read back on demand (sections 6 to 8).
LeverWhat it doesMeasured hereWhat it costs or risks
Order for the cache (2)Stable content first, so the provider reuses its work on the repeated prefixA timestamp moved from the user message into the system prompt made a call cost 3.1x more on the input side MEASUREDNothing if done from the start; one volatile byte early undoes it
Shape tool output (3)Filter, clip, page, summarise or clear what tools returnA 491 KB log: about 228,000 tokens raw (over Haiku's 200K window), 148 filtered MEASUREDClipping can cut the one line that mattered
Compaction (4)Replaces the conversation with a model-written summary18,968 to 2,258 tokens in 23 s; 127,242 to 1,971 automatically MEASUREDLossy: exact tool outputs went, and two of three summaries listed a next step nobody asked for
Memory files and skills (5)Instructions loaded on every call (CLAUDE.md) or only when needed (skills)The same 3,834-byte text: about 1,000 tokens as CLAUDE.md, about 40 as a skill description until used MEASUREDA skill that is never invoked never helps
Subagents (6)A second loop with its own window does the reading; the parent gets a summaryParent window 16,409 tokens instead of 64,533 on the same question MEASUREDTwo to three times the tokens processed in total
Notes and memory layers (7, 8)State outside the window: progress files, memory directories, fact stores, temporal graphsCLAUDE.md content survived every compaction; the best memory layer answered 24 of 25 questions, pasting the history 23 MEASUREDSomeone must write and keep them true; a write or read policy can silently lose facts

You need: the agent loop (a model call, tool calls, results appended, repeat), built from scratch on Building a harness; this page starts where that loop sends its request. The parent's section 3 and Trace and context lab measure the startup context, the caching bill and a budget model on 22 recorded runs; they are linked here, not rebuilt.

Context window: the most tokens one request may hold, prompt and reply together.
Startup context: what the harness sends before you type (tools, system prompt, memory files).
Prompt cache: the provider's store of an already-computed prompt prefix, reused at a tenth of the price.
Cache breakpoint: a marked block where a cache entry is written.
Compaction: replacing the history with a model-written summary and restarting from it.
Progressive disclosure: a short description always loaded, the body only when used (skills).
Subagent: a second agent loop with its own fresh window; only its final text returns.
Memory layer: a store outside the window with a write policy and a read policy.
Context rot: recall falling as the window fills, long before it is full.
The running example
The same tiny Python library as the parent page, textstats, with two planted bugs and the task "The tests in this repository fail. Find out why and fix the code so they pass. Do not edit the tests." Some runs add five 75 KB log files, a 30-module service package, a skill or a CLAUDE.md. Every run is Claude Code 2.1.290 headless (claude -p) on a Claude subscription, recorded on 6 October 2026, redacted, kept in src/recordings/. Dollar figures are the CLI's total_cost_usd: what the tokens would cost at Anthropic's list prices, not what the subscription paid.

1. The window is a budget

Models read and write tokens, about four characters of English prose each and fewer for code and logs. The window is 200,000 tokens for Claude Haiku 4.5 and 1,000,000 for Sonnet 5.5 as Claude Code configures them (model configuration, read 5 Oct 2026). A request that does not fit is refused: "Prompt is too long" came back when this page sent Haiku a 491 KB log in one piece MEASURED.

Four numbers make the budget: the startup context S, the growth per call g (the model's last reply plus the tool result it triggered), a reply reserve (Claude Code reports a 32,000-token output cap for Haiku 4.5), and a buffer before the harness acts. Claude Code's /context prints the window by category without calling the model. In a fresh session with six tools it reported 12.6k tokens, 6.3k of system prompt and 6.3k of tool definitions; the first real call read 13,320, so its figures are estimates within about 6% MEASURED (the parent's lab measured 13,242 on 2.1.289). With the auto-compact window set to 100K, a 33k "Autocompact buffer", a third of the window, was held free MEASURED.

Predict, then reveal. A session read five log files of 75 KB each in one turn (five parallel Read calls). The window is 200K. Did the next call fit?
Yes: the next call held 126,544 tokens, 112,953 of them new, and at the end /context said 130.7k of 200k MEASURED. A sixth file would have taken it near the limit in one step: harnesses check the budget between calls, and one turn of parallel tool calls can add more than the whole buffer.

Startup costs little; one turn of big reads fills two thirds of the window

2. Assembly order decides the cache bill

Call 12 of an agent is call 11 plus one reply and one tool result. To read a prompt the model computes a key and a value vector per token per layer (the KV cache; how big it is per model is Long context's subject), and those vectors depend only on the tokens before them. A prompt cache keeps the computed prefix, keyed by a hash of its content, and a later request that starts with exactly the same tokens reads it back instead of recomputing. Two consequences, both about order: a match must be exact from the first token, so one changed byte early invalidates everything after it; and whatever changes most often must come last.

  1. One request, in prefix order. In the static run the request held 13,320 tokens: the tools and the fixed part of the system prompt (8,344), the rest of the system prompt (3,855), the first user message (1,111), and 10 fresh. A cache match runs from the first token and stops at the first difference.
  2. Nothing volatile: from the second call, everything is read. The first call found 8,344 tokens already cached by earlier sessions on the account (the tools and the fixed part of the system prompt) and wrote 4,966; the second and third read all 13,310 tokens from cache, about $0.0013 each.
  3. A timestamp in the system prompt. Every call matches only up to the timestamp, so each one reads 8,344 and rewrites the same 4,973 tokens at the 1-hour price: about 8x the static input cost, on every call.
  4. The same timestamp in the newest user message. Only the last 1,124 tokens are rewritten and 12,199 are read: moving one line from the system prompt into the user message made each call 3.1x cheaper.
  5. One tool fewer. Dropping one tool (Glob) changed the very first block. That session's first call found nothing cached and wrote 13,056 tokens, the most of any run: tools come first, so nothing after them matched. Its second call read them all.
The eleven calls as bars, with their input-side cost

One volatile line, three places: in the system prompt it rewrites 4,973 tokens on every call

cache read (0.1x)cache write, 1 hour (2x)fresh input (1x)
Eleven one-call Claude Code sessions (Haiku 4.5, six tools, "Reply with the single word OK."), a few seconds apart; only where a per-run value sits changes. Bar: the call's input tokens as the API split them; right: input-side cost at Haiku 4.5 list prices. Recorded 6 Oct 2026.

The same rule at production scale. Cloudflare's AI code reviewer gave every review the same long system prompt followed by review-specific text, with one breakpoint after both, so each review's first request missed. Splitting the prompt at a marker so the shared part got its own breakpoint raised the first-request cache hit rate from 14 to 26% to 91 to 99.5%; cache writes had been 43% of spend, and with this and other changes the cost per review fell from $2.43 to $0.77, 68% (Cloudflare, 19 Oct 2026; the company's own figures). Whatever many requests share needs a breakpoint of its own, placed before the first byte that differs.

A cache saves the recompute; a server-held thread also saves the resend. With caching alone the client still sends the whole conversation on every call. The Claude API's message threads keep it on the server: the first request sends everything and starts a thread, later requests send only the new messages plus the previous response's ID, and the server holds the thread in memory and drops it 5 minutes after the last request (the client then sends everything again). Token usage does not change, because the model still reads the whole conversation; what falls is request size and time to first token, which matters most on very long sessions. The API stops being purely stateless, for five minutes at a time.

Message threads, as read 16 November 2026

Public beta from 2 November 2026, enabled with a thread parameter; the thread is held encrypted, in memory only, never on disk. Anthropic reports median time to first token about 35% lower for 500K to 1M-token requests, measured on Claude Code, where threads are on by default (vendor-reported). Available on the Claude Platform, on AWS, in Microsoft Foundry and on Google Cloud (Anthropic).

Anthropic's rules, which Claude Code inherits

Minimum lengths, timing and scope, usage fields, and other providers

A prefix shorter than the model's minimum is silently not cached: 4,096 tokens for Haiku 4.5 (and Opus 4.6 and 4.5), 1,024 for Sonnet 4.5, 4.6 and 5, 512 for Sonnet 5.5 and Opus 5.5. An entry can be read only after the response that wrote it has started, so parallel requests sent at once all pay to write; caches are never shared between organisations, and on the Claude API not between workspaces DOCUMENTED. Usage fields: cache_read_input_tokens, cache_creation_input_tokens, and input_tokens, which counts only what comes after the last breakpoint. Source: prompt caching and pricing, read 5 and 6 Oct 2026.

OpenAI caches automatically from 1,024 tokens; for GPT-5.6 and later it bills reads at 0.1x and writes at 1.25x and keeps entries at least 30 minutes after last use, and a prompt_cache_key helps route related requests to the same cache on earlier models (OpenAI prompt caching, read 6 Oct 2026). Gemini caches implicitly on 2.5 and newer models with "no cost saving guarantee", and offers explicit caches with a default one-hour lifetime billed for storage time; minimums are 4,096 tokens on the 3.x models and 2,048 on 2.5 (Gemini caching, read 6 Oct 2026; its discount rate not checked here). Local servers do the same in memory: mlx_lm.server keeps a prompt cache bounded by --prompt-cache-bytes.

The rules, simulated. The simulator applies them block by block to a session you configure: a request is a row of blocks in the order tools, system, messages; an entry is written at each breakpoint and keyed on the exact prefix; a read looks back at most 20 positions; prefixes below the minimum are not cached; entries expire. Predict before you press a preset: with 25 blocks per turn and one automatic breakpoint, what share of input is read from cache by call 12?

What the presets show: one growing text block (the parent's Loop lab resent the transcript as one block) never matches past the system prompt, so it is written in full at 2x every call and nothing is read (one block per message, in order, fixes it); 25 blocks per turn falls outside the 20-position lookback, so nothing is read (a breakpoint at the start of each turn fixes it); pauses longer than the lifetime rewrite everything, so the 1-hour lifetime wins once a session pauses.

Check: the simulator against the eleven recorded calls

With the block sizes measured in the static run (tools plus the fixed system prompt 8,344 tokens, already cached by other sessions; the rest of the system prompt 3,855; the first user message 1,111, plus a 13-token timestamp when present) the rules give these reads. This reproduces the recordings by construction for the static run (its sizes are the inputs) and independently for the other three.

read from cachewritten to cachefresh inputblock with a breakpointblock holding the volatile value
The request on the current call, one box per block (width grows with size, capped):
Bars: tokens per call split into read, written and fresh (left axis). Lines: cumulative cost with caching (solid) and without (dashed), right axis. A model of the documented rules, not of Anthropic's servers; not modelled: the delay before a new entry is readable, thinking blocks, images, tool-choice changes.
Rules that follow
Stable content first, volatile last; no timestamp, request id or random order in the system prompt or tool list; append only, never edit earlier messages; a fixed tool set for the whole session (Manus's "mask, don't remove": keep every tool defined and constrain which may be chosen, 18 Jul 2025); and when the prefix must change, change it once, together with compaction, so the rewrite is paid once. Claude Code 2.1.290's --system-prompt-snapshot on (the default) resends the first system prompt verbatim "until the conversation is compacted" (claude --help).

3. Tool outputs: clip, filter, page, summarise, clear

The system prompt is fixed and a few thousand tokens; tool results are unbounded, arrive every call, and stay in the history, re-read on every later call, until something removes them. A tool-output policy decides what of a result the model sees now and what it sees of it later. The parent's Trace and context lab planted a 491 KB ci.log: 6,005 lines of heartbeat noise with five relevant lines at 3,101 to 3,105. Each policy below was applied to it by a script and the result's size counted by Claude Haiku 4.5 (one call each, tools off, minus the 529 tokens of an empty prompt).

  • Raw: about 228,000 Haiku tokens; the CLI refused it ("Prompt is too long ... ~228537 tokens (limit 200000)"). The same bytes are 304,996 tokens to Sonnet 5.5, whose tokenizer splits this log into a third more pieces: a token budget depends on the model MEASURED.
  • Claude Code's own caps DOCUMENTED: a successful shell command over about 30,000 characters reaches the model as a file path plus the first 2,000 characters; a failing one as a head-and-tail excerpt of about 10,000; an over-limit Read returns a first page marked "PARTIAL view" (tools reference, read 6 Oct 2026). Here they cost 972 and 4,675 tokens and both miss the lines in the middle: safety nets that say where the rest is, so the model searches next (as Haiku and Sonnet did in the parent's recordings).
  • Head and tail, 15 lines (the Loop lab's naive clip): 1,139 tokens, misses them. Paging at 2,000 numbered lines: 80,295 tokens per page, the lines on page 2; paging bounds a result, it finds nothing.
  • Filtering heartbeat lines out: 148 tokens with all five lines and a count of what was dropped. Someone must know the filter: the model writes it (grep) or the tool's author builds it in.
  • Summarising with one Sonnet 5.5 call: a 471-token summary that kept the five lines verbatim because it was asked to, at a cost of 304,996 tokens read and $1.23 at list price (the CLI wrote the prompt to the 1-hour cache, for nothing) MEASURED: the only policy that costs more than the raw output.
  • Clearing after use (masking): a 27-token stub on every later call; right once the model has acted on a result, useless as the first view.

Only filtering and summarising keep the five lines; filtering costs 148 tokens, summarising read 304,996

Log scale, 27 to 227,987 tokens. Filled dot: all five relevant lines are in what the model sees; hollow: none are. Measured 6 Oct 2026; src/tool_policies.py, data src/inputs/policies.json.

Masking beats summarising as a default. On SWE-bench Verified with SWE-agent, keeping the last 10 turns' observations and replacing older ones with a placeholder roughly halved cost against an unmanaged context and matched or beat LLM summarisation's solve rate in four of five model settings (Qwen3-Coder 480B: 54.8% at $0.61 per instance masked, 53.8% at $0.64 summarised, 53.4% at $1.29 unmanaged) (Lindenbauer et al., arXiv 2508.21433, 29 Aug 2025; the four-of-five count from the JetBrains blog post, Dec 2025). Anthropic's API does it server-side: context editing's clear_tool_uses_20250919 strategy, once the prompt passes a trigger (100,000 input tokens by default), replaces the oldest tool results with a placeholder, keeps the most recent 3 tool uses, can exclude tools, and has clear_at_least because every clearing invalidates the cache and should free enough to be worth the rewrite (context editing, read 6 Oct 2026). Claude Code clears older tool outputs first when the window fills, before it compacts (how Claude Code works).

For the tools you write
Verdict first, evidence after (Python's -v output put the test results at lines 92 to 95 of about 240, which head-and-tail clipping cut in the parent's Loop lab); cap every result and say what was cut and how to get the rest; offer a search or filter parameter; keep errors in the history, since a failed attempt is information (Manus: "keep the wrong stuff in"); clear old results with a stub that names the call, so the model can rerun it.

4. Compaction, forced on purpose

Clearing keeps single results small, but the history still grows by every reply and action. Compaction replaces it: the harness asks a model to summarise the conversation, then starts a fresh window with the startup context, the summary and whatever it chooses to carry over. The designs, from crudest to most engineered:

  1. Drop the oldest turns (a sliding window): free; silently loses the task statement unless it is pinned.
  2. Clear old tool results (section 3): "one of the safest lightest touch forms of compaction" (Anthropic, 29 Sep 2025).
  3. Summarise everything into one structured message and restart from it.
  4. Summarise the older part, keep the recent tail verbatim. Claude Code 2.1.290 does this: every compaction record here carries a "preserved segment" of five messages MEASURED; the JetBrains summariser kept the last 10 turns. The common choice; Codex triggers at 90% of the window and other harnesses at other thresholds (Gemini CLI at 50%), read from source on Other coding harnesses, section 5.
  5. Edit the cache instead of the text. Every design above rewrites the prefix, so everything after the first changed token is prefilled again. Cache engineering lets the agent call drop (exclude chosen tokens' cached keys and values from attention) and repos (re-position the kept keys) instead; the serving engine must then track cache state, because the same token sequence can now have different caches. Dropping old tool responses on a rolling basis scored 1.7 points higher at 27.7% lower cost than summarising at a threshold, on the authors' benchmarks (Cache Engineering for Agents (arXiv 2610.28577)); it needs that engine, not a hosted API.
  6. On the provider's side or inside the model: the Claude API's compact_20260112 edit summarises past a trigger (150,000 input tokens by default); trained compressors and models that rewrite their own context go further (closed block below).

Forcing Claude Code to compact (the parent's sessions never came near 200K). Manual: a script keeps one claude -p --input-format stream-json session open and sends the task, then /compact, then a question. Automatic: --autocompact 100000 shrinks the window Claude Code compacts against to its 100K minimum, and the task reads five 75 KB logs (CLAUDE_CODE_AUTOCOMPACT_PCT_OVERRIDE=16 as well left the buffer at 33k: size, not the percentage, triggered it MEASURED). Each first message also said "the reviewer for this change is Ilse Marten, and the ticket number is TS-4471", and the folder's CLAUDE.md held "Release codename: KESTREL."; afterwards each session was asked, tools forbidden, to recall them, quote what the test runner first printed, and say what it changed.

  1. The task, call by call. Manual run 1: twelve calls to find and fix the two bugs, growing from 13,545 to 18,462 tokens, almost all of each read back from the cache (blue); every call adds one reply and one tool result on top of the last.
  2. /compact: one more model call writes the summary. The whole conversation goes to a summarising call inside Claude Code: 18,968 tokens came out as a 2,258-token summary in 23.5 seconds.
  3. The next call starts from the summary. Call 13 held 16,684 tokens: the startup prefix, 12,197, read from cache, and 4,477 written, because the summary is a new prefix after it. The project CLAUDE.md is read again from disk, not carried by the summary.
  4. What came through, and what did not. The summary copies every user message, so the reviewer and the ticket survived, and it kept the change with code snippets. The verbatim test output did not survive, and under "Pending Tasks" it listed a git commit nobody had asked for.
  5. Automatic, on a big history. With the window Claude Code compacts against set to 100K, five 75 KB reads put call 2 at 126,531 tokens (the first attempt had failed, "too_few_groups": right after the parallel reads there was only one exchange to summarise). The hidden summarising call (the glass column) read about 127,959 tokens, 113,729 of them fresh, about $0.12; 127,242 became 1,971 in 27.7 seconds, and call 3 held 15,760.

What happened, in all four runs. The three manual compactions took 18,968, 17,969 and 18,390 tokens down to 2,258, 2,357 and 2,472 in 23 to 32 seconds, and the turn that ran each cost $0.015 to $0.021 at list price MEASURED. The automatic one's cost is derived: the session's modelUsage input minus every streamed call. On a big history the summary is a large cost of its own. The first call after every compaction read the startup prefix (about 12,200 tokens) from cache and wrote the rest again: the summary is a new prefix. The card replays each session; "No compaction" is a different run of the same task.

What survived. The chat facts survived every compaction (the summary's section "All user messages" copies them), and the CLAUDE.md codename too, because Claude Code re-reads the project CLAUDE.md from disk after compacting. What went was verbatim tool output: all three uncompacted controls said correctly that the runner printed only "FAIL" lines and no assertion message; of the three manual compactions, two said they no longer had it and one confidently quoted its own later diagnostic output as what the tests printed. The large uncompacted run, at 130K tokens, put a maintainer note in two log files when it was in one.

Every session call by call: the compacted runs against their uncompacted controls

One column per model call, to scale: the tokens its request held (cache read + cache write + fresh), from the recordings. The summarising call itself is hidden from the stream and drawn as the dashed marker. "No compaction" is a different run of the same task, so its path differs: recorded sessions are paths, not samples.

Recall after the task, judged by hand against the recordings; hover a score for the reason. One run of each: what can happen, not rates.

The summary is a prompt to the next call: read what it tells the model to do


The whole summary, verbatim
Each compaction injects one user message: a fixed opening sentence, the model-written summary under nine headings, and a closing instruction. Chips: which facts of the session made it in. Shown open: the "Pending Tasks" and "Optional Next Step" headings, the part the next call is told to act on.
It can invent the next step
Claude Code's summary runs from "1. Primary Request and Intent" to "9. Optional Next Step" and ends: "Continue the conversation from where it left off without asking the user any further questions ... Pick up the last task as if the break never happened." In two of the three manual runs it listed a git commit under "Pending Tasks"; nobody asked for one (the agent had tried git init and the permission layer refused it). In the automatic run it merged an unrelated log line into the plan: "Identify and remove/fix any Python 3.8 compatibility code that breaks in 0.2". That agent ignored the false lead; the next might not. Steer it (/compact focus on ..., a PreCompact hook that saves state first) and review it like any prompt. What Claude Code re-injects after compacting (project-root CLAUDE.md, invoked skills up to 25,000 tokens, recent files) is listed on Claude Code, taken apart, section 9.
Every session call by call, the answers verbatim, and what each compaction cost

Driver for the manual sessions (the automatic ones used one task message that also asked for the five logs to be read in full):

claude -p --input-format stream-json --output-format stream-json --verbose \
  --no-session-persistence --setting-sources project --strict-mcp-config \
  --model haiku --permission-mode acceptEdits --tools "Read,Edit,Write,Bash,Grep,Glob" \
  --allowedTools "Bash(python3:*)" "Bash(python:*)" "Bash(ls:*)" "Bash(cat:*)" \
  --append-system-prompt "Never use the em-dash character." [--autocompact 100000]

# then, on standard input, one JSON line per user turn, each sent after the previous turn's result record:
{"type":"user","message":{"role":"user","content":"Before we start, note two things ... Do not edit the tests."}}
{"type":"user","message":{"role":"user","content":"/context"}}
{"type":"user","message":{"role":"user","content":"/compact"}}
{"type":"user","message":{"role":"user","content":"/context"}}
{"type":"user","message":{"role":"user","content":"Without using any tools, answer from memory ..."}}

/context answers without a model call; /compact runs the summarising call inside Claude Code and emits a compact_boundary record with the token counts before and after (the SDK documents both: commands in SDK sessions).

The answers, verbatim


What each compaction cost

"Compaction turn": the change in the CLI's total_cost_usd across the /compact turn (manual), or the hidden summarising call's input derived as modelUsage input minus every streamed call (automatic). "First call after": the next call's cache read and write.

Compaction on the provider's side and inside the model: the API, trained compressors, models that manage their own context

Server-side. The Claude API's compact_20260112 edit (beta header compact-2026-01-12) summarises when the prompt passes a trigger, 150,000 input tokens by default and at least 50,000, takes your own instructions for the summary, and returns a compaction block that replaces everything before it; a newer on-demand form (beta compact-2026-09-04) is now the recommended one (compaction docs, read 6 Oct 2026).

Trained compressors. Cognition describes fine-tuning a smaller model whose only job is compressing history (12 Jun 2025); End-to-End Context Compression at Scale (the Latent Context Language Models paper) compresses the context into soft tokens inside the model. A lighter hybrid keeps the text summary and adds what it loses: REMORY trains a small network to append a bounded run of soft memory tokens after the summary so a frozen model continues as it would with the full history; on SummHay it approached the full-context joint score with 5.2% of the input positions, and Qwen3.8-27B and GLM-5.3-Flash repeated fewer tool outputs and made fewer tool errors on BrowseComp and Terminal-Bench 2.1 (REMORY (arXiv 2610.11287)).

The model manages its own context. A Context Language Model (CLM) is given its context as a file it may rewrite without restriction, so what to keep becomes model behaviour, and several agents' contexts become several files. Built zero-shot from existing models, CLMs beat the best harness-side strategies the authors compared: 11.4% higher accuracy with 21.5% fewer FLOPs on BrowseComp-Plus, 5% higher scores with 59% fewer FLOPs on 12-hour EdgeBench. The policy can be taught: evolved natural-language instructions added up to 35.9 points on a held-out context-management task, and online RL raised Qwen3.5-9B on BrowseComp-Plus by 47.6% over its untrained start with 12% fewer FLOPs, though a summary harness trained the same way ends within noise of it, so the trained advantage is mainly cost (Context Language Models; arXiv 2609.37725; not the Latent Context Language Models above). Training any compacting agent has a credit problem: one trajectory spans several sessions, and broadcasting one trajectory-level advantage to every session cannot tell which helped; Mosaic shapes each session's advantage by its estimated contribution and beat broadcasting on BrowseComp with Qwen3.5-4B, in compaction and subagent-forking runs, using fewer sessions (Mosaic (arXiv 2610.22174)).

5. Memory files and skills: always loaded against loaded when needed

Some instructions must reach every task (how to run the tests, what never to touch); others matter for one kind of task (how to write release notes). Anything in the startup context is paid on every call and competes for attention; anything outside must be found. Memory files are plain text loaded into every session: Claude Code reads CLAUDE.md (and, per its docs, AGENTS.md, the cross-vendor name). Skills use progressive disclosure: a folder with a SKILL.md whose short description sits in the startup context; the body is read only when the model calls the Skill tool, and files it links only if needed (the three levels in Anthropic's Equipping agents for the real world with Agent Skills, 16 Oct 2025). Load order and rule syntax belong to Claude Code, taken apart; here only the window cost.

Asked to "Write the release notes for textstats version 0.2", Haiku called the Skill tool on its first call, and the next call wrote 1,361 new tokens to the cache: the body, prefixed with the skill's base directory, delivered as a message in the history MEASURED. It then followed the procedure (ran the tests, listed the public functions, ended with "Reviewed-by: (pending)"). Enabling the Skill tool also changed the tool list, so that session's first call found nothing cached and wrote all 15,584 tokens: section 2's rule again.

The same 3,834 bytes cost about 1,000 tokens as CLAUDE.md and about 40 as a skill

A 40-rule release-notes procedure as a project CLAUDE.md, and separately as .claude/skills/release-notes/SKILL.md with a one-sentence description; startup context from /context in fresh sessions (Claude Code 2.1.290, Haiku 4.5; tools Read, Edit, Write, Bash, Grep, Glob, Skill). The skill row includes the descriptions of 14 skills that ship with Claude Code (about 1.7k tokens).
Memory file (CLAUDE.md, AGENTS.md)Skill
Cost when unusedFull text, every callDescription only (about 40 tokens here)
RiskCrowds the window and dilutes attention as it growsNever loaded if the description does not match the request; a skill invoked is not a skill obeyed
After compactionProject-root file re-read from disk; nested files only when a matching file is read againInvoked bodies re-injected, 5,000 tokens each and 25,000 in all, oldest dropped first; truncation keeps the start, so put the important rules at the top
Use forFacts every task needs: build and test commands, layout, hard rulesProcedures for one kind of task; long reference material

The parent measured the other side of the trade: a four-line CLAUDE.md stating the test command cost 184 tokens and saved most runs several exploring calls, though one run explored anyway. Research: Demystifying Agent Skills (why skills help and when they misfire) and Repo-To-Skill (distilling repositories into skills).

6. Subagents: a second window for the reading

Some subtasks read a lot and answer briefly: "which module defines a class?" over a whole package. Done in the main loop, every file read stays in the main history. A subagent is a second agent loop with its own fresh window: the parent writes it a task, it reads, and only its final text returns as one tool result. Measured on a 30-module Python package (121 KB) with "Read every module in service/ in full ... which module defines a class, and which module has the largest number of functions?", twice without the Agent tool and twice told to delegate to one general-purpose subagent (Haiku 4.5 throughout).

  1. Without a subagent, the parent reads everything. Haiku read all 30 files in one turn of parallel Reads: the main window went from 13,020 to 62,442 tokens (64,533 in the second run), and every later call carries them.
  2. With one, the parent writes a task. The Agent tool's definition makes the startup larger (15,410 tokens on the first call). The task message is all the subagent will know: it sees nothing of the parent's history.
  3. The subagent reads in its own window. Its window grew from 9,177 to 43,503 tokens (52,694 in the second run) as the modules came in.
  4. Only its final text comes back. One tool result reaches the parent, which ended at 16,351 tokens (16,409 in the second run), a quarter of the window without a subagent; the subagent's window is then thrown away MEASURED.
  5. Isolation, not savings. All input processed: 181,517 tokens against 88,104 (265,699 against 92,175 in the second runs), two to three times as much, yet the cost was about the same ($0.130 and $0.134 against $0.134 and $0.139) because nearly all of it was cache reads. On a question one grep answers, the subagent only added cost: $0.057 against $0.020, 2.8x MEASURED.
The four runs as bars: main window, subagent window, all input processed

A subagent keeps the parent's window at a quarter, and processes two to three times the tokens

Per run: tokens in the main loop's last request (what the parent carries forward), in the subagent's last request, and all input processed in the session (from the result's per-model usage); API-price equivalent of the whole session beside each run.

So a subagent buys isolation, not savings: the parent's later calls stay small, its attention is not spent on 46,000 tokens of code it no longer needs, and it compacts later. Anthropic's guidance has subagents return "a condensed, distilled summary" of about 1,000 to 2,000 tokens (29 Sep 2025). Two traps: the subagent sees nothing of the parent's history, so the task message must carry everything; and the CLI's result.usage leaves the subagent's calls out while modelUsage includes them (measured on the parent page). When several agents must make decisions that agree, isolation becomes a coordination problem: Multi-agent patterns owns that, including Anthropic's advice to fold most subagents back into one loop that discloses skills and tools progressively, since tool choice degrades beyond 30 to 50 tool definitions.

7. Notes outside the window: state that survives

A task longer than one window or one session must leave its state where the next window can read it, and the history is not that place: compaction rewrites it and a new session starts without it.

  • Progress files and handoff notes. Anthropic's long-running harness has an initializer agent write a feature list (every feature initially failing) and a progress log; each later session reads them, does one feature, tests it, commits and updates the log (26 Nov 2025). Git history is part of the note.
  • Todo lists as recitation. Manus has the agent rewrite a todo.md as it goes, keeping the plan in the most recent part of the context, where it is least likely to be lost (18 Jul 2025); Claude Code's TodoWrite tool plays the same role.
  • A memory directory as a tool. The Claude API's memory tool (memory_20250818) gives the model file commands (view, create, str_replace, insert, delete, rename) on a /memories directory your application stores, with system-prompt text telling it to check the directory first and assume the window may be reset at any moment (memory tool, read 6 Oct 2026). On Anthropic's own evaluation, memory tool plus context editing improved performance by 39% over baseline, context editing alone by 29% (29 Sep 2025; vendor-reported).
  • The file system as context. Keep a pointer instead of the content: a path, a URL, a query. Manus calls the file system "the ultimate context" and makes every compression restorable this way; Anthropic calls it just-in-time context.

Who curates, and when. Just-in-Time Memory (Salesforce, 23 Sep 2026) curates an agent's memory at read time, once the task is known: untrained read-time curation beat untrained write-time memory in 15 of 17 comparisons, though most of the headline +16 points comes from RL training. Proactive Memory Agent (Meta AI, 9 Jul 2026) runs a second model beside the agent that keeps a small memory bank and injects reminders: Sonnet 4.5 went from 37.6% to 45.9% on Terminal-Bench 2.0 with an Opus 4.6 memory agent, single runs. Anthropic splits its own agent memory into three steps: capture (the model writes notes it predicts will be useful), consolidation, an offline pass it calls dreaming that rereads transcripts and notes, fixes wrong notes, builds wiki-style pages and promotes key notes into the start-of-session context, and retrieval (that small injected layer plus search). Its lessons: let a strong model judge what is salient, tell it what memory is for rather than how to keep it, and keep the injected layer small; on its own corpus test, a consolidated wiki plus search beat search alone (numbers below). Resident personal agents keep memory files across days: Personal agents.

Anthropic's agent memory measurements (6 November 2026)

On CL-Bench's database task, Opus 5.5 went from 0.655 mean reward without memory to 0.838 with a memory store. On a corpus of about 350,000 files with 25 questions, the wiki alone went from 13% to 48% of graded criteria as dreaming scaled from two sessions to 128; the wiki plus search reached 61% against 53% for search alone, saving about 20,000 tokens per question. Giving each contract its own page raised the facts kept from 41 of 57 to 57 of 57. Anthropic's own tasks; the article does not say how many runs each number is. Claude Code's auto memory loads only the first 200 lines or 25 KB of MEMORY.md (Anthropic, vendor-reported).

8. Memory layers: Mem0, Zep's Graphiti, Letta

Notes (section 7) are files the agent writes and reads itself. A memory layer is a store a framework plugs in, where a model derives something smaller than the history (facts, a graph, a self-edited block) and decides what to do when new information contradicts old. Two policies define every one: a write policy (what is extracted, in what form, and whether a contradicted memory is overwritten, kept beside the new one, or closed with a date) and a read policy (who decides to look, the harness on every answer or the model when it chooses, with what query, and how many results go back into the prompt).

answer correct ⇒ fact written ∧ fact retrieved ∧ fact read correctly

Every failure in the experiment below sits at one of the three links. Checking whether the evidence reached the prompt (no model needed) separates the first two from the third.

Four ways carry knowledge across sessions, in rising machinery: paste the full history (the baseline every product must beat, while it fits); notes the agent keeps (section 7); search the raw history, which is retrieval over your own chat log (rag-and-retrieval owns the mechanics) and keeps "tests run with test_core.py" beside "the test command is now pytest"; and a memory layer, which consolidates. LangGraph's store is the bare key-value form (LangChain and LangGraph, section 10). Three designs dominate:

Facts: Mem0

Store what was learnt, not what was said: a model turns each conversation into short sentences ("User's tests run with pytest"), each embedded; before an answer the closest sentences are pasted into the prompt. Cheap to read, easy to inspect. Since v2.0.0 (16 April 2026) the open-source library is "single-pass, ADD-only": a changed fact becomes a second sentence beside the old one.

Temporal graph: Zep, Graphiti

A model turns each conversation into entities and dated relations; a newer relation that contradicts an older one closes the older one's validity window: nothing is deleted, so the graph answers both "what now" and "what before". Built for "what changed, and when".

Paging: MemGPT, Letta

The model manages its memory with tools: a small block always in the prompt plus archives it writes to and searches, like an operating system paging between RAM and disk. Nothing is stored or found unless the model decides to.

One changing fact, four write policies: rewritten, piled up, closed with a date, or filed away

Sam's gateway, as each store held it after each session (recorded 6 Oct 2026; writers: Haiku 4.5 for the paper loop, Mem0 2.2.1 and Graphiti 0.30.2, the local Qwen3-4B for Letta 0.16.8). Bars run from the session that wrote an item to the session that rewrote or closed it; struck text is gone from the store. Dashed outlines: what each store will hold by 6 October.

One changing fact, four stores. Sam's gateway changed three times in twelve sessions; the chart follows what each store held about it, with the stored text under the chart.

  1. Session 1, 1 Sep: "All our model calls go through a LiteLLM proxy." Every store writes one item: the paper loop ADDs a memory, Mem0 2.2.1 a sentence, Graphiti an edge valid from 1 September, Letta a note filed in its archive (its core block, the part always in the prompt, never held the fact).
  2. Session 5, 15 Sep: "we dropped LiteLLM; everything goes through OpenRouter now." The paper loop UPDATEs the memory in place, so the LiteLLM text is gone, and ADDs a note of the change; Mem0 adds a second sentence beside the first; Graphiti closes the LiteLLM edge on 15 September and opens one for OpenRouter; Letta files a second note.
  3. Session 9, 26 Sep: "we switched the primary model from Haiku to Sonnet for planning steps only". Nothing about the gateway changed, yet Graphiti closed the OpenRouter edge with this date (red): a model judged the new fact to contradict it.
  4. Session 12, 3 Oct: "we are putting LiteLLM back, this time in front of OpenRouter". The paper loop rewrites its change note and adds the reason; Mem0 now holds three sentences, all current; Graphiti opens a new edge with no end date; Letta files a third note.
  5. 6 Oct: "What gateway setup do we use right now?" The reference answer is LiteLLM in front of OpenRouter. With Haiku reading, the paper loop, Mem0 and Graphiti all answer it, as does the full history; Letta, run by the local 4B model, said it had no information about the gateway.

The experiment. All three products ran on the same twelve invented sessions between a user, Sam, and an assistant (the parent frameworks root's four sessions extended to twelve; invented, assistant turns are fixed text so every system saw exactly the same history; about 1,400 tokens in all, so the full history fits and is an honest upper bound), then answered 25 questions in LongMemEval's five abilities, asked "on" 6 October 2026. Two measurements per answer: did the evidence words reach the prompt (no model needed), and was the answer right (keyword rules per question; an abstention question passes when the answer says it does not know or corrects the false premise; every answer was also read by hand). Writers and readers are Claude Haiku 4.5 and a local Qwen3-4B on Apple M1 Pro. A demonstration of mechanisms, not a benchmark MEASURED.

MemoryWriterExtraction
5 q
Multi-session
4 q
Update
6 q
Temporal
6 q
Abstention
4 q
All, Haiku readsAll, 4B readsEvidence reached the prompt
No memorynone0/50/40/60/64/44/254/25n/a
Full history in the promptnone5/54/46/64/64/423/2524/2521/21
Mem0 2.2.1 (library)Haiku4/53/46/65/64/422/2521/2520/21
Mem0 paper loopHaiku5/54/46/65/64/424/2524/2520/21
Mem0 paper looplocal 4B4/54/45/62/64/419/2517/2518/21
Graphiti 0.30.2Haiku2/52/43/64/64/415/2517/2514/21
Graphiti 0.30.2local 4B0/50/40/61/64/45/255/251/21
Letta 0.16.8, its own looplocal 4B0/50/40/60/64/44/254/251/21
Letta's notes, pasted wholelocal 4B4/54/46/63/64/421/2521/2521/21

Questions right by ability, read by Haiku (Letta's own loop: the local model); "evidence" is out of the 21 questions that have an answer. Recorded 6 Oct 2026: Mem0 2.2.1, Graphiti 0.30.2 on FalkorDB 4.22, the archived Letta 0.16.8 server; the paper loop is the parent frameworks root's minimal ADD/UPDATE/DELETE/NOOP implementation. Scripts and redacted recordings: src/memory_layers/.

What the table says. Pasting the whole history scored 23 of 25; the best memory, the paper loop with a Haiku writer, 24; Mem0 2.2.1 22; Graphiti 15, because only 14 of 21 answers' evidence reached the prompt; Letta's own loop 4, though its notes pasted whole gave 21: its write side worked and its read side did not (it searched on 5 of 25 questions). With no memory at all, 4. Swap the writer for the 4B model and the same designs lose facts: the paper loop fell to 19 and Graphiti to 5.

What writing the memory cost, per design
Memory (writer)Write calls, 12 sessionsTokens inModel time (s)API-price equivalentSearch per question (ms)Memory text per question (chars)
Mem0 2.2.1 (library) (Haiku)12117,26663$0.0711801,446
Mem0 paper loop (Haiku)2421,64594$0.03803,286
Graphiti 0.30.2 (Haiku)71177,234251$0.278651,227
Graphiti 0.30.2 (local 4B)3741,2851,360local0299
Mem0 paper loop (local 4B)249,7982,436local03,822
Letta 0.16.8, its own loop (local 4B)29139,926842localin-agent-
Full history in the prompt0--local05,796

Claude figures are the CLI's API-price equivalent at Haiku 4.5 list prices; local-model figures are tokens and seconds on a shared M1 Pro, comparable only with each other. Mem0's input is dominated by its extraction prompt (7,924 tokens with the Qwen tokenizer, over the shared local server's limit, which is why the library's writes used Haiku). Graphiti made 71 calls for 12 episodes: two is the minimum per episode (entities, then facts), and every new fact that resembles an old one costs another resolve_edge call (26 of them here). Letta has no separate search step: its 25 answers took 36 model calls inside its own loop.

break-even sessions ≈ write cost per session / (history tokens saved per answer × answers per session × input price)

At this size pasting everything is cheaper than any memory layer for a long time. The vendors' own numbers say the same at their scale: Mem0's paper puts full context at 26,031 tokens per LOCOMO conversation against 1,764 for Mem0, and its p95 latency at 17.12 s against 1.44 s (91% lower, while full context stays more accurate), Zep's about 115K against 1.6K on LongMemEval; the saving appears only once history is tens of thousands of tokens and is read many times.

Every published benchmark number for these products, with its runner

No benchmark was rerun here. LOCOMO (Maharana et al., arXiv 2402.17753, Feb 2024) is long two-person chats scored by an LLM judge (the "J score"); the paper describes 50 conversations of about 300 turns and 9K tokens, up to 35 sessions; its public release has 10 conversations, 1,986 questions, and 444 of the 446 adversarial questions have no reference answer, so every product evaluation drops that category; it has no knowledge-update questions. LongMemEval (arXiv 2410.10813, ICLR 2025) has 500 questions over histories of about 115K tokens (setting S) or about 500 sessions and 1.5M tokens (M); counts in the released file: temporal 133, multi-session 133, knowledge update 78, single-session user 70, assistant 56, preference 30, with 30 abstention variants. DMR, MemGPT's test, has 5 short sessions per conversation, which fit in a window. MemoryAgentBench (UCSD, arXiv 2507.05257) is independent.

BenchmarkSystemScoreRunnerAnswer modelDateNote
LOCOMOFull context (baseline)72.90baselinegpt-4o-mini28 Apr 2025in Mem0's own table, above both Mem0 variants
LOCOMOMem066.88 (Mem0g 68.44)vendorgpt-4o-mini28 Apr 2025paper system (1.x pipeline); 1,764 memory tokens per conversation against 26,031 for full context
LOCOMOZep65.99rivalgpt-4o-mini28 Apr 2025run by Mem0
LOCOMOZep84 (retracted)vendorgpt-4o-mini6 May 2025category-5 correct answers counted in the numerator only
LOCOMOZep58.44rivalgpt-4o-mini8 May 2025Mem0's rerun with Mem0's template
LOCOMOZep75.14 ± 0.17vendorgpt-4o-mini12 May 202510 runs; Zep corrected the calculation error within a week
LOCOMOLetta (file tools)74.0vendorgpt-4o-mini12 Aug 2025grep, search_files, open, close over the conversation stored as files
LOCOMOZep69.62 to 80.32vendorgpt-4o-mini (agent and grader)9 Dec 20255 edges / 2 nodes to 30 / 30 retrieved; default 15 / 5 gives 77.06
LOCOMOMem0 platform92.5 (old 71.4)vendornot statedApr 2026"top_200" retrieval; managed platform, "proprietary optimizations not available in the open-source SDK"
LongMemEval SZep63.8 vs full context 55.4vendorgpt-4o-mini20 Jan 2025115K-token histories; Zep context 1.6K tokens
LongMemEval SZep71.2 vs full context 60.2vendorgpt-4o20 Jan 2025the "+18.5%" is relative; Zep lower on single-session-assistant (94.6 to 80.4)
LongMemEval SGPT-4o, no memory system60.6 (87.0 given only the evidence sessions)independentgpt-4o14 Oct 2024the benchmark paper: "30% to 60%" drops for long-context models
LongMemEvalMem0 platform94.4 (old 67.8)vendornot statedApr 2026top_200 retrieval; managed platform
DMRMemGPT93.4 (GPT-4 Turbo alone 35.3)vendorgpt-4-turbo12 Oct 2023baseline is a fixed window with recursive summaries; GPT-4: 32.1 against 92.5
DMRZep94.8 (MemGPT 93.4, full conversation 94.4)vendorgpt-4-turbo20 Jan 2025each conversation "easily" fits in the window
MemoryAgentBenchMem0 / Zep / MemGPT21.1 / 24.0 / 28.3 overallindependentgpt-4o-miniv4 28 Jun 2026BM25 41.5, long context 42.2 (Table 3); 2025 product versions, chunked documents
AMA-BenchMem0 / MemGPT0.210 / 0.330 averageindependentQwen-32B26 Feb 2026agent trajectories, not chat; MemoRAG 0.461 best

The same product, Zep, scored 58.44%, 65.99%, 75.14% and up to 80.32% on LOCOMO depending on who configured it, the retrieval template, how many results were retrieved and how one category was counted. Ask five things of any memory benchmark claim: who ran it; does the whole history fit the answer model's window (then full context is the baseline to beat, and it often wins); which answer and judge models; how many memories were retrieved per question; which product version. Sources read 6 Oct 2026, quotes in src/memory_layers/inputs/research_claims.md.

How each failed (all recorded here; the fix after each arrow):

  • Duplicates, re-dated (Mem0 2.2.1): 13 of 45 memories restate an earlier fact, because extraction re-reads the previous session's last messages "to resolve references" and stamps each copy with the later date; hash deduplication only catches identical text. → deduplicate by meaning; keep source message id and date.
  • History overwritten (paper UPDATE): only the current text survives, so "what did we use before?" has nothing to read. → validity windows, or a searchable log of every UPDATE.
  • Facts never written (Graphiti): attributes and numbers (the $200 budget, $143 spent, four engineers, the Friday CSV report) became no edge, and edge search never returns raw episodes. → search episodes too; custom entity and edge types.
  • Wrong invalidation (Graphiti): 4 of 7 closed edges were closed wrongly by a model's "contradicts" judgement, and 7 edges with no valid_at can never be retired ("eval set has 40 tasks" stayed current after it grew to 60). → review closures; require a date.
  • Silent write loss (4B writer): one extraction came back as a bulleted list instead of JSON, so the paper loop stored nothing and raised nothing; Graphiti lost 2 of its first 3 episodes to a parse error ("Extra data"); Mem0's code also just logs and stores nothing. → constrained output, alert on zero facts, keep the raw conversation.
  • Never searching (Letta, local model): everything after session 1 lived in archival notes, and the agent searched on 5 of 25 questions. → key facts in the always-visible block, or the harness searches first (Personal agents measured Haiku never searching until one sentence told it to).
  • Wrong day arithmetic, even with everything in the window: "yesterday" resolved to the day Sam said it, "Saturday" to the wrong Saturday, for every design; a stored wrong date is then repeated as fact. → resolve relative dates at write time against the message timestamp.
Choosing a memory design for your situation
If your situation isUseWhy
History still fits in the window, read a few timesNothing: paste itWithin one question of the best memory here, and above both Mem0 variants in Mem0's own LOCOMO table (full context 72.90 against 66.88)
A coding or task agent that must survive a session boundaryFiles the agent maintains (section 7)Readable, diffable, editable by a person; read at start
Many users, preferences and stable facts, cheap readsFact memory (Mem0 or your own store)One search, a few hundred tokens per answer; plan for duplicates and stale facts (the 2.x library never deletes: schedule a consolidation or call update/delete yourself)
Questions about change: what was true whenTemporal graph (Graphiti or Zep)Validity windows answer "before" and "now" from one store; budget for many model calls per episode, a graph database and wrong closures, and search the raw episodes too
A long-lived assistant on a model strong at toolsSelf-managed memory (Letta style, or files plus search tools)The model decides what is worth keeping; only as good as its habits (a small model here filed diaries and rarely searched)
A large corpus of documents, not a conversationRetrieval (RAG)A memory layer is retrieval over a derived store; when nothing needs consolidating, search the source

Who curates, and when, is the one design question under all of them: the harness at write time (Mem0, Graphiti), the model in the hot path (Letta, the memory tool), or a curator at read time (Just-in-Time Memory, section 7). When the agent itself decides what to search and how to rewrite the query, that loop is Agentic retrieval.

Mem0: the paper's extract-then-update loop, the 2.x library, and how it ranks

The paper (Apr 2025) and Mem0 1.x (Chhikara et al., arXiv 2504.19413, section 2.1): two phases with GPT-4o-mini. Extraction: a model sees the new message pair, a running summary and the last m = 10 messages, and lists candidate facts. Update: for each candidate the s = 10 most similar stored memories are retrieved and a model picks one operation by tool call: ADD, UPDATE ("augmentation of existing memories with complementary information"), DELETE ("removal of memories contradicted by new information") or NOOP. The store holds the current truth; a history table logs the edits. A minimal version of this loop was run for this page (it shows the whole store to the update call instead of the top 10); with a Haiku writer it made 40 ADDs, 11 UPDATEs and 5 NOOPs over the twelve sessions.

The library since v2.0.0 (16 Apr 2026), run here at 2.2.1: "Single-pass, ADD-only": one call per add(), "No separate UPDATE/DELETE pass ... Hash-based deduplication prevents exact duplicates; ranking at retrieval time handles the rest" (v2.0.0 release). The call sees the 10 stored memories most similar to the new messages (their ids replaced by small integers, "anti-hallucination"), the last 10 messages of the scope, and an observation date (main.py, _add_to_vector_store). The docs: "Nothing is overwritten or deleted" (memory evaluation). Memories are scoped by user_id, agent_id and run_id; there are no "layers with promotion between layers", as an old note here claimed (docs).

Reading in 2.2.1 is hybrid (score_and_rank): a vector search over-fetches max(4 × k, 60) candidates; BM25 runs on spaCy-lemmatised text; named entities in the question boost memories linked to the same entity; candidates under 0.1 cosine similarity are dropped, and the rest ranked by

score = (cos + bm25̂ + entity boost) / (1 + 1bm25 + 0.5entity)
cos
cosine similarity of question and memory embeddings (here bge-small-en-v1.5, 384 dimensions)
bm25̂
BM25 score squashed into 0 to 1 by a sigmoid whose midpoint depends on query length
divisor
1, plus 1 if any BM25 hit, plus the entity weight 0.5 if any entity hit, so a memory found by all three signals can reach 1.0

Two limits of the open-source library. add() takes a timestamp documented as "Platform-only temporal parameter. Not supported in OSS", so the prompt's "Observation Date", the anchor for "yesterday", is the machine's current date: right in live use, wrong for every message of an imported history (this run patched the date to each session's). And the extraction system prompt alone is 7,924 tokens with the Qwen3 tokenizer, over the shared local server's limit, so the library's writes used Haiku.

Graphiti: bi-temporal edges, the add_episode pipeline, how invalidation and search work

Who is who. Zep published the design (Rasmussen et al., arXiv 2501.13956, 20 Jan 2025); its open-source engine is Graphiti (Apache-2.0, 31,489 GitHub stars on 6 Oct 2026). Zep stopped maintaining its self-hosted Community Edition on 2 April 2025 (announcement); Zep Cloud runs a proprietary engine. Graphiti 0.30.2 needs a graph database: Neo4j, FalkorDB, Amazon Neptune, or the embedded Kuzu, deprecated ("the upstream Kuzu project is no longer maintained"), which here failed on the first episode ('KuzuDriver' object has no attribute '_database'); this run used FalkorDB 4.22 in Docker.

Four timestamps per fact. The model is bi-temporal: "t'_created and t'_expired ... monitor when facts are created or invalidated in the system, while t_valid and t_invalid track the temporal range during which facts held true"; in Graphiti, created_at, expired_at, valid_at, invalid_at. In this replay every closed edge has expired_at 6 October 2026 (the day of the run) but invalid_at in September: the system's clock against the world's.

One add_episode (each session went in as one episode, the raw text kept as "a non-lossy data store", with reference_time set to its date) runs these prompts; calls for 12 episodes with Haiku: extract_nodes.extract_message (find the entities) 12, dedupe_nodes.nodes (is this "Sam" the node already there?) 11, extract_edges.edge (facts as relations, one sentence each) 12, extract_edges.extract_timestamps (valid_at and invalid_at relative to the reference time) 7, dedupe_edges.resolve_edge (which existing facts the new one duplicates or contradicts) 26, extract_nodes.extract_summaries_batch (rewrite the touched entities' summaries) 3; 71 in all.

Invalidation is a model's judgement. For each new edge Graphiti finds similar existing edges and asks a model which are duplicates and which the new fact contradicts (dedupe_edges.py); code then sets each contradicted edge's invalid_at to the new edge's valid_at, provided the old edge started earlier (resolve_edge_contradictions). An edge with no valid_at is never closed by that rule. Search combines cosine similarity over edge embeddings with BM25 and merges them by reciprocal rank fusion; the paper adds breadth-first graph search and rerankers (maximal marginal relevance, distance from a centre node, episode mentions, a cross-encoder). Only edges come back, so a detail that landed in an entity summary is invisible to it.

MemGPT and Letta: virtual context, and what is left of the server

MemGPT (Packer et al., arXiv 2310.08560, 12 Oct 2023) splits the prompt into system instructions, a working context the model edits with function calls, and a queue of recent messages; outside sit recall storage (every past message, searchable) and archival storage (what the model chose to file, searched by embedding). Past a warning threshold ("e.g. 70% of the context window") the system tells the model; at the flush threshold it evicts about half the queue into recall storage and replaces it with a recursive summary. The analogy is operating-system paging (Virtual memory). On its own Deep Memory Retrieval test GPT-4 alone with a fixed window and recursive summaries answered 32.1%, inside MemGPT 92.5%; GPT-4 Turbo 35.3% against 93.4%; Zep later reported the full conversation pasted in at 94.4%: the baseline MemGPT beat was a deliberately small window.

Letta. In Sep 2024 MemGPT became Letta; "MemGPT should refer to the original agent design pattern" (Letta blog, 23 Sep 2024). The V1 server kept memory blocks (a label such as human or persona, a text value, a character limit) always in the prompt, tools to edit them (memory_insert, memory_replace), conversation_search, archival_memory_insert and archival_memory_search, over Postgres and pgvector. Its last PyPI release, 0.16.8 (14 May 2026), is the one run here; the repository was archived on 16 Aug 2026, and from 0.32.13 (17 Sep 2026) the PyPI name letta installs Letta Code, a terminal agent whose memory is MemFS: "a git repository that belongs to the agent", root files in the system prompt every turn, other folders read on demand, no vector index by default, background "dreaming" subagents consolidating (MemFS docs, read 6 Oct 2026). That is section 7's memory-files design, run by the agent itself.

Running the archived server took three repairs: pip install letta==0.16.8 resolves today to dependency versions that break its imports (installing with dependencies as of its release date fixed that); its database layer only speaks Postgres, though its settings still mention SQLite; and the wheel ships no migrations, so the tables came from its ORM and the message sequence default was added by hand. The agent was letta_v1_agent with archival tools, an 8,192-token window, temperature 0 and the local Qwen3-4B, the only model here that can drive its tool loop over an OpenAI-compatible endpoint; each question went to a fresh conversation with the blocks copied.

The question set, the vocabulary, and how to check a memory layer before trusting it

LongMemEval's five abilities (Wu et al., arXiv 2410.10813, ICLR 2025; 500 questions over histories of about 115K tokens in setting S), used for the 25 questions here: information extraction (one fact said once, by the user or the assistant: "In the talk outline you drafted for me, what was the second point?"), multi-session reasoning ("How many times in total did the fallback kick in?", 37 in one session and 12 in another), knowledge update ("What gateway setup do we use right now?"), temporal reasoning ("On what date did the agent delete the tests folder?", said as "yesterday" on 17 September), and abstention ("When is the team offsite in Tokyo?"; it is in Lisbon). With the whole history pasted (about 1,400 tokens) Haiku got 23 of 25: it dated the deletion to the day Sam reported it and put the OpenRouter outage on the wrong Saturday.

Vocabulary. LangMem's guide splits long-term memory into semantic (facts and preferences), episodic (past experiences, summaries, few-shot examples) and procedural (how to behave: prompt rules), and memory formation into "in the hot path" (the agent saves while it talks, adding latency) and in the background (LangMem conceptual guide, read 6 Oct 2026). Mem0 and Graphiti are semantic memory formed in the background; Letta forms it in the hot path.

Before trusting a memory layer: (1) write a question set like this one on your own data, all five abilities, with the full-history baseline while history fits; (2) measure evidence before answers: if the evidence is not in the prompt, no reader model fixes it; (3) read the store after every session for a while: duplicates, wrong dates and wrongly closed facts show long before they cause a wrong answer; (4) log write failures loudly: an extraction that fails to parse must be an alert, not an empty list; (5) swap the writer model and rerun: the same design with a 4B writer lost what the Haiku writer kept.

Rehearsal. "I moved from Austin to Seattle": what does each design store? Paper-style memory updates "lives in Austin" to "lives in Seattle" (history lost unless logged); Mem0 2.x adds the new fact beside the old and relies on ranking; a temporal graph closes the LIVES_IN Austin edge at the move date and opens one for Seattle; self-managed memory edits its core block if the model notices. Only the graph answers "where did I live in March" directly. Why can memory make an assistant worse? Stale or duplicated facts outrank current ones, wrong dates are repeated with confidence, retrieved snippets crowd out the instruction, and without a "say you don't know" rule abstention questions become confident answers built from near misses. Memory for a million support users? Scope per user and account; write in the background, not the hot path; short facts with source message ids and dates; hybrid search with a small top-k; raw transcripts kept for audit and re-extraction; explicit conflict resolution; a LongMemEval-style test set with abstention and updates; users can see and delete what is stored. Bi-temporal, why? When a fact was true in the world answers "what was true then"; when the system learnt or retired it audits what the agent knew when it acted.

9. Context rot: recall decays before the window is full

A 200,000-token window does not mean 200,000 tokens used equally well. Context rot is the name that stuck: "as the number of tokens in the context window increases, the model's ability to accurately recall information from that context decreases" (Anthropic, 29 Sep 2025). A needle test hides one fact at a chosen depth in long filler and asks for it back. Here the haystack is real Python (files of the Python 3.9 standard library in a fixed shuffled order, cut to each length) and three needles are each hard in a different way:

  • Literal: RELEASE_PORT = 8371 # port of the textstats release box; "What value is RELEASE_PORT set to in the file above?" shares the needle's words: a lookup.
  • Non-literal (in the style of NoLiMa): # Ops note: the textstats release box sits in the rack right next to the Semperoper.; "In which city is the textstats release box located? Use what the file says plus general knowledge." The answer, Dresden, is not in the file: find the line by meaning and add one known fact.
  • State tracking: RETRY_LIMIT = N assigned five times at random depths; "What is the value of RETRY_LIMIT at the end of the file?" needs all five, in order.

Claude Haiku 4.5 found the literal needle in all 20 cases and the non-literal one in all 20, from 2,201 to 113,710 tokens MEASURED. Tracking was 28 of 32: the four misses (at 2K, 16K, 16K and 64K tokens) all named an earlier assignment, and at 64K and 120K four of the nine replies that listed the assignments found only four of the five yet named the right final value. Errors did not grow with length: this run shows no rot for Haiku at these lengths, only that lookup is easy and keeping order is not.

The local 4B model found the literal needle in all 13 cases from 781 to 11,622 tokens (its tokenizer counts the same code in fewer tokens). Asked directly "In which city is the Semperoper?" it answered Dresden; with the same fact as a comment inside 1K to 12K tokens of code it answered Dresden in 4 of 13 cases and otherwise Berlin, Boston, San Francisco, Seattle or Portland MEASURED: the code pushed aside knowledge it has. Drew Breunig calls this context distraction, "when a context grows so long that the model over-focuses on the context, neglecting what it learned during training" (22 Jun 2025); here it took only 781 tokens. Tracking: 10 of 20 with no trend in length (0 of 5 at the shortest, 5 of 5 at about 5,700 tokens): a capability limit, not rot.

Lookup holds to 114K tokens; keeping order fails at any length, and a small model ignores what it knows

Tap a cell to read the model's reply.
One request per cell, tools off, a one-line system prompt asking for the answer only. Haiku 4.5 through claude -p (Claude Code adds about 420 tokens); the local model, Qwen3-4B-Instruct-2507 in 4-bit MLX on Apple M1 Pro, through mlx_lm.server at temperature 0 (a different and much smaller model, not comparable as the same). Graded automatically by src/needle/grade.py: the expected answer must appear; for tracking, the stated final value must equal the last assignment. Recorded 6 Oct 2026; results in src/inputs/needle_*.json.

At scale the literature finds the same shape: position matters (the 75.8% to 53.8% "lost in the middle" figures are on Agentic retrieval); literal lookup saturates while tracking and non-literal tasks degrade (RULER's GPT-4, advertised at 128K, was effective to 64K; NoLiMa took GPT-4o from 99.3% to 69.7% at 32K; both on Long-context and multimodal benchmarks); and Chroma's "Context Rot" report (Hong, Troynikov and Huber, 14 Jul 2025) found performance falling with input length on 18 models even on simple tasks, faster with distractors and with needles less similar to the question. Why effective context is shorter than the window is Long context's subject. An agent's context is the worst case: the facts it needs are scattered through tool results, rarely share the question's words, and sit among near-duplicates; section 4's 130K-token session that put a note in two log files is a small instance, and the reason to keep the window lean.

10. Your own context policy, in order

For a harness of your own the levers become a short list of decisions, cheapest and safest first, each with the measurement that tells you it works.

  1. Lay out the request for the cache. Tools, system prompt, memory files, then the history one block per message, append only; nothing volatile before the last message. Check: from the second call on, cache reads equal the previous call's whole prompt (section 2's static rows).
  2. Bound every tool result. A size cap with a note on what was cut and how to get the rest; verdict first; a filter parameter. Check: the largest single result in your traces, against the window.
  3. Clear old observations. Replace results older than the last few turns with a stub naming the call; keep the model's reasoning and actions. Check: per-call input flattens instead of growing linearly; solve rate unchanged on your task set.
  4. Load instructions on demand. A short memory file for facts every task needs, skills for procedures. Check: startup context size, and whether the skill was invoked when it should have been.
  5. Isolate wide reading. A subagent for any subtask with a large input and a small answer, with a complete task message. Check: the parent's window at the end, and total tokens from per-model usage.
  6. Keep state outside the window. A progress file the agent updates, re-read at start and after compaction; a memory layer only once history stops fitting. Check: kill the session halfway and see whether a fresh one resumes correctly.
  7. Compact last, and review what it writes. Summarise the old part, keep the recent tail, re-inject the files that define the task, test the summary for invented next steps. Check: ask after compaction what you asked before (section 4's probes).

LangChain names the same moves in four words: write (outside the window), select (pull in what is needed), compress, isolate (2 Jul 2025); the 12-factor-agents list puts "Own your context window" third; Topic: agentic-frameworks discusses when a framework owns these decisions for you. The parent's Loop lab (step 4) is a working example of points 2 and 3 in about 40 lines of Python.

Depth: mistakes worth a second look, and rehearsal

A timestamp, a random id or a changing tool list in the prompt prefix
Every call rewrites everything after it: about 8x the input-side cost of a stable prefix per call (section 2). Put volatile values in the last message.
Trusting /context or a character count as an exact token budget
/context estimated 12.6k where the API counted 13,320; the same log is 228,000 tokens to Haiku 4.5 and 304,996 to Sonnet 5.5. Budget against the provider's own counts, per model, with a margin.
Summarising big tool outputs by default
The summarising call reads the whole output: $1.23 for a 471-token summary of the 491 KB log, while a filter kept the same five lines in 148 tokens for nothing. Filter or clear first.
Putting rules that must survive into the chat or into nested, path-scoped files
After compaction only the project-root memory file and unscoped rules come back from disk; chat instructions survive only if the summary copies them, and nested or path-scoped files return only when a matching file is read again.
Reading a passing needle test as proof of long-context reliability
Literal retrieval is the easy case (Haiku 4.5: 20 of 20 up to 114K tokens). Tracking a changing value, or finding something phrased differently from the question, fails earlier, and on small models much earlier.
"Memory layer X scores 90% on LOCOMO, so it is the best"; "memory saves tokens"
Ask who ran it, with which answer model, at what retrieval budget, on which version, against full context: the same product spans 58.44% to 80.32% on the same benchmark (section 8's table). Memory saves tokens per answer but costs model calls per conversation (one per session for Mem0, several per episode for Graphiti); below tens of thousands of tokens of history, pasting it all is cheaper and more accurate.
Interview rehearsal: six design questions

Why does prompt order matter for cost, and what order do you use? Caches match exact prefixes, so a change invalidates everything after it. Tools, system prompt and memory files first, then the history appended one message at a time, anything volatile in the last message. On Anthropic's API a changed tool definition invalidates the whole cache; a read costs 0.1x, a 1-hour write 2x.

Your agent's 40th call costs ten times its 2nd. Where do you look? Per-call usage: is the cache read the previous prompt (if not, something early changes or a turn adds more than 20 blocks past the lookback); the largest tool results; whether old observations are ever cleared; then the startup context. Compaction only if the history itself is the cost.

Masking or summarisation for a coding agent? Masking by default: no extra model call, no invented summary, half the cost and the same solve rate in four of five JetBrains settings. Summarise when old observations hold something the agent still needs that a stub cannot point back to.

When does a subagent help? When a subtask's input is large, its answer small, and the parent will not need the raw input again; it keeps the parent's window small (16K against 64K here) but processes more tokens, and sees none of the parent's history.

How would you test for context rot on your own workload? Cases from your own data at several lengths and depths, with tasks beyond literal lookup (a needle phrased differently, a value that changes, several items to collect), graded automatically, several seeds, compared with the same task short.

How do you tell a memory failure from a model failure? Check whether the evidence reached the prompt. If not, the write or read policy failed; if it did, the reader failed. Section 8's evidence column separates the two without any model.

Recordings: Claude Code 2.1.290, claude -p with --output-format stream-json --verbose --setting-sources project --strict-mcp-config --no-session-persistence, Claude subscription, 6 October 2026; redacted copies, scripts and notes in this page's src/. Text in the recordings is shown as written, except that each em-dash, in model replies and in Claude Code's own tool messages, was replaced by a comma (34 in all, counted by src/redact.py). The memory-layer runs (Mem0 2.2.1, Graphiti 0.30.2, the Letta 0.16.8 server, 6 October 2026) and their redacted recordings are in src/memory_layers/.