GGUF Discovery

Blog & Guides

Systems Research Paper · Agentic LLM Engineering

Context Management in Agent Loops

A complete, citation-driven account of the science of managing context inside agentic loops — why context rots, what the research actually established from MemGPT and Mem0 to Anthropic's context engineering and the Manus KV-cache lessons, how the benchmark wars mislead, and how DeepSeek quietly engineered context management into every layer of its own stack: from MLA and disk-based context caching (2024), through DeepSeek Sparse Attention (2025) and the thinking-context-management rules of V3.2, to the million-token agent context of V4 and the 196B-parameter Engram conditional-memory module of DeepSeek-V4.1-Flash, released September 10, 2026.

100:1
Input-to-output token ratio, Manus agent loops
51.4 → 67.6
BrowseComp, V3.2 with context management
84.2 → 97.0
Multi-Query NIAH with Engram conditional memory
890 B
Global KV bytes per token, V4.1-Flash (438× below V1)
Scope: Research landscape 2023–2026 · DeepSeek stack 2024–2026 · Architecture patterns Method: every number traced to a paper, official blog, or API document Read time: ~65 minutes

§ Abstract & How to Read This Paper

What this paper claims, what it deliberately does not claim, and how the evidence is organized.

An agent, in the definition Anthropic's applied AI team settled on in late 2025, is an LLM autonomously using tools in a loop. That definition has an uncomfortable corollary: the loop is a context-generating machine. Every planning step, every tool call, every raw JSON blob a tool returns, every reasoning trace a thinking model emits lands in the same finite window that must also hold the system prompt and the tool schemas. The window refills on every single call, because the model itself is stateless — each inference starts from zero, and only whatever the harness feeds back persists. Managing that feedback stream is now the difference between an agent that survives fifty turns and one that quietly degrades into a very confident, very expensive random walk.

This paper is written in September 2026, and it covers two intertwined stories. The first is the research landscape: the emergence of context rot as a measured phenomenon, the operating-system metaphor of MemGPT and its descendants (Letta, Mem0, A-MEM, MemOS, Zep), the retrieval rethink that replaced pre-fetching with just-in-time context and direct corpus interaction, the codification of the discipline by Anthropic, LangChain, and the practitioners at Manus, and the benchmark wars on LoCoMo, LongMemEval, BEAM, and DMR — including the uncomfortable fact that most head-to-head numbers in this field are published by the vendors being ranked. The second story is DeepSeek's, because no other lab has pushed context management as deeply into the model itself rather than the harness around it: Multi-head Latent Attention collapsed the KV cache by 93.3% in 2024, disk-based context caching made multi-turn agents dramatically cheaper the same year, DeepSeek Sparse Attention cut long-context attention to O(L·k) in 2025, V3.2 shipped explicit thinking-context-management rules for tool loops and published a controlled study of compaction strategies on BrowseComp, V4 grew the window to one million tokens with reasoning persistence across user turns, and V4.1-Flash (September 10, 2026) added a 196-billion-parameter Engram module that stores knowledge outside the attention stream and retrieves it with O(1) lookups — a memory system trained into the weights rather than bolted on as a retrieval tool.

Accuracy discipline

Every quantitative claim in this paper is traceable to a primary source: an arXiv paper, an official model release note, an API document, or a first-party engineering blog, all current as of September 13, 2026. Where different labs publish conflicting numbers about the same benchmark — and in the memory field they do, constantly — we present each claim with its source and flag the conflict rather than averaging it away. Where a technique is a design pattern rather than a measured result, it is labeled as such. The sources list at the end catalogues all forty-odd references.

How the paper is organized

Part I dissects the problem: what actually fills an agent-loop context, why quality degrades as the window fills (context rot, NoLiMa, lost-in-the-middle), and the economics of prefill-heavy loops, where prefix caching is not an optimization but the business model. Part II maps the research landscape from the 2023 foundations through the 2025–2026 memory-layer explosion and the codification of context engineering as a discipline. Part III is the DeepSeek deep-dive the title promises: version by version, from the dense 4K-context baseline of late 2023 to the Engram architecture of September 2026, with the exact context-management semantics of each release. Part IV assembles the practical payoff: a nine-pattern architecture catalog with trade-offs, a decision framework keyed to named constraints, and production recipes — including working code for the DeepSeek reasoning-retention loop that the V3.2 API contract makes mandatory.

Three audiences were kept in mind while writing. If you build agent harnesses, Parts I, II and IV are your material and Part III is the reference you will cite in design docs. If you train or serve models, Part III is the core and the benchmark chapters will save you from re-running settled arguments. If you are evaluating vendor claims about memory products, Chapter 8 is written specifically for you — it is a field guide to reading benchmark tables whose publishers have skin in the game.

Terminology used throughout. Context management = decisions about what occupies the live window within one session. Memory = what persists across sessions or beyond the window. Context engineering = the discipline covering both, plus system prompts, tool schemas, and retrieval policy. KV cache = the attention key/value state a serving stack computes for a prefix and can reuse when the next call shares that prefix. Reasoning trace / CoT = the thinking tokens a reasoning model emits before its answer, returned by the DeepSeek API as reasoning_content.
Part I · Chapters 1–3

The Problem: The Loop Eats Itself

What actually fills an agent's context window, why more tokens make agents worse, and why the economics of the loop are decided at the KV cache rather than the context window's advertised size.

1 Anatomy of an Agent-Loop Context

The loop, the stateless model, and the five freight cars that fill the window on every single call.

1.1 The loop, and the model that forgets

Strip away the frameworks and every agentic system in production today is the same eight lines of pseudocode: give the model a goal and a set of tools; let it emit either an answer or a tool call; execute the call in some environment; append the result; repeat. Anthropic's engineering essay on context engineering — the one that fixed the vocabulary for the whole industry in September 2025 — compresses this to a definition the field has largely converged on: agents are LLMs autonomously using tools in a loop. The loop is the easy part. The hard part is what the loop does to the model's context, because a transformer holds no state between invocations. Every pass through the loop re-sends everything the model has ever seen in the session: instructions, tool definitions, prior reasoning, prior observations. The model is stateless; the harness is the only memory it has.

This statelessness is the single most important architectural fact in agent engineering, and it was stated plainly by Louis-François Bouchard's team at Towards AI after running instrumented experiments on their open-source AI tutor in 2026: within a session you have context management; across sessions you have memory; and you cannot have good multi-session memory if a single session is already falling apart. The first half of that sentence is this Part I. The second half organizes the entire research field of Part II. Notice what the split implies: the "memory problem" that vendors sell products for is downstream of a more basic engineering discipline — deciding, at every call, which tokens earn their place in the window.

1.2 The five freight cars

Concretely, a production agent-loop call in 2026 typically carries five categories of content, and each has a different growth profile. The table below assembles a realistic accounting from the token budgets published in 2026 retrospectives by the Crux Digits engineering team and the Towards AI tutor experiments.

Sizes compiled from Crux Digits, "Context Engineering: The 2026 Playbook for AI Agents" (July 2026) and Towards AI's tutor instrumentation (August 2026). A "modest version of each" — 5,000 tools + 3,000 retrieval + 4,000 history + three 1,500-token tool results — already totals ~16,500 tokens of working context for one support ticket.
SegmentTypical sizeGrowth behaviorDominant failure mode
System prompt2,000–6,000 tokFlat, but grows every sprint as rules accreteBloat; brittle hardcoded logic
Tool schemas1,000–4,000+ tokFlat per call; explodes with MCP tool sprawlWrong-tool selection, schema violations
Message history500–2,000 tok / turnLinear in turns; compounding across a ticketRarely trimmed even when resolved
Tool outputs500–3,000 tok / callLinear in calls; raw JSON pasted unparsedThe least-examined, most bloated segment
Retrieved context2,000–100,000 tokBursty; pipeline-dependentUnfiltered chunk dumps bury the answer

The surprising empirical finding, reported by the Towards AI team after instrumenting their tutor, is that the segment everyone instinctively trims — chat history — is usually the smallest offender. In their system, each call could pull up to 100K tokens of retrieved course material, and turns were landing around 200K input tokens; the retrieval payloads, not the conversation, dominated the input. Most advice about long agent sessions aims at trimming dialogue; in a retrieval-heavy agent, dialogue is rounding error. This single observation reshapes where engineering effort belongs: at the tool-output boundary and the retrieval filter, not at the transcript.

1.3 The skew: prefill-heavy, decode-light

Chatbot traffic is roughly symmetric — a human types a sentence, the model writes a paragraph. Agent traffic is not. Manus, whose engineering blog in July 2025 became the reference on this, measured their production agents at an average input-to-output token ratio of about 100:1. A typical task takes around 50 tool calls, each of which re-sends the entire accumulated trajectory so that the model can emit a few hundred tokens of structured function call. One consequence is immediate: the cost and latency of an agent is dominated by prefill — the recomputation of everything already known — not by generation. Another consequence is subtler and is the subject of Chapter 3: because each loop iteration shares a prefix with the previous one, the KV cache transforms agent economics from "pay for the whole window every turn" to "pay for the delta," and anything that breaks prefix sharing (a timestamp in the system prompt, a reordered JSON key, a mid-session tool-set change) silently re-inflates the bill by an order of magnitude.

The agent loop as a context-generating machine
User goal + system prompt + tool schemas — the static prefix (keep stable for cache hits)
↓
Model call #n — re-prefills everything; emits thought + tool call (or final answer)
↓
Environment / sandbox — executes the action, returns an observation (often the largest token mass in the turn)
↓
Append thought + action + observation to context — the trajectory grows monotonically; nothing is free to re-derive
↻ repeat until done (or until the window, the budget, or the model's attention gives out)
Fig 1.1 — The loop. Every arrow that points down adds tokens that must be re-prefilled on the next pass. DeepSeek's V3.2, V4, and V4.1-Flash releases each attack a different part of this cycle — reasoning-trace retention (§11), KV-cache size (§13), and prefix reuse (§12) respectively.

1.4 What "context management" therefore means

Across every paper surveyed in Part II, the working definition that survives is negative: context management is the set of mechanisms that keep the effective context — the tokens the model actually re-reads — small, high-signal, and cache-stable, while the logical context — everything the session has ever produced — grows without bound. The mechanisms differ wildly in where they live: in the harness (compaction, note files, sub-agents), in the retrieval layer (just-in-time loading, corpus search), in the serving stack (prefix caching, KV compression), or in the model itself (attention sparsity, trained memory modules). The field's three-year history, traced in Part II, is essentially the migration of these mechanisms from the harness downward into the model. DeepSeek's late-2026 position — the focus of Part III — is the extreme end of that migration: at V4.1-Flash, every layer of the stack participates in context management, and the model itself now carries a dedicated 196B-parameter memory module.

2 Why Naive Context Fails

Context rot, the 32K cliff, lost-in-the-middle, and the attention budget: why bigger windows did not solve the problem.

2.1 Lost in the middle: the 2023 warning shot

The first systematic evidence that long contexts degrade non-uniformly predates the agent era entirely. Liu et al.'s Lost in the Middle study (2023) showed that a model's ability to use a document placed in the middle of a long context drops sharply relative to the same document placed at the beginning or end — a U-shaped positional performance curve. For agent builders the implication was blunt: the trajectory an agent appends turn after turn is, by construction, a pile of information drifting steadily toward the middle of the window, exactly where models read worst. Manus's engineers later turned this observation into an explicit design pattern — their agent rewrites its todo.md every few steps precisely to "recite" the plan into the end of the context, where attention is strongest (§7.6). The fix, in other words, was known before the disease was named.

2.2 Context rot: the 2025 measurement

By 2025, model vendors were shipping million-token windows, and it was tempting to declare the problem solved by brute force. Chroma Research's Context Rot study (July 2025) ended that temptation. The team tested 18 frontier models — including GPT-4.1, Claude 4, and Gemini 2.5 — on deliberately simple retrieval and replication tasks, and found that every single model degraded as input length grew, with accuracy cliffs arriving well before the advertised window limit. A 200K-token window could show serious accuracy loss by 50K tokens of input. Positional effects were severe: placing the relevant fact at positions 5–15 of a twenty-document context cost some models more than 30 accuracy points compared to placing it first or last.

Anthropic's engineering essay, published two months later, gave the phenomenon its working explanation and its budget metaphor. The transformer computes attention over n² pairwise token relationships; as context grows, "the model's ability to capture these pairwise relationships gets stretched thin." Models also train mostly on shorter sequences, leaving them under-adapted to context-wide dependencies. The result is "a performance gradient rather than a hard cliff" — and a finite attention budget that every additional token depletes. Context, in the essay's formulation, must be treated as a resource with diminishing marginal returns, like working memory in humans. The engineering consequence: the smallest set of high-signal tokens that maximizes the likelihood of the desired outcome is the optimization target — not the largest window you can afford.

2.3 NoLiMa: the 32K cliff, measured

The same quarter, Modarressi et al. published NoLiMa ("Long-Context Evaluation Beyond Literal Matching"), a benchmark that tests whether models can answer questions whose wording has minimal lexical overlap with the passage containing the answer — requiring latent, associative inference rather than literal string matching, which standard NIAH tests let models exploit. The result that agent engineers should memorize: across 13 models that all claim 128K+ context support, performance in short contexts (under 1K) was strong, but at 32K, eleven of the thirteen dropped below 50% of their own short-context baselines. Even GPT-4o — one of the top-performing exceptions — fell from an almost-perfect 99.3% baseline to 69.7%.

Why this matters for agent loops specifically

Agentic work is associative by construction. A coding agent must connect an error message in tool output #3 with a variable name introduced in its own reasoning trace from step #17 with a constraint from the original user request — none of which literally match each other. NoLiMa measures exactly the capability that long tool trajectories erode first. A model that holds 99.3% at short range and 69.7% at 32K on associative recall is not "a 128K model"; it is a short-context model with a 128K marketing budget. DeepSeek's response to this class of evidence was architectural rather than rhetorical: the V4 technical report frames its million-token push explicitly around "agentic workflows" needing efficient ultra-long context, not merely nominal support (§12).

2.4 The compounding loop failure

Put the three findings together and the agent-loop failure mode emerges with uncomfortable clarity. An agent accumulates search results, tool outputs, and abandoned reasoning paths as it works. That accumulated noise degrades every subsequent step, not just the final answer — each new decision is made inside a context that is longer, more middle-heavy, and more associatively demanding than the last. The 2026 retrospectives converge on the same production observation: a ticket that reaches turn ten with an untrimmed transcript is simultaneously the most likely to hallucinate and the most expensive call of the conversation to run. Quality and cost fail together, on the same curve, because they share a cause. This is why the field stopped treating "context window size" as the headline specification and started treating context management as the discipline — and it is why every pattern in Part IV exists.

3 The Economics of the Loop

Prefix caching, the 10× cached-input discount, and why 2026's compaction debate is decided by cache arithmetic, not sentiment.

3.1 The cache is the business model

Because agent loops re-send an almost-identical prefix every turn, inference providers let you pay once for it. Anthropic's prompt caching prices Claude Sonnet's cached input tokens at $0.30 per million versus $3.00 uncached — a 10× difference, the exact figure Manus cites when it argues that the KV-cache hit rate is the single most important metric for a production-stage AI agent, directly driving both latency and cost. DeepSeek has operated the same bargain since August 2, 2024, when its Context Caching service launched as a disk-based, automatic feature: cache hits billed at $0.014 per million tokens against $0.14 for a miss — the same 90% discount, available two years before most of the industry's agent frameworks had a caching story. By September 2026, the V4.1-Flash release note states the stakes in one sentence: "Cache-hit charges often account for a large share of agent costs. Compressing the cache cuts those costs significantly."

The mechanics deserve precision, because the engineering rules fall straight out of them. An autoregressive transformer computes attention keys and values (the KV cache) for every token of the prefix; if the next request's prefix is byte-identical up to a point, the serving stack can skip recomputation and bill the reused span at the discounted rate. A single-token difference invalidates everything from that token onward. This yields the rule set Manus published: keep the prompt prefix stable (no second-precision timestamps at the top of the system prompt); make the context append-only; ensure deterministic serialization (many JSON libraries do not guarantee stable key ordering, which silently breaks caches); mark cache breakpoints explicitly where the provider requires them; and if self-hosting on vLLM, enable prefix caching and route requests to consistent workers with session identifiers.

3.2 The 2026 twist: caching inverted the compaction calculus

Compaction — summarizing a conversation as it nears the window limit — has been the reflex answer to long sessions since 2024. In August 2026, the Towards AI team published the measurement that broke the reflex: on their production tutor, evaluated with blind-graded memory probes, under modern prompt caching, keeping the full history beat every summarization strategy they tested on cost, latency, and memory recall simultaneously. The reason is cache arithmetic, not model quality: a summary rewrites the prefix, so you pay full price to recompute everything you just tried to save, and you lose the recall of the exact tokens you discarded. Their production defaults — which looked reasonable — scored 38% on memory probes and cost twice as much as doing nothing, while still producing answers a blind judge rated as good; their conclusion was that this combination is precisely why you cannot eyeball context strategy and must measure it.

What did pay, in the same experiments, was the cheap tier of compaction: capping every tool output at a stable size cut their cost per turn by 38% with no measurable loss in memory recall, because it shrinks the context without rewriting the prefix the cache depends on. The decision rule the team distilled: name your constraint before choosing a strategy — a window that genuinely does not fit, a cached input price above roughly $0.55 per million tokens, or measured quality rot. Each points to a different fix, and only the first one is "summarize."

The DeepSeek angle

DeepSeek's pricing sits far on the favorable side of that $0.55 threshold — V4.1-Flash cache hits are billed at $0.006 per million tokens (peak), roughly a 50× discount on the $0.30 miss price — which makes the keep-everything strategy even more economical on its stack, for loops whose static prefix stays stable. The flip side: at 100:1 input skew, the miss price and the cache-hit rate dominate total agent spend, which is why DeepSeek has spent 2024–2026 compressing the cache itself (MLA, DSA, CSA2, FP4 keys — Part III) rather than only discounting it.

3.3 The three-way trade

Every context-management decision in an agent loop trades three currencies against each other, and the research of 2025–2026 is best read as the systematic exploration of that trade space.

The three currencies fail together in unmanaged loops (§2.4) and are optimized together by every serious pattern in Part IV.
CurrencyWhat drives itWho attacked it in 2025–2026
CostPrefill tokens × price; cache-hit rate; window sizeManus (prefix stability), DeepSeek (MLA/DSA/CSA2, caching), Towards AI (output caps)
LatencyTTFT on re-prefill; retrieval round-trips; memory writesDeepSeek Quick Instruction (§12.4), Mem0 (91% lower p95 vs full-context), Zep (90% latency reduction claim)
QualityEffective context size, position, and signal densityAnthropic (attention budget), Chroma/NoLiMa (measurement), Letta (filesystem beats retrieval tools), DeepSeek V3.2 (reasoning retention)

The rest of this paper is the story of how the field explored that trade space. Part II covers the research; Part III covers the one lab that pushed the frontier into the weights themselves; Part IV assembles the patterns into something you can deploy this week.

Part II · Chapters 4–8

The Research Landscape (2023–2026)

How the field moved context management from an afterthought to its own benchmarked research layer: the OS metaphor, the memory-layer explosion, the retrieval rethink, the codification by Anthropic and the practitioner blogs, and the benchmark wars that every vendor fights on its own turf.

4 Foundations & the Operating-System Metaphor

Memory streams, reflection, skill libraries — and MemGPT's 2023 bet that an LLM could manage its own memory like an OS manages RAM.

4.1 The pre-history: cognitive architectures on GPT-3.5

Before "agent" was an infrastructure category, three 2023 systems established that what you put around the model matters as much as the model. Generative Agents (Park et al., 2023) gave 25 LLM-powered agents a persistent memory stream and a retrieval score computed as a weighted blend of recency, importance, and relevance — plus a reflection mechanism that periodically distilled the stream into higher-level observations. That scoring formula is still the skeleton inside most "agentic memory" products sold in 2026. Reflexion (Shinn et al., 2023) demonstrated verbal self-improvement: an agent that stores its own failure analyses as episodic memory and re-reads them on retry outperforms the same agent without that verbal loop — an early proof that what an agent writes down about its own trajectory changes its future behavior. Voyager (Wang et al., 2023) externalized procedural memory as a growing skill library of verified code, showing that a file-shaped memory an agent both writes and retrieves beats any amount of in-context rehearsal for long-horizon competence. All three prefigure the 2026 consensus patterns: write state down, score it, retrieve it just in time, and reflect on it offline.

4.2 MemGPT: virtual context management (October 2023)

The paper that named the field arrived from UC Berkeley in October 2023. Packer et al.'s MemGPT: Towards LLMs as Operating Systems proposed virtual context management: treat the fixed context window as a limited quantity of main memory, and manage a much larger external context (conversational archives, raw documents) through explicit paging operations — evictions, fetches, and writes that the LLM itself triggers by calling functions. The OS analogy is precise and was meant to be: just as an operating system gives each process the illusion of unlimited RAM by paging to disk, MemGPT gives the model the illusion of unlimited context by paging between the window and external stores, with the model acting as its own memory manager via self-editing function calls.

Two design commitments in the original system matter for everything downstream. First, memory is structured by role, not one undifferentiated log — the system splits a persistent in-window region (core memory, including editable "blocks" like persona and human descriptions) from paged regions (recall storage for conversation history, archival storage for documents). Second, memory operations are agentic: rather than a fixed summarizer running on a timer, the model invokes memory-editing functions when it judges them necessary. Both commitments survive intact in Letta — the company built by the MemGPT team — and in every system that copied the design. The 2025–2026 memory-layer products of Chapter 5 are, to first order, competing answers to one question MemGPT posed: who decides what gets paged — the model, the pipeline, or the graph?

4.3 Letta: blocks, filesystems, and sleep-time compute

Letta, the continuation of MemGPT by its original team, contributed three developments that anchor the "agentic memory" wing of the field. Memory blocks (2025) formalized the in-window core memory as typed, editable, shareable segments — a persona block, a project block, a human block — that the agent rewrites through tool calls and that multiple agents can share, making memory a first-class interface rather than a prompt appendix. Sleep-time compute (arXiv 2504.13171, April 2025) introduced the idea that an agent can think offline about its context between queries: anticipating likely future questions and reorganizing its own memory during idle time, converting wall-clock that used to be wasted into retrieval quality at query time. It is the direct descendant of Generative Agents' reflection, industrialized.

The third contribution is the 2025 benchmark counter-attack. In Benchmarking AI Agent Memory: Is a Filesystem All You Need? (August 12, 2025), Letta attached LoCoMo conversation histories to agents as plain files navigable with grep, search_files, open, and close tools — no memory product at all — and scored 74.0% on LoCoMo with GPT-4o-mini, above the 68.5% Letta cites for the top graph variant in Mem0's own published results. Their conclusion cuts the legs out from under half the memory market: agents are highly effective at filesystem tools (because those are in their training data), so the binding constraint is the agent's ability to manage context, not the sophistication of the retrieval mechanism. Comparing frameworks-and-tools mixes is apples-to-oranges; the Letta Memory Benchmark therefore holds the harness constant and varies the model. The blog also documents a reproducibility dispute worth remembering when reading vendor tables: the MemGPT team could not reconstruct how Mem0's paper produced its MemGPT baseline numbers, and Mem0 did not respond to clarification requests — a preview of Chapter 8's broader lesson.

The durable finding

Across three years and dozens of systems, one result keeps replicating in different costumes: simple, model-familiar interfaces (files, search, self-editing blocks) beat elaborate specialized retrieval machinery for agent memory, because the model's tool-use competence is the scarce resource. The 2026 "direct corpus interaction" result (§6.2) and the Anthropic just-in-time doctrine (§6.1) are the same discovery arriving from three directions — and DeepSeek's Engram (§13) is its architectural extreme: make the lookup so primitive the model does not need a tool at all.

5 The Memory-Layer Explosion

Mem0, A-MEM, MemOS, Zep: four 2025 answers to MemGPT's question, and what each actually demonstrated.

5.1 Mem0: extraction pipelines as a managed service

Mem0 (Chhikara et al., arXiv 2504.19413, published at ECAI 2025) is the industrial wing of the memory movement. Its architecture is a two-phase pipeline rather than an agentic loop: an extraction phase that pulls salient facts from each conversational turn, and an update phase that resolves each new fact against the store with four operations — ADD, UPDATE, DELETE, and NOOP. The paper's headline results on LoCoMo: a 26% relative improvement in the LLM-as-a-Judge metric over OpenAI Memory; a graph-memory variant scoring around 2% higher than the base configuration; 91% lower p95 latency and more than 90% token-cost savings versus a full-context baseline that dumps the whole history into the window. The token-savings figure is the strategically important one: it is the same economics as Chapter 3's caching argument, achieved by not re-sending history at all.

In April 2026, Mem0's engineering team published a State of AI Agent Memory report introducing a redesigned algorithm — single-pass hierarchical extraction with ADD-only storage, plus multi-signal retrieval that fuses semantic, keyword, and entity matching in parallel — and new numbers: 92.5 on LoCoMo at ~6,956 tokens per query, 94.4 on LongMemEval at ~6,787, 64.1 on BEAM (1M scale) and 48.6 on BEAM (10M scale), with the largest category gains on temporal reasoning (+29.6 points) and multi-hop (+23.1). The report is also a useful market document: Gartner's projection that 40% of enterprise applications will integrate task-specific AI agents by end of 2026 (from under 5% in 2025) sits alongside McKinsey's more measured 2025 survey finding (23% of organizations scaling agentic AI, 39% experimenting), and its own integration census — 21 agent frameworks, 20 vector-store backends — maps the ecosystem's fragmentation better than any academic survey could. Its stated open problems (cross-session identity, temporal abstraction at scale, memory staleness) are reproduced in Chapter 16's outlook.

5.2 A-MEM: Zettelkasten notebooks that organize themselves

A-MEM (Xu et al., arXiv 2502.12110, February 2025, NeurIPS 2025) answers MemGPT's question with the model, fully. Its design borrows the Zettelkasten note-taking method: every memory is a structured note (content, keywords, tags, a contextual description generated at insertion time); an evolution mechanism then dynamically generates links between notes and, when a new note arrives, may trigger the re-organization of existing neighbors — memory that restructures itself as evidence accumulates, rather than a store that merely grows. The system demonstrated that dynamically organized, self-linking memories outperform static alternatives on long-horizon conversational QA, and its construction–link–evolve pipeline became the template for the "agentic memory" product category that followed it. Conceptually, A-MEM is the retrieval graph the Mem0 graph variant buys, minus the pipeline — the agent is the pipeline.

5.3 MemOS: memory as a schedulable resource

MemOS (Li et al., arXiv 2507.03724, 2025) pushes the operating-system metaphor past paging into scheduling. Its core abstraction, the MemCube, unifies three kinds of memory under one management layer: plaintext memory (facts and text, as every other system stores), activation memory (KV caches retained and reused across calls), and parametric model memory — with the system deciding transformations between them, scheduling when each tier is consulted, and treating memory as a first-class system resource with its own governance. The ambition is to make "memory management" a systems discipline with the same rigor as memory management in an OS: admission policies, tiering, and lifecycle management rather than a pile of vectors. The KV-cache-as-memory move is the one with teeth — it is the same insight DeepSeek industrialized at the serving layer (Part III), and that production stacks like LMCache pursue for open-weight models.

5.4 Zep: the temporal knowledge graph

Zep (arXiv 2501.13956, January 2025) rejects the vector store and the flat note alike, organizing memory as a temporally-aware knowledge graph built by its engine, Graphiti. Episodes, entities, and relations are extracted from conversations and business data as they stream in; each fact carries validity intervals, so the graph knows when something was true — the mechanism NoLiMa showed literal-matching systems lack, applied to memory rather than windows. The paper's reported results: 94.8% accuracy on the DMR benchmark, beating MemGPT's 93.4% (a benchmark the MemGPT team itself created), and on LongMemEval, accuracy improvements of up to 18.5% with response latency reduced by 90% versus full-context baselines. Zep's team also published the field's most aggressive counter-benchmarking: a May 2025 blog arguing Mem0's SOTA claim didn't hold under re-testing, reporting Zep outperforming Mem0 by 24% on DMR — while Mem0's 2026 report returns fire with LoCoMo configurations where Zep scores 80.32–83% against Mem0's 92.5. Chapter 8 treats this crossfire as data, not noise.

All figures as reported by each system's own paper or blog; see §8.3 before quoting any of them in a purchase decision.
SystemMemory abstractionWho manages memorySignature reported result
MemGPT / Letta (2023–25)Hierarchy: in-window blocks + paged archivesThe model, via self-editing toolsUnbounded-context design; filesystem-only agents hit 74.0% LoCoMo (GPT-4o-mini)
Mem0 (2025)Fact store + optional graphExtraction/update pipeline+26% vs OpenAI Memory (LLM-judge, LoCoMo); >90% token savings vs full-context; 92.5 LoCoMo (2026 alg.)
A-MEM (2025)Self-linking Zettelkasten notesThe model (note construction, linking, evolution)Dynamic organization beats static stores on long-horizon QA
MemOS (2025)MemCube: plaintext + activation (KV) + parametricOS-style schedulerUnified lifecycle management across three memory tiers
Zep / Graphiti (2025)Bi-temporal knowledge graphGraph extraction engine94.8% DMR (vs MemGPT 93.4%); LongMemEval +18.5% at −90% latency

6 Retrieval Rethought

From pre-fetching everything to just-in-time loading, direct corpus interaction, and quarantined sub-agent contexts.

6.1 Just-in-time context: the Anthropic doctrine

The dominant retrieval pattern of the RAG era was pre-inference: embed everything, fetch the top-k chunks, stuff them into the prompt before the model thinks. Anthropic's September 2025 essay documented the shift the field was already making: agents that maintain lightweight identifiers — file paths, stored queries, web links — and pull the referenced data into context at runtime, only when needed. Claude Code is the flagship example: it performs complex analysis over large databases by writing targeted queries, storing results, and using head and tail over files — never loading the full data objects into the window. The essay frames this as cognitively honest ("we don't memorize corpuses; we build filing systems") and operationally superior: the metadata of a reference (a file's name, its directory, its timestamp) carries signal that a stuffed chunk does not, and the agent's exploration becomes progressively disclosing — each read informs the next query.

6.2 Direct corpus interaction: agents grep better than embeddings rank

The 2026 research result that formalized the pattern is Beyond Semantic Similarity: Rethinking Retrieval for Agentic Search via Direct Corpus Interaction (arXiv 2605.05242, May 2026). Its proposal, DCI, gives the language agent an interface to query raw text directly — search, filter, and read over the corpus itself — instead of consuming a pre-ranked embedding shortlist. The empirical finding: agents using DCI outperform traditional similarity-based retrieval pipelines on agentic search tasks, because the agent can reformulate its queries mid-search (the same competence Letta's filesystem experiment isolated) while embedding pipelines rank once, blind to what the agent has since learned. Combined with Letta's 74.0% filesystem result, the 2026 picture is coherent: retrieval is no longer a pre-processing stage but an agentic behavior, and the corpus interface — files and grep — is the one models already know from their coding post-training.

6.3 Sub-agent architectures: isolation as a context strategy

The third retrieval-side pattern is not retrieval at all: it is context quarantine. Anthropic's essay describes the orchestrator-worker design in which specialized sub-agents take focused questions into clean windows, explore exhaustively (tens of thousands of tokens each), and return condensed summaries of 1,000–2,000 tokens to the lead agent, which thereby never sees the noise. Their multi-agent research system is the reference deployment. The warning label comes from the practitioner side: Philipp Schmid's December 2025 retrospective names the failure mode context pollution — when sub-agents share one context, you pay the KV-cache penalty anyway and the shared noise confuses every model reading it. Isolation only pays when the boundary is real: fresh window per sub-agent, distilled handoff at the seam. DeepSeek's V4 harness takes the same discipline to training time, with the DSec sandbox platform evaluating agentic rollouts in isolated execution environments (§12.5).

6.4 The four levers: LangChain's consolidation

LangChain's engineering team consolidated the whole design space into four verbs that now organize most production agent frameworks: Write (persist context outside the window — scratchpads, memory files, running plans), Select (pull the right information in at the right moment — tools, retrieval, file reads), Compress (reduce what is already in the window — summarize resolved turns, trim tool outputs), and Isolate (split work across separate windows — sub-agents, sandboxed steps). Their January 2026 "Context Management for Deep Agents" post describes the Deep Agents SDK implementing exactly these through offloading, summarization, and filesystem abstraction, and LangGraph's checkpointed state graphs became the 2026 default substrate for auditable long-running agents because the four operations map onto first-class graph constructs. The four-lever frame is the taxonomy Part IV's pattern catalog is organized around — it is descriptive, not competitive, and nothing in the catalog falls outside it.

7 Context Engineering Grows Up

Karpathy names it, Anthropic codifies it, ACE makes it self-improving, and Manus ships the production field manual.

7.1 From prompt engineering to context engineering

On June 25, 2025, Andrej Karpathy posted the tweet that renamed the discipline: "+1 for 'context engineering' over 'prompt engineering'… the delicate art and science of filling the context window with just the right information for the next step." The renaming mattered because it relocated the engineering problem. Prompt engineering optimizes one static instruction; context engineering manages the full, changing set of information an agent sees at every step of a multi-turn task — system prompt, tools, examples, memory, history, runtime data — as one curated, dynamically assembled artifact. Anthropic's essay adopted the frame in September 2025 and gave it the working definition used throughout this paper: the set of strategies for curating and maintaining the optimal set of tokens during inference, iteratively, on every call.

7.2 Compaction, done carefully

Anthropic's essay treats compaction as the first lever of long-horizon coherence: as a conversation nears the window limit, summarize its contents and reinitiate a new context from the summary. The Claude Code recipe is concrete enough to implement verbatim: pass the message history to the model to summarize, preserving architectural decisions, unresolved bugs, and implementation details while discarding redundant tool outputs and messages, then continue with the compressed context plus the five most recently accessed files. The essay is equally explicit about the risk: overly aggressive compaction loses "subtle but critical context whose importance only becomes apparent later," and the recommended tuning order is recall-first (capture everything relevant), then precision (eliminate the superfluous). The lightest-touch form — tool result clearing, deleting the raw payload of deep-history tool calls whose fact has already been absorbed — shipped as a platform feature on the Claude Developer Platform in September 2025 (with the documented caveat that cleared spans invalidate the corresponding cached prefix). DeepSeek's V3.2 ran the same play at the model level, discarding reasoning traces at user-turn boundaries while preserving tool-call history — and then benchmarked the alternatives on BrowseComp; both stories appear in Chapter 11.

7.3 Structured note-taking: the NOTES.md pattern

The essay's second pattern is structured note-taking, or agentic memory: the agent regularly writes notes to files outside the window and pulls them back in later — a to-do list in Claude Code, a NOTES.md in a custom agent — "tracking progress across complex tasks, maintaining critical context and dependencies that would otherwise be lost across dozens of tool calls." The demonstration that convinced the skeptics is Claude playing Pokémon: with no prescribed memory format, the agent maintained precise tallies over thousands of game steps ("for the last 1,234 steps I've been training my Pokémon in Route 1, Pikachu has gained 8 levels toward the target of 10"), drew maps of explored regions, and recorded combat strategies; after context resets it re-read its own notes and resumed multi-hour objectives. The production version is Anthropic's memory tool (public beta since the Sonnet 4.5 launch): a file-based system that lets agents build knowledge bases over time and reference previous work without keeping it all in context.

7.4 Agentic Context Engineering: the playbook that rewrites itself

The most conceptually aggressive 2025 research result is ACE (Zhang et al., arXiv 2510.04618, October 2025; Stanford, SambaNova, UC Berkeley). ACE splits the context-improvement job across three roles: a Generator produces task trajectories; a Reflector distills concrete lessons from what worked and what failed; and a Curator folds those lessons back into a structured, evolving context playbook — the system prompt stops being a static artifact written once by an engineer and becomes a self-improving artifact maintained by the system. On their evaluations, ACE-managed contexts beat strong static baselines without a single gradient update: +10.6% on agent tasks and +8.6% on financial-analysis tasks. The model did not get smarter; its context did. ACE is the bridge between this chapter and Part III: it treats context itself as trainable state — the same philosophical move DeepSeek made when it trained a 196B-parameter memory module into the weights (§13).

7.5 Model-native features: the provider layer joins in

By late 2025, context management had stopped being purely a harness discipline: the model APIs themselves began shipping native mechanisms. Anthropic's September 2025 release wave brought the context-editing capability set — tool result clearing and thinking-block clearing with cache-interaction semantics documented in the platform's context-window guide — alongside the memory tool. The platform docs formalized the full accounting: everything in the request counts toward the window, including tool definitions and thinking tokens, with cache reads split out in the usage field. Claude's chat interface manages the window on a rolling first-in-first-out basis — the interface-level version of truncation. The significance for architects: the boundary between "harness pattern" and "model feature" is dissolving, and procurement decisions now include which native context primitives a provider exposes alongside price and quality. DeepSeek's reasoning-retention contract (§11.3) is exactly such a primitive — an API-level context policy with an error code attached.

7.6 The Manus field manual: seven rules from production

The single most-cited practitioner document of the era is the Manus engineering blog, "Context Engineering for AI Agents: Lessons from Building Manus" (Yichao 'Peak' Ji, July 18, 2025). Its rules deserve quoting in structure, because each one encodes a failure their team hit in production:

  • Design around the KV-cache. The hit rate is the number-one production metric; keep the prefix stable, the context append-only, serialization deterministic; set explicit cache breakpoints; use consistent session routing. (The 100:1 ratio and the 10× cached-input price from Chapter 3 are this rule's economic foundation.)
  • Mask, don't remove. Dynamically adding or removing tools mid-loop invalidates the cache from the tool-definition position and strands history that references now-undefined tools, producing schema violations and hallucinated calls. Instead, Manus constrains the action space at decode time — a context-aware state machine that masks tool logits via response prefill, exploiting the three standard function-calling modes (auto / required / specified), plus naming conventions (browser_*, shell_*) that make group constraints mechanical.
  • Use the file system as context. Observations can be huge; performance degrades with length; long inputs are expensive even cached. So: "the file system as the ultimate context — unlimited in size, persistent by nature, and directly operable by the agent itself," with compression always restorable (drop the web page, keep the URL; drop the document, keep the path).
  • Manipulate attention through recitation. The todo.md behavior is deliberate: by rewriting the task list every few steps, the agent "recites" its objectives into the end of the context — recent positions, where attention is strongest — countering lost-in-the-middle and goal drift across ~50-tool-call trajectories.
  • Keep the wrong stuff in. Erasing failures removes the evidence the model needs to update its beliefs away from the failed action; error recovery is treated as a marker of genuinely agentic behavior. (Contrast the common instinct to hide errors and retry "clean.")
  • Don't get few-shotted. A context full of near-identical action–observation pairs teaches the model to imitate the pattern even when it is no longer optimal; Manus injects structured variation (serialization templates, phrasing, ordering) to break the mimicry.
  • Expect to rebuild. Their agent framework was rebuilt four times as better context shapes emerged — their name for the process, "Stochastic Graduate Descent," is the field's most honest methodology statement.
One caution inside the manual

Manus's logit-masking recipe assumes control of the decoding loop (self-hosted or prefill-friendly providers) and their file-system doctrine assumes a sandbox with real storage. Both hold for their product. In a managed-API setting, the equivalents are weaker: tool-set stability plus provider-native clearing features, and object-store references instead of a live filesystem. The rules survive the translation; the mechanisms do not.

8 The Benchmark Wars

LoCoMo, LongMemEval, BEAM, DMR: what each benchmark actually measures, and how to read vendor tables whose publishers are also contestants.

8.1 What the four benchmarks measure

Category counts as reported in Mem0's 2026 state-of-memory report and the original papers.
BenchmarkScaleWhat it testsIntroduced by
LoCoMo1,540 questions, 4 categoriesRecall from multi-session conversations: single-hop, multi-hop, open-domain, temporalAcademic (2024); adopted as the memory default
LongMemEval500 questions, 6 categoriesSingle-session user/assistant/preference recall, knowledge update, temporal reasoning, multi-sessionAcademic (2024); enterprise-oriented
BEAM1M and 10M token scalesTen categories including abstention and contradiction resolution, at corpus scales no window solves2025-era; the production-scale test
DMRHotpotQA-derived multi-sessionDeep memory retrieval in conversational form; the MemGPT/Letta lineage's home benchmarkLetta (MemGPT team)

The evaluation stack that consolidated around these benchmarks combines five dimensions — BLEU, F1, an LLM-judge score, tokens consumed per query, and wall-clock latency — precisely so that a system cannot win on accuracy while quietly spending 26,000 tokens per question. The discipline of reporting token consumption per query is the benchmark suite's most useful product: it is the Chapter 3 economics, instrumented.

8.2 The crossfire, documented

Here is the same field as reported by its contestants, side by side, with sources named. The numbers are all real; the configurations are not comparable; that is the point.

Every cell is a first-party publication about a market they sell into. The variance between "92.5" and "74.0" for overlapping systems is mostly model choice, judge model, retrieval configuration, and units (per-conversation vs per-query tokens).
ClaimReported numberPublished byThe counter-claim
Mem0 is SOTA on LoCoMo92.5 (2026 algorithm, ~6.9K tok/query); +26% vs OpenAI Memory (2025 paper)Mem0 paper & 2026 reportZep's blog: Mem0's numbers don't hold under re-test; Zep +24% on DMR (May 2025)
Zep leads DMR and LongMemEval94.8% DMR; LongMemEval +18.5%, −90% latencyZep paper (Jan 2025)Mem0's 2026 table: Zep at 80.32–83% LoCoMo (config-dependent), 71.2 LongMemEval (GPT-4o)
A filesystem beats memory tools74.0% LoCoMo, GPT-4o-mini, no memory productLetta (Aug 2025)Also documents that MemGPT baselines in Mem0's paper were not reproducible; clarification requests unanswered
OpenAI Memory52.9 LoCoMoCarried in Mem0's tablesMem0's own 2026 report flags it: "not independently confirmed for this report… confirm sourcing before publishing"

8.3 How to read a memory benchmark in 2026

The wars teach a reading protocol that costs nothing and prevents most expensive mistakes. Check the model under the harness. LoCoMo scores move tens of points with the driver model (Letta's 74.0 was deliberately run on GPT-4o-mini to match a disputed baseline; Mem0's 92.5 runs on a frontier stack). Check the judge. LLM-as-a-Judge scores inherit the judge's biases, and different papers use different judges. Check the units. Mem0's 2025 paper reported tokens per conversation (~26,000 for full-context) while the 2026 algorithm reports tokens per retrieval call (~6,956) — "different units measuring the same underlying efficiency," in their own footnote. Check who ran it. The three most-cited head-to-head tables in the field were published by Mem0, Zep, and Letta, each of which sells the winner. Prefer dynamic and holistic evaluation. Letta's Memory Benchmark creates memory interactions on the fly (defeating training-set contamination and testing management, not just retrieval), and Terminal-Bench-style task benchmarks measure memory as it actually manifests: an agent holding task state across a long-running job. And when a vendor's number matters to a decision, re-run it — Mem0 open-sourced its benchmark suite (github.com/mem0ai/memory-benchmarks) for exactly this reason, and the Towards AI team's 2026 finding that their own production defaults looked fine and measured badly is the cautionary tale for skipping the step.

Part III · Chapters 9–14

DeepSeek's Work (2023 → Late 2026)

One lab's version-by-version engineering of context management into the model itself: MLA and disk caching in 2024, DeepSeek Sparse Attention and thinking-context-management rules in 2025, the million-token agent context of V4 in April 2026, and the Engram conditional-memory module of V4.1-Flash in September 2026.

9 Baseline Era: MLA & Context Caching

2023–2024: the dense 4K-context starting point, the 93.3% KV compression that made long context affordable, and the disk cache that made agent loops cheap.

9.1 The 2023 baseline: no context management at all

DeepSeek LLM 7B and 67B (November 2023) are the honest baseline for this history: dense transformers with standard attention (MHA in the 7B, grouped-query attention in the 67B), a 4K-token context window, and not a single mechanism aimed at context management. Every problem documented in Part I existed here in its purest form: a multi-turn tool loop hit the window after a handful of observations; attention cost grew quadratically with the trajectory; the only available strategies were truncation and hope. The line matters because the rest of this Part is measured against it: the V4.1-Flash release materials compute their KV-cache footprint against a "~390,000 bytes per token" figure that corresponds to this era's full-precision multi-head attention across a deep stack — a 438× gap that closed in under three years (§13.4).

9.2 V2 (May 2024): MLA makes the KV cache 93.3% smaller

DeepSeek-V2 introduced Multi-head Latent Attention (MLA), the first architectural bet that context economics belong inside the model. MLA jointly compresses the keys and values of every attention head into a small latent vector cached per token, decompressing them on the fly during attention; the RoPE positions ride in a small decoupled stream. The paper's own headline numbers: a 93.3% reduction in KV-cache size relative to the 67B dense baseline's attention, a 5.76× maximum decoding throughput improvement under cache-bound serving, and 42.5% lower training cost for comparable generation quality. In V3's 61-layer configuration, the per-token KV footprint works out to roughly 70 KB in bf16, against ~500 KB for an 8-group GQA and ~4 MB for full MHA — the compression that made "re-prefill the whole trajectory every turn" survivable at all. The window was already there — V2 itself supported 128K context, YaRN-extended from the 4K pre-training length with NIAH results reported clean across the range — so MLA's decisive contribution was not the window but the cost curve of filling it. Every model in the V3 line inherited the mechanism (the V4 generation replaced it with its hybrid compressed-attention stack, §12), and every serving stack that runs open-weight agents at scale — vLLM, SGLang, LMCache offloading — is built around MLA-shaped caches.

9.3 Context Caching (August 2024): the agent-loop business model, shipped

On August 2, 2024, DeepSeek's API launched Context Caching: a disk-based, automatic cache of KV states for previously seen prefixes, billed at $0.014 per million tokens on hits against $0.14 on misses — the 90% discount that Chapter 3 established as the economic core of agentic inference. The engineering choice to make it automatic is worth pausing on: with no cache breakpoints to manage and no manual invalidation API, every multi-turn conversation and every agent loop with a stable prefix benefits by default, which is precisely the population Manus later identified as the ones whose cost is decided by hit rate. Two years on, the pricing page has only sharpened the bargain — V4.1-Flash cache hits are $0.006 per million tokens at peak — and the release note for V4.1-Flash explains why the discount keeps deepening: cache-hit charges often account for a large share of agent costs, and compressing the cache cuts those costs. The compression is the next chapter.

9.4 V3 and R1: the window grows, and reasoning makes context heavier

DeepSeek-V3 (December 2024) kept the 128K context and added Multi-Token Prediction — which sped decode (1.8× tokens-per-second with the MTP module as a speculative decoder at an 85–90% acceptance rate) but left context management to the harness, as before. R1 (January 2025) then changed the problem's shape: a reasoning model emits long chain-of-thought before every answer, and in agent loops that reasoning lands in the window alongside tool outputs. The R1-era serving contract was the blunt one: reasoning content was discarded at each new user message. The V3.2 paper later named the cost of that policy precisely — "the model is forced to redundantly re-reason through the entire problem for each subsequent tool call" (§11.1) — making R1's contract the explicit baseline that DeepSeek's next two releases would be engineered against. The lesson generalizes: reasoning traces are context freight, and a context-management story that ignores them is already obsolete.

10 V3.2-Exp: DSA, the Cheap Long Context

September 2025: the lightning indexer, O(L·k) attention, a 5× decode-cache cut at 131K, and a 50%+ price drop — the substrate every later context feature stands on.

10.1 The attention tax, and how DSA removes it

The V3.2 release line began with DeepSeek-V3.2-Exp on September 29, 2025, carrying DeepSeek Sparse Attention (DSA). Vanilla attention scores every query against every key — O(L²) in sequence length — which is exactly the tax an agent's growing trajectory pays on every turn. DSA adds a lightning indexer: a tiny, FP8-quantized scoring network (64 shared heads of 128 dimensions, ReLU-activated) that computes a cheap relevance score between every query and every key, after which each query attends only to its top-k keys (k = 2048) — cutting the main model's attention complexity from O(L²) to O(L·k), with k independent of context length. The indexer itself still scans the sequence, but at a fraction of the main model's per-pair cost, and it runs in a masked-MHA shortcut regime for short prompts where full attention is cheaper than selection.

10.2 The cache arithmetic, in bytes

For serving, DSA split the KV budget in two: the compressed MLA entries (which the paper's deployment numbers put at ~656 bytes per token per layer in the production stack: 512 bytes of FP8 latent plus scales, and 128 bytes of bf16 RoPE keys) and the indexer scores, which are small enough to store at ~132 bytes per token per layer (128 bytes FP8 + scale). Because only the top-k entries are needed at decode, the working set at a 131K-token context shrinks from ~5.2 GB to ~1.1 GB per batch element in the deployment's accounting — a ~5× reduction in decode-time cache traffic, delivered by DeepGEMM's fp8_mqa_logits indexer kernels and a sparse FlashMLA attention kernel. Independent long-context evaluations after release (Artificial Analysis' long-context reasoning suite) put V3.2-Exp four points above V3.1-Terminus in reasoning mode — evidence that the sparsity did not trade quality for the efficiency. The pricing followed the cost: input and output prices dropped by more than 50% (output to $0.28 per million tokens), the first time a DeepSeek architecture release was explicitly priced as an agent-infrastructure event.

Why an efficiency chapter belongs in a context-management paper

DSA is not a "context strategy" in the harness sense — nothing is summarized, dropped, or retrieved. It belongs here because it changes the exchange rate of every strategy that is: after DSA, an extra 100K tokens of retained trajectory cost O(k) additional attention rather than O(L), and the persistent cache costs bytes rather than DRAM budgets. DeepSeek's context-management decisions from here on — retaining reasoning traces (V3.2), never dropping anything (V4), paging KV to SSD with bounded replay (V4.1-Flash) — are only rational because the substrate became this cheap. Efficiency is a context-management strategy when the context is the cost.

11 V3.2: Thinking Context Management

December 2025: the first model with an explicit context-management policy for tool loops, an API contract with a 400 error attached, and a controlled study of compaction strategies on BrowseComp.

11.1 The policy: retain reasoning across tool calls, discard on user turns

DeepSeek-V3.2 (December 1, 2025; arXiv 2512.02556) is, by its own framing, a "reasoning-first model built for agents," and its signature context-management contribution is Section 3.2.1, Thinking Context Management. The reasoning is stated as a rejection of the R1 baseline: discarding reasoning content whenever a new round of messages arrives "results in significant token inefficiency," forcing the model to "redundantly re-reason through the entire problem for each subsequent tool call." The replacement policy, tuned specifically for tool-calling scenarios, has three rules:

  • Rule 1 — tool outputs do not wipe reasoning. Historical reasoning content is discarded only when a new user message enters the conversation. If only tool-related messages (e.g., tool outputs) are appended, the reasoning content is retained throughout the interaction.
  • Rule 2 — user turns are the reset boundary. When reasoning traces are removed (at a genuine user turn), the removal is wholesale: the model re-reasons for the new request.
  • Rule 3 — tool history outlives reasoning. When reasoning traces are removed, the history of tool calls and their results remains preserved in the context.

The paper is candid about the boundary condition: agent frameworks that simulate tool interactions via user messages — it names Roo Code and Terminus — may not trigger the tool-calling path and therefore "may not fully benefit from our enhanced reasoning persistence"; for such architectures DeepSeek explicitly recommends non-thinking models. This is a documentable, testable semantic, and it is the first time a frontier lab shipped a context-management policy as a model behavior rather than a framework convention.

11.2 Training the behavior in

The policy is not a post-hoc serving trick; it is trained. V3.2's post-training unified reasoning and tool-use in single trajectories, starting from a cold-start that prompted a V3-style model to interleave multiple tool calls inside its reasoning, then scaling through reinforcement learning on synthesized agentic tasks: over 1,800 distinct environments and 85,000 complex instructions, spanning search, code-engineering, and code-interpretation tasks. The release notes headline it as "our first model to integrate thinking directly into tool-use," supporting tool-use in both thinking and non-thinking modes. The high-compute sibling of the release, V3.2-Speciale, deliberately omitted tool use (API-only, at the time) to push reasoning benchmarks to gold-medal level — the split itself illustrating that agentic context behavior and pure reasoning length were being optimized as separate axes. On the agentic side of that split, V3.2's reported scores include Terminal-Bench 2.0 at 46.4 (against Claude-4.5-Sonnet's 42.8, GPT-5's 35.2, and Gemini-3.0-Pro's 54.2 in the same table), SWE-Verified at 73.1, and τ²-Bench at 80.3 — with the paper's framing that V3.2 "significantly advances the agentic capabilities of open models" while remaining "a highly cost-efficient alternative in agent scenarios."

11.3 The API contract: reasoning_content is mandatory in tool loops

The same policy is enforced at the API surface, in DeepSeek's thinking-mode guide. In thinking mode the model's chain-of-thought is returned as reasoning_content, a sibling of content. Whether it persists into the next request's context depends on the request's shape:

  • With the tools parameter present (agent loops): the reasoning_content of all previous turns must be passed back — even for turns where the model performed no tool call. If the harness drops it, the API returns a 400 error.
  • Without tools (plain chat): the reasoning content of prior turns is ignored even if passed — the chat-side discard rule, applied server-side.

This is the cleanest instance in the industry of context management as a contractual API primitive: the retention policy from Section 3.2.1, expressed as request-validation semantics with an error code. Chapter 16's recipe implements the compliant loop.

11.4 The experiment: compaction strategies under a compute budget

Section 4.4 of the V3.2 paper — Context Management of Search Agent — is the part agent architects should read twice, because it is the one controlled, published comparison of harness-level context strategies from a frontier lab. The motivation: even at 128K, agentic search workflows "frequently encounter maximum length limitations that prematurely truncate the reasoning process," capping test-time compute. The intervention, triggered when token usage exceeds 80% of the context window:

  • Summary — summarize the overflowed trajectory and re-initiate the rollout. Measured effect: average steps extended to 364, with performance improving to up to 60.2 on BrowseComp — effective but token-expensive relative to its gains.
  • Discard-75% — drop the first 75% of the tool-call history to free space.
  • Discard-all — reset the context by discarding all previous tool-call history; the paper notes the similarity to the new-context tool Anthropic shipped in 2025. Despite its brutality, it "performs well in both efficiency and scalability," reaching 67.6 on BrowseComp with significantly fewer steps than the parallel baseline.
  • Parallel-fewest-step (the comparison baseline) — sample N independent trajectories and keep the one that finishes in the fewest steps.

Two results deserve emphasis. First, the headline: DeepSeek-V3.2's BrowseComp moves from 51.4 to 67.6 when context management is applied (the table's asterisked number; the same table lists Kimi-K2-Thinking with 60.2 under its own context management). Context management is not an operational nicety — on this benchmark it is worth +16.2 points, a bigger jump than most model-generation improvements deliver. Second, the counter-intuitive ordering: the crudest strategy beat the sophisticated one. Discard-all (67.6) outscored Summary (60.2) while using far fewer tokens, "comparable to parallel scaling while using significantly fewer steps." The paper's own conclusion frames the design space: test-time compute can scale serially through context management or in parallel, and "finding the optimal combination of serial and parallel scaling… remains a crucial direction for future work."

Do not over-generalize the Discard-all win

The experiment is scoped to search agents on BrowseComp, where early tool calls (search results long superseded) are close to pure noise — the regime where aggressive dropping provably helps. A coding agent's early tool calls (the failing test it must keep in view) are the opposite regime; Manus's "keep the wrong stuff in" rule (§7.6) exists precisely for it. The transferable finding is not "discard everything"; it is measure the strategies under your own compute budget, because the ordering is task-dependent and the naive orderings are wrong.

12 V4: A Million Tokens Built for Agent Loops

April 2026: the preview that reframed context as the product — reasoning persistence across user turns, CSA+HCA hybrid attention, Quick Instruction's cache-native auxiliary tasks, and a 500-step/512K agent harness.

12.1 The reframing: "a million-token context that agents can actually use"

DeepSeek-V4 arrived as a preview on April 24, 2026 (technical report arXiv 2606.19348) in two configurations — V4-Pro at 1.6T total parameters (49B activated) and V4-Flash at 284B (13B activated) — and with a framing that is itself a data point for this paper's thesis: the Hugging Face announcement titled it "a million-token context that agents can actually use." The efficiency claims that justify the phrasing, at one million tokens of context: V4-Pro requires 27% of the single-token inference FLOPs and 10% of the KV cache that DeepSeek-V3.2 would need; V4-Flash runs at 10% and 7% respectively. The report's comparison table scores the V4-Pro-Max configuration at 83.5 MMR on Long-MRCR-1M and 62.0 ACC on CorpusQA-1M — trailing Opus-4.6 (92.9 and 71.7) but demonstrating retrieval that still functions at the 1M scale: the quality-side evidence that the million tokens are usable, not nominal. The architecture behind the numbers is a hybrid attention stack (Compressed Sparse Attention interleaved with a Heavily Compressed Attention) whose details are documented in the V4 report's architecture chapter; for this paper, the relevant point is what the efficiency buys: enough headroom to stop discarding context.

12.2 Interleaved thinking, refined for agents

Chapter 11 documented V3.2's policy: reasoning persists across tool calls but is flushed at user-message boundaries — which, the V4 report notes, "still caused unnecessary token waste in complex agentic workflows: each new user turn would flush all accumulated reasoning content, forcing the model to reconstruct its problem-solving state from scratch." V4's refinement splits the semantics by scenario:

  • Tool-calling scenarios: all reasoning content is fully preserved throughout the entire conversation — including across user-message boundaries — maintaining "a coherent, cumulative chain of thought over long-horizon agent tasks."
  • General conversational scenarios: the V3.2 rule stands (reasoning from prior turns is dropped when a new user message arrives), "keeping the context concise for settings where persistent reasoning traces provide limited benefit."

The caveat survives verbatim: frameworks that fake tool calls as user messages (Terminus is the named example again) do not trigger the tool-calling path and get the conversational semantics instead — and DeepSeek continues to recommend non-thinking models for those architectures. Read together, Chapters 11 and 12 give a lab-internal, two-step evolution of the same policy, each step justified by measured token waste in the previous one: R1's flush-everything → V3.2's flush-at-user-turns → V4's keep-everything-when-tools-are-real. No other frontier lab has published this reasoning trail.

12.3 The agent harness, stated in the report

DeepSeek's agent evaluations in the V4 report use an internally developed framework whose configuration is itself a reference design: a minimal tool set — a bash tool and a file-edit tool; a maximum of 500 interaction steps; a maximum context of 512K tokens (half the model's window). The reported results include Terminal-Bench 2.0 at 67.9 for the V4-Pro-Max configuration (the report separately cites approximately 72.0 on the Verified subset for V4-Pro) and SWE-Verified at 80.6, with search-agent tasks (BrowseComp, HLE with tools) run in a separate websearch-plus-Python harness — and, notably, BrowseComp evaluated with "the same discard-all context management strategy as DeepSeek-V3.2": the §11.4 finding carried forward into the next generation. Behind the evaluations sits real infrastructure: the report describes DSec (DeepSeek Elastic Compute), a production sandbox platform of three Rust services — API gateway, per-host agent, and cluster monitor — running agentic post-training and evaluation rollouts on the 3FS distributed filesystem. The training pipeline fed it a two-stage paradigm (domain specialist models trained with SFT+RL, then unified by on-policy distillation) with agent capability as an explicit domain, and the mid-training data mix gained agentic and long-document corpora. The pattern to notice: by 2026, DeepSeek treats agent-loop context behavior as a first-class training objective with its own data, infrastructure, and evaluation harness — not a post-deployment afterthought.

12.4 Quick Instruction: auxiliary tasks that reuse the cache

The V4 report's most quotable piece of systems craft targets a cost nobody benchmarks: the small model that production chat products run before the main model to classify the request (does this need a web search? what domain is it? should this URL be fetched?). That model cannot share the main model's KV cache, so the whole prefix is prefilled twice. Quick Instruction eliminates the second prefill by appending dedicated special tokens directly to the input sequence — <|action|>, <|title|>, <|query|>, <|authority|>, <|domain|>, <|read_url|> — each bound to one auxiliary task. Because the tokens ride on the already-computed KV cache, the auxiliary outputs (search-trigger decisions, generated queries, authority and domain classifications, URL-read decisions) are produced in the same forward pass, in parallel, "completely avoiding redundant prefilling," cutting user-perceived time-to-first-token, and retiring the extra model from the stack. It is the same insight as Manus's stable-prefix rule, inverted: instead of protecting the cache from auxiliary work, move the work into the cache. The same release also moved tool-call serialization to an XML format that "mitigates escaping failures and reduces tool-call errors" — protocol-level context hygiene, the unglamorous kind that production uptime is made of.

DeepSeek-OCR, the detour worth one paragraph. October 2025's DeepSeek-OCR paper (arXiv 2510.18234) explored "Contexts Optical Compression" — feeding long text to the vision encoder as a 2D image so that a small number of visual tokens carry the document, an initial investigation into compressing context optically. A December 2025 follow-up from other authors ("Optical Context Compression Is Just (Bad) Autoencoding," arXiv 2512.03643) argued the reconstruction is shallow. We include it because it shows the lab treating the input representation itself as a context-management variable — the same research program that Engram later executed successfully at the weight level.

13 Engram & V4.1-Flash

January 2026's conditional-memory research, scaled to 196B parameters in the September 10, 2026 release — knowledge stored outside the attention stream, retrieved with O(1) lookups.

13.1 The research: a new axis of sparsity

The intellectual foundation of DeepSeek's late-2026 context story is Conditional Memory via Scalable Lookup: A New Axis of Sparsity for Large Language Models (Cheng et al., arXiv 2601.07372; submitted January 12, 2026, revised July 2026). The paper's starting observation is that transformers have no native knowledge-lookup primitive — to answer from memorized facts, they must "inefficiently simulate retrieval through computation," burning attention FLOPs to reconstruct what a database would fetch. The proposal: conditional memory as a sparsity axis complementary to MoE's conditional computation, instantiated as the Engram module — a modernized N-gram embedding table addressed by the input's local n-gram context with O(1) deterministic lookup. Formulating the "Sparsity Allocation" problem — how much capacity to spend on neural computation (MoE experts) versus static memory (Engram entries) — the authors uncovered a U-shaped scaling law governing that trade-off, and scaled the module to 27B parameters under its guidance, beating a strictly iso-parameter, iso-FLOPs MoE baseline.

The results matrix is where context management re-enters. Knowledge benchmarks improve as expected (MMLU +3.4, CMMLU +4.0, HumanEval +3.0, MATH +2.4 over the MoE baseline) — but the larger gains are elsewhere: general reasoning (BBH +5.0, ARC-Challenge +3.7) and, most strikingly for this paper's subject, long-context retrieval: Multi-Query Needle-in-a-Haystack improves from 84.2 to 97.0. The mechanistic analysis explains the counter-intuitive part: by delegating local, static knowledge to lookups, Engram "relieves the backbone's early layers from static reconstruction, effectively deepening the network for complex reasoning," and "frees up attention capacity for global context" — the model attends better precisely because it no longer wastes attention on rote recall. Efficiency is infrastructure-aware by design: deterministic addressing enables runtime prefetching from host memory with negligible overhead, keeping the memory out of the GPU's HBM budget. The concluding vision — conditional memory as "an indispensable modeling primitive for next-generation" LLMs — is the thesis DeepSeek shipped seven months later.

13.2 V4.1-Flash: the release

DeepSeek-V4.1-Flash (September 10, 2026) is the smallest model of the new architecture family, and its release materials read as a context-management manifest. The headline configuration: a 552B-parameter MoE backbone plus 196B of Engram memory, in a Causal Encoder–Decoder (CED) split — 20 encoder layers activating 8B parameters per input token, 20 decoder layers activating 16B per output token — with native multimodal understanding, trained on 45 trillion tokens with post-training deliberately weighted toward agentic and reasoning data. The attention stack is Compressed Sparse Attention 2 (CSA2), which attacks the cache on three axes at once: entry size (projection shares information across heads), sequence dimension (multiple tokens compressed into single KV entries), and layer dimension (KV information reused across layers), operating in three modes — Full (compute and index), Reindex, and Reuse — under a hierarchical sparse-indexer design. The KV state is quantized to FP4 (MXFP4).

The context-economics bottom line, in the release's own figures: global KV footprint of 890 bytes per token — roughly a quarter of V4-Flash's HBM requirement and an eighth of its SSD footprint — with the local sliding-window cache reconstructible via SWA Bounded Replay (rebuilding state from a bounded window rather than persisting it whole), shrinking the persistent cache to 1/8 of the previous generation. Decode computation stays nearly flat as context scales toward one million tokens, courtesy of the hierarchical indexer and the encoder–decoder split. Benchmarks published with the release: Terminal-Bench 2.1 at 90.6 (against V4-Pro's 82.7 in the same evaluation), DeepSWE at 74.2%, and a Codeforces rating of 3471 — agent-first numbers, led by the benchmark that Letta's own memory research treats as the holistic test of agent state management (§8.3). The pricing page completes the picture: $0.006 per million cache-hit tokens, $0.30 misses, $1.20 output at peak, with off-peak at 50% — and the release note's one-line theory of agent cost: cache-hit charges are the large share; compress the cache, cut the bill.

13.3 What Engram changes about the taxonomy

Map the release against Part II's patterns and a new category appears. MemGPT pages memory via tool calls; Mem0 extracts facts into a vector store; Zep synthesizes them into a temporal graph; Anthropic's memory tool writes files. All of them keep the model fixed and manage context around it. Engram inverts the arrangement: the memory is inside the forward pass — addressed by the token stream itself, gated contextually (multi-head hashing with context-aware gating, in the V4.1-Flash paper's description), and invisible to the harness. Three consequences follow. Zero-latency memory: there is no retrieval round-trip to amortize; the lookup is part of the attention pass. Cache-native memory: Engram state is consistent for identical prefixes, so it composes with the context-caching discount rather than fighting it. Memory as capacity: knowledge migrates out of the attention stream, and — per the January paper's measurements — the freed attention capacity makes the window itself more reliable at range (the 84.2→97.0 NIAH jump). The name is the thesis: an engram is the physical trace a memory leaves in a brain, and this one leaves it in the weights.

The honest caveats

Engram does not solve cross-session user memory — per-user state still needs a harness-level store (Chapter 15's patterns remain necessary); it solves knowledge lookup for the model itself. The 196B module adds weight-storage cost that only pays off at serving scale, and the published comparisons are against DeepSeek's own iso-FLOPs baselines, not against an external frontier. And as of this writing, third-party evaluations of V4.1-Flash are just beginning to appear. The architecture direction is verifiable today; its external validation is still accumulating.

14 The DeepSeek Playbook

Five layers, one cost model, and the compiled timeline: what a lab looks like when context management is the product plan.

14.1 The five layers

Assembled from Chapters 9–13, DeepSeek's 2024–2026 program attacks the agent-loop context problem at every layer of the stack simultaneously — which is the distinction this paper's title points at:

Each row cites its chapter: serving §9–10, §13; protocol §11–12; harness §12.3; training §11.2; architecture §13.
LayerMechanismFirst shippedWhere it lives
ServingDisk context caching; MLA; DSA; CSA2; FP4 KV; SWA Bounded ReplayAug 2024 / May 2024 / Sep 2025 / Sep 2026API + inference stack
ProtocolReasoning-retention rules; reasoning_content contract; XML tool serializationDec 2025 / Apr 2026Model behavior + API surface
Harnessbash + file-edit minimal toolset; 500-step / 512K evaluation harness; DSec sandboxApr 2026Training + evaluation infra
TrainingThinking-in-tool-use trajectories; 1,800 environments / 85K instructions agentic RL; agent-domain distillationDec 2025 → 2026Post-training data
ArchitectureEngram conditional memory (196B); CED asymmetry; hierarchical sparse indexerJan 2026 paper → Sep 2026 releaseThe weights

The strategic reading: harness-level context management (the Part II patterns) is table stakes that any lab's customers can implement; weight-level context management is a moat. DeepSeek's sequence — make context cheap, then make its retention policy explicit, then train the policy in, then move memory into the weights — is a coherent program of moving the discipline down the stack. The V4.1-Flash release note compresses the whole program into one sentence about one number: compress the cache, because cache hits are the agent bill.

14.2 The cost model, worked

Run the Chapter 3 economics on V4.1-Flash pricing and the loop's arithmetic becomes concrete. Take a 50-tool-call agent task (Manus's measured average) with a stable prefix that grows by ~2,000 tokens per turn, all calls at peak pricing:

Illustrative arithmetic from the published peak prices ($0.30/M miss, $0.006/M hit, $1.20/M output), assuming ideal incremental prefix caching: each turn's ~2,000 new tokens are prefilled once at the miss price and every prior turn's span is a hit. The ~12× swing comes entirely from prefix stability — before any architectural discount.
Cost componentNaive (no cache)Stable prefix (cache hits)
Total prefill tokens (~50 turns, Σ ~2.55M)2.55M × $0.30~100K new tokens (misses) + ~2.45M reused (hits)
Prefill cost$765$30 + $15 = $45
Decode (50 × 300 output tokens × $1.20/M)$18$18
Total, 50-call task~$783~$63

Two conclusions fall out. First, the cache-hit rate is worth more than the model choice: a mid-loop tool-set change or a timestamped system prompt costs more than the difference between competing frontier models. Second, the reason DeepSeek keeps compressing the cache itself (93.3% → 656–132 bytes/token/layer → 890 bytes/token global) is that at agent-traffic volumes, the hit-rate line of the bill is the line that scales with the industry's agent adoption curve — 40% of enterprise applications integrating agents by end-2026 in Gartner's projection, from under 5% a year earlier.

14.3 The compiled timeline

MAY 2024
MLA (DeepSeek-V2)
Latent-compressed KV cache: 93.3% smaller than the dense 67B baseline, 5.76× decode throughput, 42.5% training savings. Long context becomes affordable to serve.
AUG 2024
Context Caching (API)
Automatic, disk-based prefix cache: hits at $0.014/M vs $0.14/M misses — the 90% agent-loop discount, two years before the industry's agent boom.
DEC 2024–JAN 2025
V3 (MTP) & R1
128K window carried over from the V2 line; MTP speculative decode at 1.8× TPS. R1's long CoT arrives with the flush-reasoning-at-user-turn contract — the policy V3.2 later rejects as token-inefficient.
SEP 29, 2025
DeepSeek-V3.2-Exp: DSA
Lightning indexer + top-2048 selection: attention O(L²)→O(L·k); ~132 B/token/layer indexer cache vs ~656 for MLA entries; ~5× decode-cache reduction at 131K; prices cut 50%+.
OCT 2025
DeepSeek-OCR: Contexts Optical Compression
Research detour: compressing long contexts via optical 2D mapping of text through the vision encoder — input representation treated as a context variable.
DEC 1, 2025
DeepSeek-V3.2: Thinking Context Management
Rule set: retain reasoning across tool outputs, discard at user turns, preserve tool history. First thinking-in-tool-use model; 1,800 environments / 85K prompts agentic RL; BrowseComp 51.4→67.6 with context management (§4.4 study); reasoning_content contract with 400-error enforcement.
JAN 12, 2026
Engram paper (arXiv 2601.07372)
Conditional memory via scalable lookup: O(1) n-gram-addressed memory as a second sparsity axis; U-shaped allocation law; Multi-Query NIAH 84.2→97.0; host-memory prefetch.
APR 24, 2026
DeepSeek-V4 preview
1M-token context "agents can actually use": CSA+HCA at 27% FLOPs / 10% KV (Pro) vs V3.2 @1M; reasoning preserved across user turns in tool scenarios; Quick Instruction cache-native auxiliary tasks; 500-step/512K agent harness; DSec sandbox.
AUG 2026
V4-Pro GA & V4-Flash-Vision-Exp
General availability of the V4 line (Aug 13) and the vision experiment (Aug 21); Engram-equipped Flash lineage prepares for the September handoff.
SEP 10, 2026
DeepSeek-V4.1-Flash
552B backbone + 196B Engram; CED 8B/16B asymmetric encoder–decoder; CSA2 with FP4 KV at 890 B/token global (438× below the V1-era baseline); SWA Bounded Replay at 1/8 persistent cache; Terminal-Bench 2.1 90.6; cache hits at $0.006/M. "Cache-hit charges often account for a large share of agent costs."
Part IV · Chapters 15–16

Architectures & the Playbook

Nine context-management patterns with their trade-offs, a decision framework keyed to named constraints, working recipes — including the compliant DeepSeek reasoning loop — and the open problems the field has left on the table.

15 The Pattern Catalog

Nine architectures, organized by LangChain's four verbs, with the evidence for each and the failure mode that kills it.

15.1 The catalog

Lever vocabulary from LangChain's write/select/compress/isolate (§6.4). Every pattern is documented in Part II or Part III with its primary source.
#PatternLeverEvidence anchorKills you when
P1Sliding window / truncationCompressClaude chat's rolling FIFO; every framework's max-history knobEarly facts (the failing test, the constraint) scroll out of view
P2Compaction (summarize & re-init)CompressAnthropic's recipe (§7.2); DeepSeek's Summary strategy (60.2, 364 steps)Cache rewrite wipes the discount; recall drops below what you saved
P3Tool-result clearing / output capsCompressClaude context editing; Towards AI's 38% cost cut; V3.2's Discard-75%Cleared payloads invalidate cached prefixes; future steps need the raw data
P4Structured notes / scratchpad filesWriteNOTES.md, todo.md recitation (Manus); Pokémon memory; AGENTS.md conventionsNotes rot — stale state misleads more than no state
P5Hierarchical memory storeWrite + SelectMemGPT blocks, Mem0, A-MEM, MemOS, Zep (§5)Retrieval quality caps at the driver model's tool competence
P6Just-in-time retrieval / DCISelectAnthropic JIT doctrine; DCI (arXiv 2605.05242); Claude Code's head/tailExploration loops burn tokens re-finding what a cache would have kept
P7Sub-agent isolationIsolateAnthropic orchestrator-worker (1–2K-token returns); V3.2's parallel-fewest-stepShared context = KV penalty + pollution; handoff summaries lose the detail
P8Cache-aware loop engineering(meta)Manus's prefix rules; Bouchard's keep-everything result; Quick InstructionAny prefix mutation — timestamps, tool churn, unstable serialization
P9Model-native context features(meta)DeepSeek reasoning_content contract; Claude memory tool / context editing; EngramProvider lock-in; semantics differ per vendor (Terminus-style harnesses break rules)

15.2 The decision framework: name the constraint first

The single most transferable lesson of 2025–2026 — common to the Anthropic essay, the Manus manual, the Towards AI measurements, and the DeepSeek §4.4 study — is that pattern selection is constraint-driven, not fashion-driven. Bouchard's team reduced it to three named constraints; the DeepSeek study added the compute-budget axis. The framework below merges them:

Name your constraint — measured, not assumed
A. Window overflow
The trajectory genuinely does not fit (500-step harness, 10M-token corpus). → P2 compaction, P3 clearing, P5 offload, P7 isolation. DeepSeek's evidence: even crude Discard-all beat an unmanaged overflow by +16.2 BrowseComp points.
B. Cost
Prefill dominates (100:1 skew); cached input price above your threshold (~$0.55/M in the Towards AI calculus). → P8 first (stabilize the prefix, cap outputs), then P9 native caching; only then P2. On DeepSeek pricing, keep-everything usually wins.
C. Quality rot
Blind-judged recall drops, NoLiMa-style associative failures, goal drift by turn 40. → P4 recitation (todo.md), P6 JIT loading, P7 clean sub-agent windows; P5 only with a strong driver model.
↓
Then measure on your own workload — the Towards AI team's production defaults looked reasonable, scored 38% on memory probes, and cost twice the baseline. Every ordering in this catalog has task-dependence published against it.
Fig 15.1 — Constraint-first pattern selection. The three constraints fail together (§2.4) but are fixed separately; fixing B with A's tools (summarizing for cost) is the documented 2026 mistake.

15.3 The hybrid that production converged on

No serious 2026 deployment runs one pattern; the convergent stack composes five, and it maps cleanly onto the four verbs. A stable, versioned system prompt and a frozen tool schema protect the cache (P8). A working set — current plan in a todo file, recent turns, uncleared critical outputs — rides in the window (P4 + light P3). Everything else lives in files or a store the agent queries on demand (P6), with sub-agents spawned for wide exploration and returning distilled findings (P7), and vendor-native features (DeepSeek's reasoning contract, Claude's editing) substituted for home-grown versions where the stack allows (P9). The V4 harness DeepSeek evaluates in its own report — two tools, 500 steps, 512K window — is this shape in miniature, which is the strongest available signal that the pattern generalizes across labs rather than being a house style.

The 2026 synthesis

Three years of research resolved into one sentence: keep the working set small and cache-stable; write everything else down where the agent can find it; let sub-agents make the noise; and buy the model whose internals respect the budget. Parts I–III established why; this catalog is the how; the next chapter is the wiring.

16 Recipes, Checklists & Outlook

Working code for the compliant DeepSeek agent loop, the compaction harness, and the memory-block pattern — plus the open problems the field has left standing.

16.1 Recipe 1: the DeepSeek tool loop that respects the contract

Chapter 11.3 documented the rule: in tool-carrying requests, reasoning_content must round-trip for every prior assistant turn, or the API rejects the call. This is the compliant loop — and it is also the retention policy from §11.1, expressed in harness code:

deepseek_agent_loop.py — compliant reasoning retention●●●
from openai import OpenAI

client = OpenAI(api_key="<DeepSeek API Key>",
                base_url="https://api.deepseek.com")

messages = [{"role": "user", "content": "Find and fix the failing test."}]

while True:
    resp = client.chat.completions.create(
        model="deepseek-flash",          # V4.1-Flash: $0.006/M cache hits (peak)
        messages=messages,
        tools=TOOLS,                       # tools present => agent semantics
        reasoning_effort="high",
    )
    msg = resp.choices[0].message

    # CRITICAL: keep reasoning_content in the history.
    # Dropping it => HTTP 400. Keeping it => reasoning persists
    # across tool outputs, per V3.2 Thinking Context Management.
    messages.append({
        "role": "assistant",
        "content": msg.content,
        "reasoning_content": msg.reasoning_content,
        "tool_calls": msg.tool_calls,
    })

    if not msg.tool_calls:
        break                            # final answer; loop ends

    for tc in msg.tool_calls:        # execute each call, cap the output
        result = execute(tc.function.name, json.loads(tc.function.arguments))
        messages.append({
            "role": "tool",
            "tool_call_id": tc.id,
            "content": cap(result, max_tokens=1500),  # P3: stable caps, -38% cost
        })
        # A new USER message here would trigger the discard rule;
        # tool outputs alone never do (§11.1, Rule 1).

Three details carry the whole Part III story. The reasoning_content append implements Rule 1 (tool outputs never wipe reasoning). The cap() on tool results implements the cheapest proven compaction tier from Chapter 3. And the loop's append-only shape — nothing above the current turn is ever rewritten — is what keeps every subsequent call inside the prefix cache, converting the 100:1 skew from a liability into the $0.006-per-million discount.

16.2 Recipe 2: compaction with the cache in mind

When the window genuinely overflows (constraint A), compact at the boundary — not mid-prefix — and keep a restorable residue, following the Anthropic recipe and the Manus restorability rule:

compact.py — recall-first, cache-aware●●●
def maybe_compact(messages, window, budget):
    used = tokens(messages)
    if used < 0.80 * window:          # V3.2 §4.4 trigger point
        return messages

    kept = [m for m in messages if m["role"] in ("system",)] \
        + [m for m in messages[-5:]]     # recent turns + system prompt

    summary = llm_summarize(
        messages,
        prompt="""Preserve: architectural decisions, unresolved bugs,
        implementation details, user constraints. Discard: raw tool outputs
        whose facts you have restated, superseded search results.
        For every dropped artifact, keep its reference (path/URL) so the
        agent can re-fetch it.""")                  # recall first, then precision

    return kept[:1] + [{"role": "user", "content": summary}] + kept[1:]

# Measured trade-offs before you ship this:
#  - DeepSeek BrowseComp study: Summary hit 60.2 at 364 avg steps;
#    Discard-all hit 67.6 with far fewer steps (§11.4).
#  - Towards AI: with cheap cache hits, keep-everything beat every
#    summary on cost+latency+recall at once (§3.2).
#  - Compaction rewrites the prefix: the next call re-prefills at full price.

16.3 Recipe 3: memory blocks, the Letta shape

For state that must outlive the window (constraint: long-horizon coherence), the self-editing block remains the pattern with the deepest evidence trail. A minimal JSON rendition of the Letta-style core memory, editable by the agent through tools:

core_memory.json — self-editing blocks (P4/P5)●●●
{
  "persona": {
    "block": "You are the repo-maintenance agent for api-gateway.",
    "last_rewritten": "2026-09-13T10:22:31Z"
  },
  "task_state": {
    "block": "Goal: fix flaky auth e2e. Done: repro, log capture. Open: token-refresh race in middleware/auth.py:L214. Hypothesis 2 rejected (clock skew). Next: instrument refresh window.",
    "limit_tokens": 2000,              # bounded, in-window, always visible
    "rewrite_policy": "agent-tool: core_memory_replace"
  },
  "project_facts": {
    "block": "CI: GitHub Actions, runners have 7GB RAM. Test DB: ephemeral Postgres 16. Owner: @infra-oncall.",
    "limit_tokens": 1000
  }
}
# The todo.md recitation rule (Manus) is this pattern's file-shaped twin:
# rewrite the block every few steps so the plan sits at the END of context,
# where attention is strongest (§2.1) and drift dies.

16.4 The production checklist

  • Stable prefix: no timestamps, no per-request IDs, no dynamic tool sets above the history. Version the system prompt; roll it deliberately (§3.1).
  • Append-only history: deterministic serialization (stable JSON key order); tool outputs capped at a stable size; nothing rewritten mid-loop (§3.2).
  • Reasoning contract honored: on DeepSeek, round-trip reasoning_content whenever tools is present; know your framework's user-message emulation (Terminus-style harnesses flip the semantics — §11.1).
  • Working set defined: plan block + recent turns + uncleared critical outputs in the window; everything else addressable by reference (P4–P6).
  • Sub-agent seams sealed: fresh context per worker, 1–2K-token distilled returns; never share one growing window across workers (§6.3).
  • Failures kept in context: no silent retries; the trace of what failed is the model's evidence (§7.6).
  • Compaction is conditional: triggered at ~80% window use, recall-first prompt, restorable references for everything dropped (§16.2).
  • Instrumented: cache-hit rate, tokens per query, and blind-graded memory probes on your own traffic — the three numbers every 2026 retrospective wished it had from day one (§8.3).

16.5 The open problems, honestly stated

The field's own documents name what remains unsolved, and they agree more than their benchmark tables suggest. Mem0's 2026 report lists three: cross-session identity (whose memory is it, and how does it follow the user across agents and vendors?), temporal abstraction at scale (summarizing what changed over time, not just what is true now), and memory staleness (knowing when a stored fact has died). DeepSeek's V3.2 paper adds its own: the optimal combination of serial and parallel test-time scaling — when to keep one long managed trajectory versus sampling many short ones — and token efficiency: the model's own admission that its reasoning chains run longer than frontier quality justifies, with "intelligence density" of reasoning as the named target. The Anthropic essay closes on the same note from the opposite direction: smarter models need less prescriptive engineering, but "treating context as a precious, finite resource will remain central."

16.6 Outlook: what the next cycle looks like

Extrapolating only from shipped evidence, three trajectories are already visible. Memory continues migrating into the model: the harness patterns of Part II are being absorbed as trained behaviors and architectural primitives — retention rules at V3.2, cache-native auxiliary tasks and full reasoning persistence at V4, a 196B lookup memory at V4.1-Flash; the announced V4.1-Pro will show whether Engram scales with the flagship line. The economics compound: with cache hits at $0.006 per million and KV at 890 bytes per token, the marginal cost of a retained context is collapsing toward the cost of the decision to retain it — which is why DeepSeek's own release notes now discuss agent cost in cache terms. Context becomes observable operations: the ICML 2026 workshop program carried "agentic AI" in at least 60 of 247 accepted proposals, and monitoring products like Amazon CloudWatch's Coding Agent Insights (July 2026) exist because agent context behavior became a line item engineering leaders track. The three-year arc of this paper — from "fit the window" to "manage the artifact" to "engineer the economics" — has one more turn left, and it is the one DeepSeek has already bet on: context management as a property of the model itself, with everything else as scaffolding around it.

If you remember five numbers

100:1 — the prefill:decode skew that makes caching the business model. 50% at 32K — NoLiMa's cliff that bigger windows did not remove. 74.0 vs 92.5 — the benchmark spread that says "measure it yourself." 51.4 → 67.6 — what DeepSeek's own study says context management is worth on hard agentic search. 84.2 → 97.0 — what happens when memory moves into the weights. Everything else in this paper is derivation.

Sources (all accessed and verified September 13, 2026). Primary papers: MemGPT (arXiv 2310.08560); Zep/Graphiti (arXiv 2501.13956); Mem0 (arXiv 2504.19413, ECAI 2025); Sleep-time Compute (arXiv 2504.13171); A-MEM (arXiv 2502.12110, NeurIPS 2025); MemOS (arXiv 2507.03724); NoLiMa (Modarressi et al., 2025); ACE (arXiv 2510.04618); DeepSeek-OCR (arXiv 2510.18234); optical-compression critique (arXiv 2512.03643); DeepSeek-V3.2 (arXiv 2512.02556); DeepSeek-V4 (arXiv 2606.19348); Engram (arXiv 2601.07372); DCI (arXiv 2605.05242); Lost in the Middle (Liu et al., 2023); Generative Agents, Reflexion, Voyager, LLMLingua, HippoRAG, LongMemEval (2023–2024 literature). Official engineering and product sources: Anthropic, "Effective Context Engineering for AI Agents" (Sep 29, 2025) and platform context docs; Manus, "Context Engineering for AI Agents" (Jul 18, 2025); Letta, "Benchmarking AI Agent Memory" (Aug 12, 2025) and memory-blocks/sleep-time posts; Zep blog (May 6, 2025); Mem0, "State of AI Agent Memory 2026" (Apr 1, 2026); LangChain context-engineering posts (Jul 2025; Jan 2026); philschmid (Dec 4, 2025); Crux Digits 2026 playbook (Jul 24, 2026); Louis-François Bouchard, "Context Engineering in 2026" (Aug 18, 2026); Chroma Research, "Context Rot" (Jul 2025); Karpathy, X post (Jun 25, 2025). DeepSeek primary releases: Context Caching (Aug 2, 2024); V3.2-Exp (Sep 29, 2025); V3.2 (Dec 1, 2025) + thinking-mode and tool-calls API guides; V4 preview (Apr 24, 2026) + Hugging Face announcement; V4-Pro GA (Aug 13, 2026); V4-Flash-Vision-Exp (Aug 21, 2026); V4.1-Flash (Sep 10, 2026) release notes, paper, and pricing page. Conflicting benchmark figures are presented with their publishers named; see §8.3 for the reading protocol.

Compiled as a single self-contained HTML document. No external dependencies, no trackers, no build step — the way a research artifact should ship.