How an Agent Builds Its Context
The morning after a long session with an operations agent, you type one line: "Is CHG-4182 still on for tonight?" Yesterday you and the agent spent three hours on that change: questions, a ticket, a runbook, a plan, a change of plan. None of that history is in front of the model now. The window it reads this morning was built a moment ago, and the only parts of yesterday inside it are what the agent wrote down before the session ended.
Thesis: A model remembers nothing between calls, so what it knows on any call is what the harness assembled for it: some parts loaded every time, some read by the model through a tool, some selected by code, and the rest cut when the total does not fit the window. None of it is learning. Knowing which mechanism brought each part in, and which lever shrinks which part, is how you keep the window small without losing what the next step needs.
Four Kinds of Context sorted what a call carries into direction, law, coordination and working context, and Direction Is Not Law and Law Belongs in the Harness took the first two kinds on their own. This chapter is about how those pieces get into the window on each call, and what happens when they do not all fit. The change ticket CHG-4182, its service and runbook are invented.
The Window Is Rebuilt Every Call
The model remembers nothing between calls. On every call the harness assembles a fresh input and appends each tool result it runs (Anatomy of a Turn; How the Model Reads the Window covers the order and the caching).
Two decisions shape the window over a long task. The first is what to load before the first call versus what the model fetches when it needs it, which Anthropic's engineering post on context engineering (2025-09-29) calls "just in time". The second is what reaches the next session, which is only what someone wrote outside the window. That second decision is what people mean by memory.
Here is the morning question, call by call. The harness loads a short index of notes before the first call, the model asks for the one note it needs, and the harness puts the note's text into the next call's input. Nothing reaches the model except through the harness.
sequenceDiagram
participant You
participant H as Harness
participant N as Notes on disk
participant M as Model
You->>H: Is CHG-4182 still on for tonight?
H->>N: Load the index of notes
N-->>H: Index lists a note on CHG-4182
H->>M: Call 1: system prompt, tools, index, your question
M-->>H: Tool call: read the CHG-4182 note
H->>N: Read the note
N-->>H: Friday 22:00, failover to pay-06
H->>M: Call 2: all of call 1, the tool call, the note
M-->>H: Answer: not tonight, Friday at 22:00
H-->>You: Not tonight, it moved to Friday 22:00
Figure: The CHG-4182 question answered from a note. The harness loads an index of notes, the model asks to read the CHG-4182 note, and the second call carries the first call's input again plus the note, the only part of yesterday the model sees.
Call 2 carries everything in call 1 again, plus the note. Yesterday's three hours are not in either call; the note is the only part of yesterday the model reads.
Memory Comes in Four Shapes
"Memory" names several mechanisms, and this site sorts them into four shapes by who decides what enters the window, because that predicts how each fails. The grouping is this site's, a working tool rather than one of the series' three ideas; in LangChain's terms all four bring back what was written outside the window, three of them by selecting it, and the CoALA paper's long-term memory types describe what is stored rather than how it comes back. Examples are from Claude Code and Anthropic's API, as of November 2026; other harnesses have equivalents.
| Shape | Who decides what comes back | Example | Pays | Fails when |
|---|---|---|---|---|
| Loaded whole | Nobody: it always comes back | Claude Code reads CLAUDE.md files "at the start of every session" | Tokens on every call | It grows until it drowns the task |
| Read by the model through a tool | The model | Anthropic's memory tool: Claude requests file operations and "your application runs them" | A tool call when used | The model never thinks to look |
| Selected by code from a rule | A rule keyed on the work | Path-scoped rules "load only when Claude works with matching files" | Tokens only when matched | The rule keys on the file, never the question |
| Retrieved by code using the question | Code that reads your words | A hook on each prompt that receives it and adds matching notes | A search per prompt | A note matches the words and misleads the task |
The first shape is reliable and expensive. The second is cheap and depends on the model's judgment. The third and fourth move the judgment into code, which is predictable but sees only the file or the words, not the next step. Most real agents mix them: a small index loaded whole that names what exists, with the contents read through a tool when needed. In the morning example, the agent found yesterday's note because the index loaded at session start listed CHG-4182, and the model then opened the note with a file read (the API's memory tool does the same job).
None of the four is learning. The model's weights do not change between sessions. So a note has three jobs. It keeps identifiers verbatim, because a note that says "the payments change" hands tomorrow's session a search, not a fact. It says what it supersedes, because tomorrow's session cannot see the conversation where the plan changed. And it has a writer and a date, because a memory the agent wrote is data with an owner, not a fact. The Files Are the Memory is the pattern built on this.
When the Input Does Not Fit
Every part of a call's input competes for one fixed budget: the context window, measured in tokens. The system prompt and the tool definitions are sent whole on every call. The history grows with every turn, retrieved passages arrive per question, and room has to be held back for the reply. When the total is larger than the window, something has to go, and the harness, not the model, decides what.
The lab below is that decision with the numbers made visible. Size each part, pick what the harness does when the input is over budget, and read what the model loses. Try the largest tool set first, then switch between dropping and summarising the oldest turns. With JavaScript off, a table shows three of the same cases.
| Case (an example 128,000-token window, 8,000 held for the reply) | What is asked for | What the harness does | What the model loses |
|---|---|---|---|
| A medium system prompt, 40 tools, 30 past turns, 6 passages, a one-line question | 71,150 tokens of input | Sends everything | Nothing; 48,850 tokens spare |
| Hundreds of tools (80,000 tokens), same history and passages | 131,150 tokens of input | Drops the 10 oldest turns | Turns 1 to 10, completely, unless they were written to a file |
| Hundreds of tools, same history and passages, summarising | 131,150 tokens of input | Replaces the 11 oldest turns with a 2,000-token summary | The exact identifiers in turns 1 to 11; many decisions too (on two real compactions, a third to over half were lost outright) |
In the terms of Four Kinds of Context, the bar's parts are not equal. The system prompt and the tool definitions are standing capability, plus any law written as prose, and they are never cut. The history, the tool results inside it and the retrieved passages are working context, and they are what the harness cuts. Direction and coordination survive a cut only if they were written outside the window, in a note or a record that comes back in.
The numbers are illustrative, and 128,000 is an example size (each of the latest Claude models has a window of 1 million tokens, per Anthropic's models overview), but the shape is not. A large tool set or a long system prompt does not fail loudly: it shrinks the room left for the conversation, so the harness starts forgetting sooner. What Compaction Actually Destroys measured what a summary keeps, and How the Model Reads the Window explains why even what fits is not read evenly.
The Levers, in One Place
Dropping and summarising the oldest turns are the crude levers, the ones a harness pulls by default. The working toolkit has more, and each cuts a different part of the bar. Here they are together, with when each pays. The examples are Anthropic's API and Claude Code as of November 2026; other harnesses have equivalents. The table is a catalogue, not another scheme to learn. The last column is the word LangChain's four strategies use for the same move.
| Lever | What it cuts, and how | Use it when | Not when | Strategy |
|---|---|---|---|---|
| Clear old tool results | Results the model has already read. Anthropic's context editing replaces each with a placeholder once the input passes a threshold | Long, tool-heavy tasks whose old results can be fetched again | A later step needs the exact old result and cannot re-fetch it. Clearing also invalidates the cached prefix, so clear in large steps | Compress |
| Tool search | Tool definitions. Most stay out of the window and the model searches for the few it needs; Anthropic's tool search tool returns "up to 5 matching tools by default" per search, and the model can set a limit from 1 to 10,000 in its search input |
Ten or more tools, or definitions over 10,000 tokens: the thresholds Anthropic's page gives | Fewer than ten tools, or every tool used on every call | Select |
| Skills | Guidance for one kind of task. Only each skill's name and description load up front (about 100 tokens a skill); the full instructions load when a task matches, which Anthropic calls progressive disclosure | Procedures and formats that some tasks need and most do not | Guidance every call needs: that is the always-on set, and it must pass the 2+2 test | Select |
| Compaction | The older history, replaced by a summary. Claude Code compacts automatically and on demand; Anthropic's API offers server-side compaction in beta | A session that must carry on past the window | Before identifiers and the record of what was superseded are written outside the window: a summary drops them (When Context Turns Against You has a lab) | Compress |
| Subagents | A side task's whole working context. A subagent runs in its own window and returns only a summary | Exploration or bulky work whose detail the main task does not need | Tightly coupled work, where every step is a decision the other agent must see (Shared State Needs One Writer) | Isolate |
| Retrieval | Knowledge that would not fit. Code searches a store on each question and adds the best passages | Knowledge too large or too changeable to load whole | A small corpus that fits: load it, and a miss stops being possible (Where Retrieval Enters the Turn) | Select |
| Memory files | Everything the next session would otherwise rebuild. An index loads whole; the notes it names are read through a tool | Identifiers, decisions and progress that must outlive the session | Short tasks where nothing needs to outlive the session (The Files Are the Memory) | Write |
Two things are missing from the table on purpose. Prompt caching lowers the price of a repeated prefix and removes nothing from the window, so it eases the bill and not the drowning. And the cheapest lever of all is a decision, not a technique: give the agent only the tools and the rules its job needs, so there is less to search, skip or summarise.
Read the table against the lab above. Tool search shrinks the tool-definitions segment, clearing and compaction shrink the history, subagents keep whole branches of history from ever entering it, and memory files are what lets you cut the rest without losing what the next step needs.
The Phase Flow: Discovery, Execution, Change of Plan
The harness policies above decide what is in the window. None of them records what was decided. The window keeps decisions as chat, in the order they were said, so when the goal moves, the superseded version stays and looks as current as the new one. When operations moves the CHG-4182 restart from Thursday to Friday in one message, both versions stay in the history, and When Context Turns Against You follows what that does to the next plan and builds the fix: a short written record of the decisions in force and the decisions they replaced. The phase flow below is this site's policy for keeping such a record current. It belongs in this chapter because it decides the order in which the levers above are pulled: the record first, the history after. If the failure it guards against is new to you, read When Context Turns Against You first; this section is the policy, that chapter is the evidence.
| Phase | How the agent behaves | The record | The history |
|---|---|---|---|
| Discovery | Asks, restates, lists open questions | Written at the end, through a tool call | Kept: the questions and answers are the evidence |
| Execution | Terse; asks only on a conflict | Read, not rewritten | Grows with tool results; old ones cleared when the input fills |
| Change of plan | Back to discovery | Rewritten first, with old decisions moved to a Superseded list | Summarised (compaction) or cleared, with the record as the focus |
| After any reset | Unchanged | Re-read from disk | Only the summary, if anything |
Each piece rests on a documented mechanism, shown here in Claude Code. An output style, the standing instructions for how the agent behaves, can be switched mid-session, which is how the agent changes from asking to doing. A hook, code the harness runs at a set moment, can add a reminder; and a hook that runs when a session starts, which in Claude Code also happens after a compaction, can put the record back into the window. The order is the point: the record changes before the window does, so a reset never throws away the reason the old plan was abandoned.
Two joints are weak. Detection is one: a check on the agent's reply catches a change of plan only after one wrong answer, and a person usually knows they changed their mind before any detector does. Cost is the other: a discovery phase spends turns asking before any work starts, which pays only when the goal is genuinely unclear. And whether re-reading the record after a reset stops a superseded plan from steering the work has not been measured; the phase flow is a design, not a finding.
Try It: One Ticket Across Two Sessions
This is the yesterday the hook describes, call by call, and the morning after it. The lab follows CHG-4182 through both sessions: what each call's input holds, who put each part there, how long it stays, what the phase flow above does to it, and what was written outside the window before the session ended. Step with Back and Next, the numbered steps or the arrow keys. The ticket, the service, the notes and the harness are invented; the window size is counted in characters computed from the text shown, against an illustrative limit, not in tokens. With JavaScript off, the table gives every step.
| Step | Who acts | What enters or leaves the window | Why it matters |
|---|---|---|---|
| 1. You send a message | You | Typed, not yet in the window: Your message. | You type one sentence. The model has not seen anything yet. What it will see is decided by the harness in the next step. |
| 2. The harness assembles the request | Harness | Enters: Tool definitions; System prompt; Output style: discovery (session start); Project rules file; Memory index, loaded whole; Memory note, selected by code for this message. Written outside the window: Session log. | The harness puts six blocks before your sentence, in the order prompt caches read: tools, system, messages. The first five repeat every call: a cached prefix, cheaper but still in the window. A past-restart note was picked by code from your words. The session log on disk starts here. Related post: Anatomy of a Turn. |
| 3. Call 1: in discovery style, the model asks before it plans | Model | Enters: Thinking (this call); Reply: discovery questions. | The model thinks first, then replies with questions instead of a plan, because the discovery style says to. Its thinking is output it wrote for itself; whether that block rides along in later calls depends on the model and the API, so count it as context while it is there. |
| 4. You answer the questions | You | Enters: Your answers. | Three decisions are now in the history: restart in place, Thursday at 22:00, you approve rollbacks. So far they exist only as chat, in the order they were said. |
| 5. Call 2: discovery ends with the aligned record | Model | Enters: Tool request: write_record (aligned record v1); Tool result: record saved, phase set to execution. Written outside the window: Aligned record v1 (file). | The model writes the record through a tool call: objective, decisions in force, superseded decisions, open questions. The request and its result enter the window; the file lands on disk. In this design the save also flips the phase: from the next call the style is terse and works against the record. |
| 6. Call 3 asks for the ticket and the runbook | Tool | Enters: Style switch: execution (sent as a message); Tool requests: get_ticket, search_runbook; Tool result: ticket; Retrieved passages. | The record write switched the style to execution, sent as a message so the cached prefix is kept. The model asks for the ticket and runbook; the harness runs both. Code picks which passages come back; if the right one is missing, the model cannot tell. |
| 7. You change the plan | You | Enters: Your message: the plan changes. Superseded, still in window: Your answers; Tool request: write_record (aligned record v1); Tool result: ticket. | Your message reverses two decisions. Nothing is replaced: your earlier answers, the record's request and the ticket still say Thursday and in place. Only their order marks which version is current. The pivot came in passing, with no words that announce a change of objective. |
| 8. Call 4: a plan that fuses both versions | Model | Enters: Reply: plan (wrong window), built from superseded parts. | The new steps came from your message, the Thursday window from older blocks, and the execution style said to act against a record that is now stale. A hypothesis, not yet measured: a contradiction in the window yields answers like this, built from parts that each look current. Hypothesis: a claim not yet measured. |
| 9. The harness detects the pivot | Harness | Enters: Reminder injected by the harness; Style switch: discovery (sent as a message). | A check after the reply compares it with your latest message and the record, finds them disagreeing, appends a reminder to rewrite the record, and switches the style back to discovery. It is one wrong answer late, because it ran after the reply, not when your message came in. |
| 10. Call 5: the record is rewritten | Model | Enters: Tool request: write_record (aligned record v2); Tool result: record saved. Written outside the window: Aligned record v2 (file). | The new record keeps the objective, lists the new decisions in force, and moves the old ones to Superseded with their old wording and what replaced them. The file on disk now says which version is current, in words, instead of leaving it to position in the history. |
| 11. The harness clears old tool results | Harness | Enters: Cleared tool results. Leaves: Tool result: ticket; Retrieved passages. | Clearing comes first here: the old ticket and runbook results are replaced by placeholders, and the requests that made them stay. The stale Thursday ticket leaves with them. Clearing changes the history, so the cache after that point has to be written again. |
| 12. At the pivot, the harness compacts | Harness | Enters: Summary (compaction). Leaves: Memory note, selected by code for this message; Your message; Thinking (this call); Reply: discovery questions; Your answers; Tool request: write_record (aligned record v1); Tool result: record saved, phase set to execution; Tool requests: get_ticket, search_runbook; Cleared tool results; Your message: the plan changes; Reply: plan (wrong window); Reminder injected by the harness; Tool request: write_record (aligned record v2); Tool result: record saved; Style switch: execution (sent as a message); Style switch: discovery (sent as a message). | The window still has room; the harness compacts because the goal moved and the history now holds more superseded text than current. The summary keeps the gist, drops ticket, nodes and window, and reads as if nothing is missing. On this site's measured live compaction, 31 of 31 record ids were lost. Verified number: measured on this site, linked to its home post. Related post: What Compaction Actually Destroys. |
| 13. The record is re-injected | Harness | Enters: Aligned record v2, re-injected. | The harness reads the record back from disk and appends it after the summary, so the decisions, what they superseded and the exact identifiers return verbatim. The design's claim, not yet measured: a re-injected record stops a superseded decision from steering the next action. Hypothesis: a claim not yet measured. |
| 14. Before the session ends, the model writes memory | Model | Enters: Tool request: memory_write; Tool result: note saved. Written outside the window: Memory note CHG-4182 (saved). | Memory is written by a tool call; the note lands in the store, whose index now lists CHG-4182. A note saying only that the plan was revised would carry the gap forward; one that saved the first plan would carry the contradiction forward. This one names what it supersedes and keeps the ids. |
| 15. Next day: a fresh window | Harness | Enters: Memory index, loaded whole (updated); Your message (next day). | A new session starts empty. The harness loads the same fixed blocks and the memory index, which now lists a CHG-4182 note. The note itself is not loaded: this harness preloads the index and leaves the notes to be read when needed. Yesterday's history, summary and record are not in the window. |
| 16. Call 1 reads the note through the memory tool | Tool | Enters: Tool request: memory_read; Tool result: memory note. | The model saw CHG-4182 in the index and asked for the note; the harness read it and appended it. Memory read this way costs nothing until it is read, and helps only if the model thinks to read it. |
| 17. A subagent re-checks the ticket in its own window | Subagent | Enters the subagent's window: Subagent's tool definitions; Subagent's own prompt; Project rules file; Brief from the parent; Tool result: ticket (subagent's call). | This is the subagent's window, not the parent's. It holds its own prompt, its own tools, the project rules file and the brief. The parent's system prompt, with its rule about approved tickets, is not here; nor are the output style, the memory or the history. Only its summary goes back. Related post: Subagents: Fresh Eyes on Demand. |
| 18. Call 3: the answer, from the note and a fresh check | Model | Enters: Tool request: run_subagent; Subagent's summary; Reply. | The parent's window gained two blocks from the subagent's work: its run_subagent request and the summary that came back. The answer comes from the note and the re-checked ticket. Yesterday's three hours reached today only as the note, the record file and the log. |
When Accumulation Wins
A short chat with no tools. If the conversation fits comfortably, resending everything is the simplest correct policy.
A task whose goal never moves. Discovery costs turns and every record write costs a call. On a task decided in the first message, both are overhead.
Every management step can drop what mattered. Clearing can drop a result a later step needed, compaction drops identifiers, and a re-read record is only as good as its last rewrite.
What to Do Next
- Name the shape of each memory you run. For every store, write down who decides what comes back: always, the model, a rule, or a search on the question. That tells you how it will fail.
- Load an index, not the contents. Keep the always-loaded part small and make it name everything worth fetching.
- Make a change of plan a phase, not a message. When the goal moves, rewrite the record first, then decide what to do with the history.
- Give every note an author, a date and an approval state. Memory an agent writes is data with an owner who decides how long it lives and how a wrong one is corrected.
- Do the budget for your largest call. Add up the system prompt, the tool definitions, the history and the retrieved passages, and find out which one your harness cuts first when the total is over the window.
Next: When Context Turns Against You, the five ways the assembled window fails, a lab that runs one session through four ways to manage the window, and why a written record of the decisions in force and the decisions superseded is the fix for the two that get worse with time. Related reading: Anatomy of a Turn for why every call resends the whole conversation; Where Retrieval Enters the Turn for the fourth shape in detail; The Files Are the Memory for state outside the window; and What Compaction Actually Destroys for what a summary keeps.