All chapters
  1. Start hereA model knows only what it can see now
  2. Foundations · 1The context window: tokens, messages and order
  3. Foundations · 2Signals and authority: who is allowed to instruct the model
  4. Foundations · 3The context assembly pipeline: select, rank, deduplicate, pack
  5. Retrieval · 4Retrieval fundamentals: lexical search, embeddings, hybrid search, reranking
  6. Retrieval · 5RAG architecture: chunks, metadata, grounding, citations, freshness
  7. Budget · 6Context budgeting: truncation, dilution, token cost and caching
  8. Budget · 7Compression, summarization and compaction, with loss tests
  9. Agents · 8Coding-agent context: repository maps, instruction files, diffs and tool outputs
  10. Agents · 9Working context, durable memory and checkpoint state
  11. Agents · 10Dynamic context: just-in-time retrieval, selective tool disclosure, delegation
  12. Agents · 11Multi-agent context isolation and scoped handoffs
  13. Trust · 12Context security: injection, poisoning, access controls, tenant boundaries
  14. Trust · 13Measuring context quality: recall, utilization, grounding, ablation
  15. Practice · 14Frameworks and standards: what each one assembles for you
  16. Practice · 15Context in production: versions, drift, refresh, observability, incidents
  17. Practice · 16The insurance lab: one submission, every context decision
  18. ReferenceGlossary
  19. AboutAbout this site and its sources
Agents · 8

Coding-agent context: repository maps, instruction files, diffs and tool outputs

A coding agent cannot read a whole repository. What fills its window: instruction files such as CLAUDE.md and AGENTS.md, a map of the repository, diffs, and the output of every tool it runs.

You will understand
What fills a coding agent's window: instruction files, a repository map, file reads, test logs, diffs.
You will see
Why test logs take most of the window, and why trimming them the usual way hides the failure.
You will be able to
Write instruction files that load cheaply and say where a repository's context should come from.

The policy fixture changed on 1 July 2026: under version 2026.2, rule R-ROOF-01 allows a roof of at most 25 years in wind zone C, down from 30. The underwriting agent of the earlier pages reads that rule from a retrieved passage. But the insurer also has code that applies its rules: a small service, uw-rules-service, that the deterministic tool check_eligibility runs. Its code still says 30.

A developer gives the job to a coding agent: "R-ROOF-01 under policy 2026.2 allows at most 25 years in wind zone C; the code still allows 30. Fix the rule, its test and the changelog." The agent reads a map of the repository, searches for the threshold, reads three files, runs the tests, edits the fixture generator, runs the tests again, sees one failure, fixes the test, runs the tests a third time, updates the changelog and checks the whole diff. Fourteen tool calls.

Here is the second test run, the one after the generator was fixed and before the test was updated, as the agent's harness receives it. It is a log of 64 tests and a summary, 2,278 stand-in tokens. Now suppose the harness has a common, reasonable-looking rule: tool outputs are trimmed to their first 300 tokens, to protect the window. The script below was written for this page and run against examples/uw-context/repo_context.py; it puts the same log into a window three ways.

"""Coding-agents page: three ways to put the failing test log of step 10 into a window."""
from repo_context import session
from tokens import count_tokens, truncate_tokens

log = next(s for s in session() if s["step"] == 10)["output"]
lines = log.splitlines()
head = truncate_tokens(log, 300)
start = next(i for i, line in enumerate(lines) if line.endswith("... FAIL"))
failures = "\n".join(lines[start:])

for name, text in [("full log", log), ("head, 300 tokens", head), ("failures and summary", failures)]:
    print(f"{name:22} {count_tokens(text):>5} tokens  names the failing test: {'test_r_roof_01_limit' in text}")
print()
print(failures)
full log                2278 tokens  names the failing test: True
head, 300 tokens         300 tokens  names the failing test: False
failures and summary     178 tokens  names the failing test: True

test_r_roof_01_limit ... FAIL
======================================================================
FAIL: test_r_roof_01_limit
Traceback (most recent call last):
  File "tests/test_rules.py", line 8, in test_r_roof_01_limit
    self.assertFalse(rules.roof_too_old(30, "C"))
AssertionError: True is not false
Ran 64 tests
FAILED (failures=1)

The head of the log is sixty lines of ... ok. The trimmed window would tell the agent that tests are passing, and the one line that matters, at the end, would be gone without an error. The same log with only its failures and summary is 178 tokens and says everything: which test, which line, which assertion. This is the roof report of Budgeting turned around: the provider put its decisive field first, the test runner puts it last.

This page follows the coding agent through its session and measures where its window goes. It is the site's second example, and every idea from the earlier pages appears in it in a new shape.

A coding agent, and the fixture#

A coding agent is an agent whose tools act on a software repository: it reads files, searches, edits, runs commands such as tests, and proposes a change. Its context is built from the repository and from its own tool results. For example: Claude Code, given the task above, would read files and run the tests itself, step by step, until the change is done.

The example cannot run a real coding agent; it has no model and no shell. It carries a fixture instead (repo_context.py, with repo_context/repo.json): an invented repository of ten files and a scripted session of the fourteen tool calls described above. The fixture counts stand-in tokens per source of context at every step. The instruction files are stored as data inside the JSON, so no tool that loads instruction files picks them up from the example's folder.

Part of the fixtureWhat it isStand-in tokens
CLAUDE.md, AGENTS.mdTwo instruction files165 + 134
Repository mapOne line per file: path and purpose163
src/rules.py, tools/make_fixture.py, tests/test_rules.py, docs/CHANGELOG.mdThe files the task needs420, 260, 206, 75
src/report.py, data/sample_submissions.json, two othersFiles the task does not need822, 4,122, 226
Three test runspython -m unittest, 64 tests eachabout 2,100 to 2,300 each

Everything here is synthetic, and the agent is a scripted stand-in, so these results show how the mechanism works, not how good any model is.

Instruction files: the part that is always there#

An instruction file is a file in the repository that a coding agent's harness loads into the window at the start of a session, so that standing instructions (how to build, how to test, what never to do) do not have to be repeated in every request. It plays the role the system instructions play for the underwriting agent. For example, the fixture's CLAUDE.md:

# uw-rules-service

Synthetic repository for teaching. Rules of the illustrative policy fixture as code.

- Run the tests: `python -m unittest` from the repository root.
- One function per rule id in `src/rules.py`; the rule id is in the docstring.
- Never change a rule without changing its test in `tests/test_rules.py`.
- `src/fixtures/*.json` are generated: edit `tools/make_fixture.py`, then regenerate.
- Record every rule change in `docs/CHANGELOG.md` with the policy version.

Every line of it is something the agent would otherwise have to discover by reading code, or would get wrong. The line about generated fixtures is the one that matters for this task: without it, an agent that finds "max_roof_age_years": 30 in src/fixtures/policy_2026_2.json edits the JSON by hand, and the next regeneration undoes the fix.

Two file names are in wide use, and they are worth telling apart.

CLAUDE.md is the instruction file of Claude Code. Its documentation, read for this page, describes several scopes (a managed file for an organization, a user file in ~/.claude/, the project's ./CLAUDE.md or ./.claude/CLAUDE.md, and a personal CLAUDE.local.md), and says that all the files found from the filesystem root down to the working directory are concatenated into the window rather than overriding each other, with files closer to the working directory read last. Files in subdirectories load on demand, when the agent reads or edits a file there. The documentation recommends staying under 200 lines per file, because longer files consume more context and reduce adherence, and it is explicit about what the file is: Claude treats it as context, not enforced configuration. To block an action whatever the model decides, it points to a hook instead.

AGENTS.md is an open format for the same purpose, "a README for agents" in the words of its site, used by many coding agents (the site lists tools such as Codex, Jules, Cursor, Gemini CLI and GitHub Copilot's coding agent) and stewarded by the Agentic AI Foundation under the Linux Foundation. It is plain Markdown with no required fields. A repository can have one at the root and more in subprojects; the site states the rule for conflicts: the file closest to the edited file wins, and explicit instructions in the chat override everything.

The two meet in Claude Code. Its documentation says that Claude Code reads AGENTS.md when there is no CLAUDE.md, .claude/CLAUDE.md or CLAUDE.local.md in the working directory or above it, and reads only the CLAUDE.md files when both exist; a setting changes that default (for example to read both), and reading AGENTS.md directly requires a recent version (v2.1.277 or later). The fixture loads both files into its window, 299 tokens, like a harness configured to read both. A Claude Code session on this repository with default settings would load the 165 tokens of CLAUDE.md and not the AGENTS.md. If your team keeps both files, decide which one is the source and import or link the other, or the two will drift.

Common confusion. An instruction file is not a configuration file. A line in it is text the model reads, with the same standing as any other instruction: usually followed, never guaranteed. "Never push to main" in CLAUDE.md is a request; a permission rule or a hook that blocks the command is a control. The Signals page explains why text in the window cannot enforce anything; Guardrails Engineering owns the controls.
What this is not. How an instruction file is worded, structured and versioned is prompt engineering: Prompt Engineering. This page treats the file as an item of the working set: when it loads, what it costs, and what it displaces.

A map before the files#

The agent cannot read the whole repository into its window, and should not. A repository map is a short index of a repository: one line per file (or per module, class or function) with its path and what it is for. The agent reads the map first and opens only the files the task needs. For example, three lines of the fixture's map:

src/rules.py: one function per rule id
tools/make_fixture.py: generates the fixture
data/sample_submissions.json: 60 sample submissions

The whole map is 163 stand-in tokens. Loading every file instead costs 6,131, and two thirds of that is data/sample_submissions.json (4,122 tokens), which the task never needs. The fixture runs the session both ways: reading on demand from the map ("just in time"), and loading every file up front.

StepJust in time (map, then reads)Up front (every file at the start)
1, before any tool call3466,477
16, end of the session8,99613,897
16, with old tool results cleared1,3209,272

(Real output of repo_context.py, --upfront and --clear; synthetic stand-in tokens.) Loading up front costs 6,131 tokens on every call of the session, most of them for a file nobody opens. Anthropic's engineering article on context engineering describes Claude Code's approach as a hybrid: the instruction file loaded up front, other files found with search tools when needed. The view below shows the two strategies side by side, step by step; Dynamic context is the home of just-in-time loading and treats it in depth.

Where the window goes#

Here is the whole session, just in time and with nothing cleared (real output of repo_context.py). Each row is the window after that step; each column is one source of context.

uw-rules-service (synthetic): 14 tool calls; clear=off loading=just in time
step tool             instr    map  files search  tests  diffs   msgs  total
   1 -                  299      0      0      0      0      0     47    346
   2 repository_map     299    163      0      0      0      0     66    528
   3 grep               299    163      0    127      0      0     86    675
   4 read_file          299    163    420    127      0      0    102   1111
   5 read_file          299    163    680    127      0      0    131   1400
   6 read_file          299    163    886    127      0      0    154   1629
   7 run_tests          299    163    886    127   2105      0    177   3757
   8 edit_file          299    163    886    127   2105    110    202   3892
   9 run                299    163    886    127   2121    110    223   3929
  10 run_tests          299    163    886    127   4399    110    246   6230
  11 edit_file          299    163    886    127   4399    230    272   6376
  12 run_tests          299    163    886    127   6504    230    292   8501
  13 read_file          299    163    961    127   6504    230    311   8595
  14 edit_file          299    163    961    127   6504    283    330   8667
  15 git_diff           299    163    961    127   6504    566    343   8963
  16 -                  299    163    961    127   6504    566    376   8996

Read the last row as a budget. Test logs: 6,504 of 8,996 tokens, 72 percent. The source code the agent read: 961. The change itself, as diffs: 566. The instruction files: 299, about 3 percent. The three runs of the test suite are the window. And of those three, the agent needs the newest one; the first proves the suite passed before the change, the second shows the one failure, and both have done their job by step 12.

The lab steps through the same session. Move through the steps and switch on "clear old tool results" to see the window when only the newest three tool results are kept in full.

StepToolTotal tokens (no clearing)Total tokens (newest 3 kept)
1-346346
2repository_map528528
3grep675675
4read_file1,1111,111
5read_file1,4001,253
6read_file1,6291,375
7run_tests3,7573,103
8edit_file3,8923,001
9run3,9292,855
10run_tests6,2303,072
11edit_file6,3763,131
12run_tests8,5015,263
13read_file8,5953,100
14edit_file8,6673,075
15git_diff8,9631,287
16-8,9961,320

Diagram: A coding agent's window · seven sources, and how much each takes by the end of the session

Read left to right. The first column is loaded before any work, the second as the agent explores, the third as it runs and changes things. Numbers are the end of the scripted session without clearing: 8,996 stand-in tokens, 6,504 of them test logs.

  1. Loaded at the start
    1. Instruction files: Standing instructions from the repository: how to build, test, and what never to do.
    2. The task: The developer's request for this session.
  2. Exploring
    1. Repository map: One line per file with its purpose; read first, instead of loading the repository.
    2. Search results: Where a term occurs, by file and line.
    3. File reads: The files the task needs, read on demand.
  3. Running and changing
    1. Test logs: Three runs of the suite. The decisive line of a failing run is at the end.
    2. Diffs: Each edit as removed and added lines, and the final git diff of the whole change.
  4. Kept small
    1. Clearing old results: Results older than the newest three become a one-line placeholder naming the call.

With clearing, the window at the end is 1,320 tokens instead of 8,996. The cleared results are replaced by a one-line placeholder that names the call ([tool result of step 7 cleared: run_tests python -m unittest]), so the agent knows the call happened and can repeat it. This is the tool-result clearing of Compaction, and it carries the same condition: it is safe when the agent has written down what it learned. In the scripted session the agent's own lines ("The test still expects 30; updating it.") stay in the messages, which grow from 376 to 610 tokens because each placeholder is a line of its own.

Notice also what clearing cannot fix. At step 12 the window still holds two full test logs (4,383 tokens of tests out of 5,263), because they are among the newest three results. Clearing limits how many old outputs stay; it does nothing about the size of one output. That needs the log treatment from the opening: give the window the failures and the summary, keep the full log in a file, and put its path in the window.

Before AI. A CI system does not email the full build log to the developer; it reports the failing tests with their traces and links to the log. The agent's harness should do the same for the model. The comparison holds further than it seems: a developer who reads 2,000 lines of ok to find one FAIL is slower and makes more mistakes, which is attention dilution in a person.

Diffs: the change as context#

A diff is the representation of a change as removed and added lines. Diff context is a diff used as context for a model: instead of the whole file before and after, the window holds only what changed, with a few unchanged lines around each change so that the reader can place it. For example, the agent's edit of the test, as the fixture records it:

--- a/tests/test_rules.py
+++ b/tests/test_rules.py
-        self.assertFalse(rules.roof_too_old(30, "C"))
-        self.assertTrue(rules.roof_too_old(31, "C"))
+        self.assertFalse(rules.roof_too_old(25, "C"))
+        self.assertTrue(rules.roof_too_old(26, "C"))

(The fixture's diffs are shortened: they omit the hunk headers and context lines a real git diff prints.) Diffs are the cheapest correct description of a change. The whole change of the session (generator, test, changelog) is 283 tokens as the final git diff. In the window above, diffs add up to 566 because every edit appears twice: once when it is made, once in the final git diff. That duplication is useful, because the final diff is the agent's own review of the whole change before it reports, and it is the same object a human reviewer will read.

Diffs are also how context flows out of a coding agent. A pull request is a diff plus a description; a reviewer, human or agent, needs the diff, the task, and the instruction file's rules (one rule change per pull request; name the rule id and the policy version in the title, says the fixture's AGENTS.md). How a change made with a coding agent is reviewed, tested in CI and shipped is the subject of Diff to Deploy.

Production pitfall. A diff without its surrounding code can mislead. A two-line change to a threshold looks safe; the function it sits in may be called with the threshold in another unit. When a diff is the context for a review, give the reviewer the diff with enough unchanged lines around it, and the definitions of the functions it touches, or let the reviewer read them on demand.

The same ideas, both examples#

The coding agent's window is built from the same parts as the underwriting agent's, under different names.

Idea from earlier pagesUnderwriting agentCoding agent
Standing instructions (authority)System instructions, 257 tokensCLAUDE.md / AGENTS.md, 165 to 299 tokens
Selection before loading6 of 15 field groupsA repository map, then the files the task needs
Retrievalsearch_guidance over 31 chunksgrep and file search over the repository
A tool output that floods the windowThe 4,080-token roof report (UW-202)Test logs, 72 percent of the window
Trimming that must keep the decisive partRoof age in the report's first lineThe failure at the end of the log
Clearing old tool resultscompact.py clearrepo_context.py --clear, newest 3 kept
FreshnessSuperseded 2025.4 chunksDocumentation of a version that is not installed
The record of what the model sawThe context manifestMostly not exposed; see below

The last row is the honest gap. The underwriting agent's assembler is your code, so it writes a manifest. A coding agent's harness is usually a product, and its window is assembled for you. What you can still observe, in Claude Code per its documentation: /context shows a live breakdown of context use by category, including which CLAUDE.md and memory files loaded, and /memory opens them.

Diagram: Two examples, one set of ideas · the underwriting agent and the coding agent side by side

Each box on the left has a twin on the right. The mechanism is the same; the names and the shape of the data differ. The one real gap is the manifest: a product harness usually does not write one.

  1. Underwriting agent
    1. System instructions: Who the agent is and how to treat data blocks.
    2. Field selection: Only what this step needs enters the window.
    3. Long tool output: One tool result large enough to crowd out the rule.
    4. Context manifest: The record of what was included and omitted, with reasons.
  2. Coding agent
    1. Instruction file: Standing instructions loaded from the repository at session start.
    2. Map, then reads: Only the files the task needs enter the window.
    3. Test log: One tool result large enough to dominate the window.
    4. What you can observe: Products assemble the window for you; some show a breakdown of context use.

How Claude Code fills the window#

The Claude Code documentation read for this page includes a walkthrough of a session's context window. Before the first prompt, the window holds the system prompt, CLAUDE.md files (or AGENTS.md in their place), auto memory, the names of MCP tools and the descriptions of skills. As the agent works, every file read adds to the window, and path-scoped rules (instruction files that apply only to matching paths) load next to the files they match. Its example session uses illustrative token counts, as this site does.

Two mechanisms on that page are context engineering in product form. A subagent handles a research subtask in its own separate context window, so large file reads stay out of the main one; only its summary and a small metadata trailer come back. (Isolation is this site's home for that pattern; Dynamic context covers delegation.) And compaction, automatic or through /compact, re-reads the project-root CLAUDE.md and auto memory from disk and re-injects them, while instructions given only in conversation are summarized with the rest. The documentation's advice follows from that: an instruction that must survive a long session belongs in CLAUDE.md, not in a chat message. That is pinning, from Compaction, done by the harness.

The harness side of all this (the loop, permissions, hooks, how several coding products name the same jobs) is the subject of a chapter of Harness Engineering: Coding harnesses.

Instruction files are an attack surfaceWho can write the text your agent obeys, and how to limit it

An instruction file is text that enters the window with high authority, and it lives in the repository, where many people and processes can change it. Three consequences.

A pull request can change the agent's instructions. A contributor adds a line to AGENTS.md in a subdirectory ("when you touch this folder, also update the deploy credentials in ..."). The nearest-file rule of AGENTS.md means that line applies when the agent edits files there. Review instruction files as you review CI configuration: required reviewers (code owners) for every CLAUDE.md, AGENTS.md and rules directory, and no agent run on an unreviewed branch with write tools enabled.

Imports reach outside the repository. The Claude Code documentation describes @path imports in CLAUDE.md (up to four hops deep) and shows an approval dialog the first time a project's instruction files import files from outside the working directory. Treat that dialog as a security decision, not a nuisance.

Repository content is data, not instructions. A README, a code comment or a test fixture can contain text that looks like an instruction. The coding agent reads it as a tool result. It deserves the same treatment as the broker attachment of UW-005: delimited, labelled as untrusted, and never able to authorize an action. The controls that do authorize (permission rules, hooks, sandboxing) are outside the window by design; Security covers the attack, Guardrails Engineering the enforcement.

For a Principal engineer: designing a repository for agentsInstruction-file budgets, maps, tool output contracts, and monorepos

Budget the instruction files like the system prompt. They are paid on every call of every session and they sit in the cached prefix. Keep the root file short and stable; push folder-specific rules into nested files or path-scoped rules that load only when relevant; and remember that imports organize a file without reducing its cost, as the Claude Code documentation notes.

Make tool output a contract. The test runner, the linter and the build should have an agent-facing output mode: failures first or only, a summary line, and the path to the full log. That is cheaper and more reliable than any trimming in the harness, and it turns the opening failure of this page into a design decision rather than an accident.

Generate the map, do not write it. A hand-written map drifts as files move. Generate it from the repository (paths plus the first docstring or a one-line description per file), and regenerate it in CI. A stale map is a freshness bug: the agent opens a file that no longer does what the map says.

Monorepos multiply the rules. With nested instruction files, the effective instructions depend on which directory the agent is in. Claude Code concatenates root to leaf; AGENTS.md lets the nearest file win. Write nested files as additions to the root, never contradictions, because the two conventions resolve contradictions differently and the documentation warns that conflicting instructions may be followed arbitrarily.

Measure where the window goes. The fixture's table (tokens per source per step) is the most useful single view of a coding agent's context. Products expose parts of it (/context in Claude Code). If yours does not, log tool output sizes per call yourself; test logs and file reads are almost always the top two.

A checklist for a coding agent's context#

CheckWhy
The root instruction file is short (the Claude Code documentation suggests under 200 lines) and lists build, test and never-do rulesIt is in every window and in the cached prefix
One instruction file is the source; the other imports or links itCLAUDE.md and AGENTS.md drift, and Claude Code reads only CLAUDE.md by default when both exist
Rules that must be enforced are permission rules or hooks, not lines in the fileThe file is context, not configuration
The agent starts from a repository map and reads files on demandUp front, a 4,122-token data file nobody needs rides on every call
Test and build output reaches the window as failures plus summary, with a path to the full logHead-trimming a test log hides the failure
Old tool results are cleared, keeping the newest fewThree test logs were 72 percent of the window
The final diff is in the window before the agent reportsIt is the agent's review of the whole change, and the reviewer's input
Instruction files have required reviewersA pull request can change what the agent obeys

In one breath#

A coding agent's window is the instruction file, a map of the repository, the files it chose to read, and the output of every tool it ran, and the last one dominates: test logs alone can be most of the window. Keep the instruction file short and treat it as context, not control; load a map and read on demand instead of loading the repository; give the window failures and a summary rather than a whole log, because a head-trimmed log hides the one line that matters; clear old results; and end with the diff, the cheapest correct description of the change. Every one of these is an idea from the insurance example under another name.

What comes next#

Both agents now have well-built windows for one call and one run. But some of what they need was never in the run: the underwriter's standing preference for seeing both roof values side by side, the override on another submission last month, the position the run had reached before it was interrupted. The next page, Memory boundary, separates what the model sees now from what is stored between sessions and what is saved as a run's position, and shows how each one enters a window.