Chapter 7 of 18

Context

What the agent can see decides what it can do. How to feed it, keep it clean, and carry knowledge between sessions.

Chapter 5 gave you a hard fact: everything the model will use has to fit in one request. Now the practical side of it. What the agent can see decides what it can do. A function it hasn't seen, it guesses at. A rule that has fallen out of the window might as well never have been written, and nothing warns you that it has gone.

So treat context as a budget you spend. Every file read and every test log stays in the window and gets read again on each later turn. This chapter teaches three habits: feed it what the task needs and little else, keep what is in there clean, and carry knowledge from one session to the next, since each one starts empty.

A lot of what gets said about this is folklore, so we separate the two. Established: every token is resent and billed, models recall less reliably from long contexts, and irrelevant text can hurt. Not established: any specific point at which a model "gets dumb". You will hear numbers. They are working rules from people who do this a lot, and no one has shown us the data behind them.

We read the tool behaviour here on 5 November 2026 (Claude Code v2.1.318), and it changes monthly. The benches count tokens with a small estimator on the page, tuned to Anthropic's published average of about 2.5 characters per token. It is not Claude's tokeniser, so use the count_tokens endpoint when you need the true figure.

Context engineering

Choosing what the model can see on each request: which instructions, files, tool results and history go in, and which stay out. The prompt is what you say. Context is everything else it reads before it answers.

An agent gathers most of its context itself by calling tools, so your sentence is a small part of what it reads. Better wording can't supply a file it never opened. In chat you pasted everything in by hand. With an agent, you set up what it can reach and what it reads first.

Say it to your agent

“Before you change anything, list the files you have read for this task, what you still need to see, and any name you are assuming exists. Read src/api/checkout.ts and src/discount.ts first, then stop and tell me.”

Chapter 5 said a window has a limit. On a 1M-token window you will rarely reach it. What you reach first is the price of everything you put in.

Context budget

Also called Attention budget

Treating the window as money you spend. Each token that goes in stays in, gets sent again on every later turn, and leaves less room for what comes next. Test logs and whole files are the big purchases.

An agent spends this without asking. A test log nobody needed is read again on each turn after it, and billed each time. Larger windows moved the limit but not the logic. Claude Code's docs say you will "rarely run out", and still advise clearing between tasks, because "a focused context gets you better answers and costs less."

Say it to your agent

“Here is my /context output. Name the five biggest items and say whether this task needs each one. Take any MCP server we haven't used this week out of .mcp.json. From now on, search with rg -n and read line ranges, not whole files.”

So at what point does a full window start to hurt? You will hear a number, so here is how much weight it can bear.

The dumb zone

Also called Smart zone, Context rot

The informal claim that a model gets worse past some point in its window, so you should stay below it. That reliability falls as context grows has support. Any specific percentage is a working rule, because no one has shown us a measured line.

The habit it teaches is good: clear early, and keep noise out. But don't repeat a number as fact, least of all in an interview. Windows went from 200K to 1M, and a percentage and a token count now give very different answers. Watch for symptoms in your own sessions: rereading files, forgetting rules.

Say it to your agent

“If you reread a file you already read, or break a rule in AGENTS.md, stop and tell me. When I see /context pass 100k, I will ask you to write the state to docs/handoff.md and start a new session. That number is our rule of thumb, not a known limit.”

Now the spending, starting with the purchase you make before you type anything.

Instruction budget

Also called Short AGENTS.md

The limit you set on instructions that always load. AGENTS.md goes into every request, so each line has to earn its place on every task, including the many it has nothing to do with. Short and specific beats long and thorough.

Caching makes the dollars small, so that is not the main cost. Agents tend to do what these files say, so each needless requirement makes them do needless work, and a long file buries the rules that matter. Keep what the agent can't work out from the code, and cut the rest.

Say it to your agent

“Go through AGENTS.md line by line. Delete anything you could learn by reading the code, and any overview of the repo. Keep commands and rules the code can't show. Move rules that only apply to src/db/ into .claude/rules/db.md with a paths field. Get it under 100 lines and show me the diff.”

If you can't afford to load it all, load an index and let the agent pull the rest.

Progressive disclosure

Starting the agent with a small entry point and showing it where to look next: a short index now, details when they are needed. A skill's description is the index entry, and its body is the detail.

You keep a whole shelf of procedures for the price of their labels. But the risk moves. The detail arrives only if the label matches, so a vague description means a procedure that never loads, and nothing tells you. Test the label, not just the procedure.

Say it to your agent

“Move the 400-line release procedure out of AGENTS.md into .claude/skills/release/SKILL.md, with the description "Use when cutting a release or bumping the version." Leave one line in AGENTS.md. Start a new session, ask it to cut a release, and show me that the skill loaded.”

Just-in-time retrieval

Also called Just-in-time context, Agentic search

Keeping lightweight pointers, such as file paths and search patterns, and loading what they point to only when it is needed. The agent searches, reads twenty lines and moves on, and never holds the whole repo in view.

You pay only for what the task touches. And what it reads is current, whereas a file loaded an hour ago may have changed since. The price is more tool calls, and an agent that searches for the wrong word may not learn what it missed.

Say it to your agent

“Don't read the whole of src/. Run rg -n "SESSION_TTL" src, open only those lines with 20 lines either side, and tell me the value on disk right now. If the search finds nothing, say so. Don't guess.”

Searching only works if the agent has some idea of where to start.

Codebase map

Also called Repo map

A short description of how a repo is laid out: which folder does what, and where to begin. It gives the agent a picture of the project without reading it, so its first search is aimed at something.

Without one, an agent can spend its first tokens wandering. But this is the most disputed advice in the chapter. Measured evidence says overviews often don't help, because agents find their way with ls and search anyway. So write down only what those can't show: the real entry point, what is generated, what owns what.

Say it to your agent

“Add at most 10 lines to AGENTS.md: the entry point, which folders own the database and auth, and which folder is generated and must not be edited. Anything ls would tell you stays out. Then start a new session and ask it where login is handled.”

Pointing at examples

Also called Prior art

Telling the agent to copy something that already exists: "follow the pattern in src/db/users.ts". One path, and the code does the explaining. It is about the cheapest useful context there is.

Left alone, an agent writes what was common in its training text and not what is common in your repo. A pointer settles naming, errors and test layout in one line. It also copies the flaws, so point at the file you would want more of.

Say it to your agent

“Add a GET /api/orders route. Copy the structure of src/api/users.ts: same validation, same error shape, same test layout as src/api/users.test.ts. Tell me anything you had to do differently, and why.”

Sometimes the text is too big to read and you don't know where the answer is, so a search system picks for you.

Retrieval (RAG)

Also called Retrieval-augmented generation, BM25

Searching a body of text, taking the top matches and putting them in the prompt so the model answers from them. Keyword search (BM25 is the standard scoring formula) finds exact words. Embeddings find related meaning. Each misses what the other finds.

The model sees only what came back, so a missed page may as well not exist, and the answer still sounds sure. For code, the leading agents have moved towards searching live. For big piles of documents nobody can grep usefully, retrieval still earns its place, if you measure it.

Say it to your agent

“Search docs/ with rg first. If we build retrieval, measure it: write 20 real questions, each with the document that answers it, and report how many of those documents appear in the top 5, for BM25 alone and for BM25 with embeddings.”

That was feeding it. Keeping it clean starts with what your own tools print.

Context-efficient output

Also called Context-efficient backpressure

Making your tools print only what an agent can use: one tick when a check passes, and the full output only when it fails. The check still runs in full. Only the reading gets shorter.

A test run that prints 200 lines to say "all good" spends window on nothing, then gets read again each turn. Agents also trim noisy output themselves with head, which keeps only the first lines and can cut off the one failure and force a second full run. Let the exit code decide what gets shown, and not the model.

Say it to your agent

“Write scripts/quiet.sh. It runs a command, saves the output to a temp file, prints one ✓ line on exit 0, and otherwise prints the whole file and exits with the same code. Use it for bun test, bun run typecheck and lint, and put it in AGENTS.md.”

Subagents as context hygiene

Sending noisy work, such as searching or reading big files, to a subagent, so the reading happens in its window and only a short summary comes back to yours. What you are buying is the clean window, not a specialist.

A search through 30 files shouldn't crowd the agent doing the careful work. But it isn't free: it costs more tokens in total, it may be slower because it starts knowing nothing, and you see only its summary, which can be wrong. Now that windows are big, keep it for work that is truly noisy.

Say it to your agent

“Use a subagent to read src/auth/ and find where sessions expire. Return at most 10 lines: file:line and one sentence each, with no code. Also say what you did not check.”

Noise wastes the window. A wrong fact in the window does something worse.

Context poisoning

A mistake that gets into the context and stays: a guess stated as fact, an invented function, a wrong summary. Every later turn reads it again and builds on it, so the agent's own earlier words keep arguing for the error.

A correction is one line against all the lines already written in favour of the mistake. So a third correction rarely works, and starting over with what you learned often beats arguing. Memory files can carry the same error into every future session.

Say it to your agent

“Stop. You have been assuming issuedAt is in seconds, and nothing has shown that. Print one real value from the test fixture. Then write what you found to docs/handoff.md, and I will start a new session from that file.”

Drift

Also called Session drift

A session slowly moving away from what you asked: the scope grows, an early rule stops being followed, the goal changes shape. No single turn looks wrong. You notice when the diff has things in it you never asked for.

Your first message becomes a smaller share of what the model reads, compaction may have removed it, and you are probably not watching closely by then. The defence is short sessions, rules kept on disk and not in chat, and comparing the diff with the original request.

Say it to your agent

“Re-read the task at the top of this session, then run git diff. List anything in the diff I did not ask for, and anything I asked for that is missing. Don't fix either until I have answered.”

There are two ways out of a bloated or poisoned session. The simple one comes first.

Starting fresh

Also called /clear, Context reset

Ending the conversation and beginning a new one with empty context, then giving it only what it needs. Your files and commits stay. What it read and said is gone, unless it was written down.

It costs nothing, and it removes every wrong turn at once. People resist because it feels like losing progress, but anything worth keeping should be in a file anyway. Do it between unrelated tasks, and after two failed corrections.

Say it to your agent

“We are moving to something unrelated. Commit what is done and write anything undecided to docs/handoff.md. I will run /clear, then point you at that file.”

Compaction

Also called /compact, Tool result clearing

Replacing older turns with a summary, so a session can continue in less space. Most tools do it automatically near the limit, or when you ask. Whatever the summary leaves out is gone, and nothing flags the loss.

It is a summary you didn't write, and it loses things. A rule you typed in chat can vanish, and a wrong assumption can survive as fact. So keep rules on disk, where they get reloaded, and if you do compact, say what to keep. Doing it yourself, early, beats waiting for the automatic one.

Say it to your agent

“/compact keep the decision not to add a date library, the failing test name, the exact error text, what we ruled out and the next step. Drop old test logs and file contents.”

Whether you clear or compact, the part you control is what gets written down first.

Handoff note

Also called Structured note-taking

A short file one session writes for the next: what is done, what failed, what was ruled out, what to do next and how to check it. It is all that crosses from one empty context to the next, so it has to stand alone.

The next session will otherwise pay to rediscover everything, or walk into the same dead end. What was ruled out is the part people forget, and it is the most expensive to find twice. A cheerful status report answers none of this, so write it for a stranger.

Say it to your agent

“Write docs/handoff.md before we stop: branch name, what is done with commit hashes, the exact failing test and error, what you ruled out and how, the next step, and the command that checks it. A new agent must be able to carry on from this file alone.”

Do that on purpose at every stage, and you have a workflow.

Research, plan, implement

Also called RPI, Frequent intentional compaction

Splitting work into three phases. Research how the code works now and write it down. Turn that into a plan file. Implement from the plan. Each phase starts from the last one's file with a small window, and you review the files.

A research note and a plan are short enough to read properly, which a 2,000-line diff isn't. So you catch a wrong idea when it is one sentence and not a hundred files. For a small change it is overhead, so skip it. Nobody has measured this properly that we could find.

Say it to your agent

“Phase 1 only: research how checkout applies discounts today. Read code and change nothing. Write docs/research/discounts.md, under 60 lines, with file:line for every claim, then stop so that I can read it. We plan in a new session, from that file.”

Notes for one session are easy. Knowledge that should outlast all your sessions needs a home.

Docs in the repo

Keeping decisions, plans and how-tos as plain files next to the code, not in a wiki or a chat. The agent can search them with the same tools it uses on code, they change in the same commit as the code, and review covers them.

For an agent, a stale doc is worse than none: it believes what it reads, and states it with confidence. So docs in the repo need the same discipline as code, and the discipline can be a check. An agent can also keep them current, if you ask it to in the same commit.

Say it to your agent

“Move the deploy steps out of the wiki into docs/deploy.md, with the commands as they really run today. Then add a CI step that fails if a file path mentioned in docs/ no longer exists.”

The repo as the system of record

Also called System of record

The rule that anything the work depends on lives in the repo, in a form the agent can read. A decision in a meeting, a chat thread or your head doesn't exist for the agent until someone writes it where the agent looks.

It changes what counts as finishing a discussion: a decision isn't made until it is committed. It helps new people as much as agents. It has limits. Peter Naur argued in 1985 that part of a program's theory never gets written down, and a repo can't hold what nobody can say.

Say it to your agent

“We agreed in Slack that refunds over $500 need a second approver. Write that in docs/decisions/refund-approval.md with the date and the reason, link it from AGENTS.md, and add a failing test for it so the rule exists in code too.”

Agent legibility

Also called Legibility, Ambient affordances

How easily an agent can find out what it needs by itself: names it can search for, errors that say what went wrong, logs it can query, an app it can start. Whatever an agent can't observe, it can only guess about.

Poor legibility is paid for in tokens and wrong guesses on every task. Most fixes are ordinary good engineering, with one twist: a name you can grep for now matters more, and code that assembles a name from pieces of text while it runs hides from search. Being findable saves reading, and so saves tokens.

Say it to your agent

“Make this debuggable without me. Add bun run dev:test, which boots the app on a free port with seed data and writes logs to .logs/app.jsonl, then show me you can find a failed request by searching that file. Replace routes built by string concatenation with literal names that rg can find.”

Do it for real

Reading gets you the words. This gets you the experience behind them, and something to show.

Read your own window

Most people have never looked. Knowing what your setup costs before you type a word, and being able to cut it, is evidence that you have done this for real.

  1. Start a new session in a real project and run /context (or your tool's equivalent) before you type anything. Save the output.
  2. Do one ordinary task, and run /context again. Note the three biggest items.
  3. Make two cuts: turn off an unused MCP server or skill, and shorten AGENTS.md. Commit the second.
  4. Run the same task again in a new session, and compare. Say what changed and what didn't. If quality changed, say how you know.

Done when: A before and after table with token counts by category, the commit that shortened AGENTS.md, and one honest sentence about whether it helped.

Build a quiet check wrapper, and try to break it

This is a small script with a measurable result, and it stops a real waste on every run. It is also an easy thing to show someone in a repo.

  1. Write scripts/quiet.sh: run the command, save its output, print one ✓ line on exit 0, and otherwise print everything and exit with the same code.
  2. Measure with wc -c: the output of your test command alone, and through the wrapper, on a passing run.
  3. Break a test on purpose. Confirm that the full failure appears and the exit code is not 0. Then run your suite through head -n 20 and look at what you can no longer see.
  4. Add the wrapper to AGENTS.md, then watch a session and check that the agent really uses it.

Done when: A committed wrapper, the before and after byte counts, and the terminal output of it failing correctly.

Hand off between two empty sessions

A handoff you have never tested is only a hope. The test is cheap: give it to an agent that knows nothing, and see what it gets wrong.

  1. Stop a real task halfway. Ask the agent to write docs/handoff.md: done, failed, ruled out, next, how to check.
  2. Read it yourself, and fix anything untrue.
  3. Start a new session. Tell it only: "Read docs/handoff.md and tell me what you would do next, and what you would avoid."
  4. Note what it had wrong or had to rediscover. Add what was missing to a template and use it next time.

Done when: Your handoff file, committed, plus a short note listing what the fresh session got wrong on its first read.

The build, stage 7 of 18

Starting from nothing

A quiet test wrapper, a settle-up function, and a handoff note that a brand new session followed correctly.

About 45 to 75 minutes, on the same app as every other stage. We ran it first and show what went wrong.

Open stage 7 of the build

Gate 7: Context

0 of 6 right

  1. 1Your suite takes six minutes and prints 3,000 lines, so your agent runs it through head -n 50 to save context. It keeps running the suite twice. What do you change?

  2. 2In an interview someone says: "Everyone knows models get dumb past 40% of the context window." What is the accurate reply?

  3. 3At the start of a long session you typed "use bun, not npm". Four hours later, just after a compaction, the agent runs npm install. What is the best fix?

  4. 4Twenty turns in, the agent is sure the bug is in the cache. You have told it twice that the cache is fine, and it apologises and then blames the cache again. What now?

  5. 5A teammate generates a 900-line AGENTS.md describing every folder, and says that it must help, because it is more information. What does the evidence let you say?

  6. 6You built BM25 search over your handbook. "How do customers sign in?" returns nothing useful, though a page called "Logging in" exists. What is going on?

Get every answer right to install it, and to put 2 files in your repo. Wrong answers cost nothing.

Next chapterThe brief

The workshop

Name a word, or describe what you mean in everyday language.