Sub topic 7
Reading only what you need from the codebase
This chapter assumes you have used a coding agent in a terminal, know basic shell tools such as grep and sed, and use git. It builds on the earlier chapters about what fills the context window. Here the focus is one of the biggest contributors: file reads.
Why reads dominate the budget
Every file an agent opens is copied into the context as text. It stays there for the rest of the session, or until compaction removes it. A 2,000-line source file can cost around 20,000 to 30,000 tokens. Reading five such files "to get oriented" can use a large share of the window before any real work starts.
The cost is also repeated. If the agent reads a file, edits it, and reads it again to check the result, the file is in the context twice. Old copies are stale, and they can mislead the model when it later has to decide which version is current.
The goal is not to avoid reading. The agent cannot edit code it has not seen. The goal is to read the smallest slice that answers the current question.
Search first, then read
A reliable pattern has three steps:
- Locate: search for a name, string, or pattern to find which files and lines matter.
- Narrow: cap the number of search results.
- Read: print only a line range around the match.
# Find the definition first, then read only the lines around it
grep -rn "def parse_config" src | head -n 20
sed -n '120,180p' src/config.pyThe search returns one line per match, and head -n 20 limits the list even if the pattern is common. The sed -n '120,180p' command prints lines 120 to 180 only. Together they put a few dozen lines into the context instead of an entire file.
Choosing the search term
Search terms vary in how much they narrow things down.
| Search term | Typical result size | Use it when |
|---|---|---|
| A definition such as `def parse_config` | Very small, often one hit | You know the name of the function or class |
| An error message string | Small | You are tracing where a failure comes from |
| A call site such as `parse_config(` | Medium | You need to see how callers use an API |
| A generic word such as `config` | Large | Almost never; refine the term first |
If a search returns hundreds of lines, do not read them all. Change the query instead: add a path, a file type, or a more specific identifier.
# Narrow by directory and file type, and list file names only
grep -rln "parse_config" src --include="*.py"
# Count matches per file to see where the hits cluster
grep -rc "parse_config" src --include="*.py" | grep -v ":0"The -l flag lists only file names. The -c flag counts matches per file, and the second grep drops files with zero matches. Both give you a map of the codebase without any file content.
Look at structure before content
Often you need to know what a file contains, not what every line says. A list of function and class names is much smaller than the code.
# Outline a Python file: only top-level definitions and their line numbers
grep -nE "^(class|def) " src/config.pyThe output might look like this:
14:class ConfigError(Exception):
31:def load_settings(path):
88:def parse_config(text):
152:def merge_defaults(cfg, defaults):Now you know that parse_config starts at line 88 and the next definition starts at line 152. You can read lines 88 to 151 and skip the rest. Many agents offer a symbol or outline tool that does the same job with better language support. Prefer it when it is available, because a regular expression can miss decorators, nested definitions, or unusual formatting.
Read in ranges and widen on demand
Start with a tight range, then widen only if the first read is not enough. A good first range covers the whole function or block you care about, plus a few lines before it for imports or decorators.
# The function body, plus a little context above it
sed -n '84,151p' src/config.py
# Need the imports too? Read just the top of the file
sed -n '1,25p' src/config.pyTwo small reads cost less than one full read, and they are more precise. Many agent file-read tools accept an offset and a line count, which is the same idea. Use them.
For files you only need to scan, use head or tail.
# The first lines of a file: license, imports, module docstring
head -n 30 src/config.py
# The last lines of a log: usually the most recent events
tail -n 50 logs/app.logUse version control to read only what changed
When the task is about recent work, a diff is a much smaller input than the files it touches.
# Which files changed, and by how much
git diff --stat main
# Only the changed hunks in one file, with 3 lines of context
git diff -U3 main -- src/config.py
# What a single earlier commit did
git show --stat HEAD~1git diff --stat costs a few lines and tells you where to look. git diff -U3 shows only the changed hunks with three lines of context on each side. For review tasks, regression hunting, and resuming interrupted work, this is usually the right starting point.
Skip what is not source
Some files are large and rarely useful to read in full:
- Lock files such as
package-lock.jsonorpoetry.lock - Generated code, build output, and minified bundles
- Vendored dependencies and
node_modules - Data files, fixtures, and snapshots
- Long logs
Most search tools respect .gitignore, which keeps many of these out by default. Check that yours does. If a generated file is the thing you must understand, read its generator or its schema instead. If you must inspect a data file, look at its shape: the first few lines, the column names, or the count of records.
# Peek at a large CSV: header plus three rows, and a row count
head -n 4 data/orders.csv
wc -l data/orders.csvDecide what to read: a flow
The decision order below keeps reads small. Move to the next step only when the previous one does not answer the question.
When reading the whole file is right
Targeted reading is a default, not a rule. Read the whole file when:
- The file is short, roughly under 150 lines. The overhead of several partial reads can exceed the cost of one full read.
- You are about to rewrite or restructure most of it, so every part matters.
- The logic is tightly coupled, and a partial view has already led to a wrong guess.
- The file is a configuration or interface definition whose every line carries meaning.
Check the size before you decide. Reading wc -l output costs almost nothing.
wc -l src/config.py src/loader.py src/cli.pyCommon errors
- Reading to get oriented. Opening many files "just in case" fills the context with code that never matters. Ask a specific question first, then search for the answer.
- Uncapped search output. A broad
grep -rnon a large repository can return thousands of lines. Always cap withhead, narrow the path, or use-lor-c. - Re-reading unchanged files. If the file has not changed since you read it, the earlier copy is still in the context. Refer to it instead of reading it again.
- Reading a range that is too narrow. A slice that cuts off the middle of a function can lead to a wrong edit. Include the full block, and check that the range starts and ends on a boundary.
- Trusting stale line numbers. After an edit, line numbers shift. Re-run the search before reading a range from an earlier result.
- Reading output you could filter. For logs and data, filter with
grep,head, ortailbefore the content reaches the context.
A worked example
Suppose a bug report says that load_settings ignores the timeout key. A narrow path through the code looks like this:
# 1. Where is the key handled?
grep -rn "timeout" src --include="*.py" | head -n 20
# 2. Outline the likely file
grep -nE "^(class|def) " src/config.py
# 3. Read only the function that builds the result
sed -n '88,151p' src/config.py
# 4. After fixing it, read only what changed
git diff -U3 -- src/config.pyFour commands, each with bounded output, take the agent from the report to a verified change. The whole files config.py, loader.py, and the test suite never enter the context.
Exercise
A search for retry in a large repository returns about 900 lines. List two ways to reduce the output before reading any file, and explain why you should not simply open the files that look most relevant.
Show answer
First, change the query so it matches less: restrict the path (for example src/net), add --include="*.py", or search for a more specific identifier such as retry_policy or a call site like retry(. Second, change the output type: use grep -l to list only file names or grep -c to count matches per file, and cap the list with head -n 20. Opening the files that merely look relevant spends context on whole files when you do not yet know which function matters. Narrow the search, outline the best candidate, and read only the line range of the relevant function.
Exercise
You noted that the function parse_config was at lines 88 to 151. After an edit that added 12 lines near the top of the file, you want to re-read it. What should you do, and why?
Show answer
Search for the symbol again (for example grep -n "def parse_config" src/config.py) and read the new range from the fresh result. The inserted lines moved the function down, so lines 88 to 151 now show different code, probably the end of an earlier function and the start of the target. Reusing stale line numbers can produce a misleading read or a wrong edit.