Sub topic 5
Scoping Work So a Task Fits One Session
Earlier chapters covered the context window, what fills it, and how a crowded context degrades an agent's work. This chapter covers the cheapest fix, which is to size the task before you start. It assumes you have used a coding agent on real repositories, you can read a git diff, and you know that a token is a chunk of text of roughly three to four characters.
Why scope comes first
Compaction, notes, and subagents all help once a session is crowded. Scoping prevents the crowding. A task that needs 40 files, three test runs, and a long design discussion will degrade the session however well you manage it. The same work split into three tasks stays inside a healthy window each time.
Scoping also gives you checkpoints. When a session ends on a green test run and a commit, the next session starts from known good ground. When a session ends halfway through an edit, the next one starts by working out what the first one did.
What makes a task fit
A task fits one session when the agent can finish it, and check it, before the context shows the symptoms you learned to recognize: forgotten decisions, repeated questions, and edits that contradict earlier ones. Four factors drive the fit.
| Factor | Question to ask | Warning sign |
|---|---|---|
| Files touched | How many files must the agent read and edit? | More than about 10 to 15 distinct files |
| Concerns | Is this one change or several that happen to be related? | The description contains "and also" |
| Verification | Can one command confirm the work is correct? | You need manual checks or several test suites |
| Output volume | Will the work produce long logs, diffs, or search results? | Builds, migrations, or broad test runs |
These factors compound. Ten files with a fast, quiet test command fit comfortably. Four files with a 2,000-line test log on every run may not.
A rough budget
You can estimate the reading cost before you start. The script below approximates tokens as characters divided by four. That ratio is crude, and code with long identifiers or unusual symbols often costs more. It is good enough to tell a 3,000-token task from a 60,000-token one.
import sys
from pathlib import Path
CHARS_PER_TOKEN = 4
def estimate_tokens(path):
text = Path(path).read_text(encoding="utf-8", errors="replace")
return len(text) // CHARS_PER_TOKEN
def main(paths, budget=30000):
total = 0
for p in paths:
n = estimate_tokens(p)
total += n
print(f"{n:>8} {p}")
print(f"{total:>8} total (budget {budget})")
if total > budget:
print("Over budget: split the task or read selectively.")
if __name__ == "__main__":
main(sys.argv[1:])Run it on the files you expect the task to touch:
python estimate_tokens.py src/config.py src/loader.py tests/test_config.pyThe budget of 30,000 is an example, not a rule. A sensible budget is a fraction of your window, because the instructions, the conversation, tool output, and the agent's own edits also need room. Reading the files should take well under half of what you have.
Keep in mind that reading is only part of the cost. Each edit adds the new text to the conversation, and each test run adds its output. Budget for the work, not just the inputs.
Splitting along seams
A good split follows a natural boundary in the code or the workflow, so each piece can be finished and checked without the others in mind. Useful seams include:
- Layers. Parsing, business logic, and presentation can often change one at a time.
- Modules. One package or service per session.
- Phases. Add the new path, then migrate callers, then remove the old path.
- Kinds of work. Investigation, implementation, and documentation have very different context profiles.
Take the settings loader migration from the sample progress file in this tutorial: move from INI to TOML without changing the public API. A single instruction to "migrate everything" would pull in the loader, every caller, the tests, and the docs. A scoped plan looks like this:
| Slice | Done condition | Rough size |
|---|---|---|
| 1. Add the TOML parser path in `config.py` | New unit tests for the TOML path pass | 2 files |
| 2. Switch callers to the new path | Existing integration tests pass | 5 to 8 files |
| 3. Remove the INI path and update docs | Full suite passes, docs build | 3 to 4 files |
Each slice ends in a commit. Each has a single command that says whether it worked. The order matters: slice 2 depends on slice 1, but the agent in slice 2 does not need to remember how slice 1 was written. It needs only the result, which lives in the code and in your notes.
Writing the task statement
The task statement is where scope is enforced. A good one names the goal, the boundary, and the stop condition. Compare these two:
Migrate the settings loader to TOML.Goal: add a TOML parsing path to src/config.py behind the existing load_settings().
In scope: src/config.py and tests/test_config.py.
Out of scope: callers of load_settings(), docs, removing INI support.
Done when: pytest tests/test_config.py -q passes and the diff touches only the two files above.
If you find something else that needs changing, list it at the end instead of changing it.The second version gives the agent a boundary it can check itself against. The last line matters most. It turns scope creep into a list you can review, not extra edits and extra reading.
Edge cases
Tasks that resist splitting. A rename across 200 files cannot be done one slice at a time in a sensible way. Do not ask the agent to open each file. Use a mechanical tool such as a codemod, a refactoring command, or a scripted search and replace. Have the agent write and verify the script, then run it and check the result with a compile or test pass. The agent's context holds the script and a summary of the output, not 200 files.
Unknown size. You cannot scope a task you have not looked at. Run a time-boxed investigation session whose only output is a notes file: which files matter, what the risks are, and a proposed split. That session may be messy, and that is fine, because you throw away its conversation and keep the notes. The next chapters cover how to structure those files.
Hidden dependencies between slices. Sometimes slice 3 depends on a decision made in slice 1, such as a naming scheme or an error type. Write that decision into the notes file and the code comments at the end of slice 1. If you rely on the agent to remember it, you are relying on exactly what a fresh session lacks.
Over-splitting. Every session pays a startup cost for instructions, orientation, and re-reading. Slices so small that each costs more to start than to do waste effort and add handoff risk. If two slices share most of the same files, combine them.
Scope creep during the session. The agent will notice a failing unrelated test, an outdated comment, or a tempting cleanup. Decide in advance that these go on a list. If one turns out to block the task, stop and widen the scope on purpose, then re-check the budget.
Estimates that were wrong. If the session is already showing degradation and the task is half done, do not push through. Commit what works, write down where you stopped, and finish in a new session. A smaller slice that completes is worth more than a larger one that drifts.
Common errors
- Scoping by feature name, not by files. "Add caching" sounds small and may touch 30 files. Look at the code before you decide.
- Done conditions that need judgment. "The loader feels cleaner" cannot be checked. Use a command with a pass or fail result.
- Ignoring output size. A test suite that prints 5,000 lines per run can consume a slice's budget by itself. Plan for bounded output, as covered later in this tutorial.
- Slicing by time. "Work on this for an hour" has no relationship to context use. Slice by seams and done conditions.
- Starting the next slice in the same session by default. After a commit and a green check, a clean break is often cheaper than carrying the old conversation forward.
Summary of the method
- Look at the code and estimate files, concerns, and output volume.
- If the size is unknown, run an investigation session that ends in notes.
- Split along seams so each slice has one done condition and ends in a commit.
- State the goal, the boundary, and the stop condition in the task statement.
- Park anything outside the boundary on a list.
- If a slice proves too big mid-session, commit, record where you stopped, and continue fresh.
Exercise
You need to replace a deprecated logging helper with a new one. A search shows 140 call sites across 60 files, plus two test modules that check log formats. Propose how to scope this work into sessions, and name the done condition for each.
Show answer
Do not have the agent edit 60 files by hand in one session. Session 1 (investigation and tooling): confirm that the call patterns are regular, then write a codemod or scripted replacement and a short notes file listing exceptions. Done when the script runs on a sample directory and the diff looks correct. Session 2 (apply and verify): run the script across the repository, handle the exceptions the script flagged, and check the result with the full test suite. Done when the suite passes and a search finds no remaining uses of the old helper. Session 3 (optional, cleanup): remove the old helper and update the two log-format tests and any docs. Done when the suite passes and the old helper is gone. Each session ends in a commit, and the notes file records the exceptions and decisions between sessions.
Exercise
A task statement reads: "Improve error handling in the API layer and also fix the flaky upload test." Name two problems with this statement as a scope definition and rewrite it.
Show answer
The statement joins two unrelated concerns ("and also"), and it has no boundary or done condition, so "improve" can expand to any number of files. Split it into two tasks. Task 1: "Add typed errors to the request handlers in api/handlers/. Out of scope: other directories and the upload test. Done when pytest tests/api -q passes and each handler returns an error from the new error module." Task 2: "Find the cause of the flaky testuploadlarge and fix it. In scope: tests/test_upload.py and the upload module. Done when the test passes 20 runs in a row." Each task can be verified separately and fits its own session.