Sub topic 3
Giving the agent the context it needs
A coding agent works from what it can see. It reads files, runs commands, and reads the output. It does not know your team's habits, your release process, or why a strange function exists, unless those facts are in the files it opens or in the task you write. This chapter covers what context to supply, where to put it, and how to tell when it is wrong or missing.
This chapter assumes you can read and write code in at least one language, use Git branches and diffs, run a test suite and a linter from the command line, and have used an AI coding assistant before. Scoping a task and defining "done" get their own chapter. Here the focus is the background knowledge the agent needs before it starts.
Why context matters more in existing code
In a new project, the agent can choose conventions. In existing code, the conventions are already chosen, and the agent has to match them. Without context, it falls back on common patterns from its training data. Those patterns are often reasonable and still wrong for your codebase.
Typical symptoms of missing context:
- The agent uses a different test framework than the rest of the repository.
- It adds a new dependency when an existing internal helper already does the job.
- It formats code in a style your linter rejects.
- It removes a "redundant" check that guards a case you hit only in production.
- It calls a function that does not exist, because it guessed from the name of a similar one.
Each of these costs a review cycle. Most can be prevented with a few lines of context.
Four kinds of context
Context for a change falls into four groups. Check each before you start.
| Kind | Question it answers | Example |
|---|---|---|
| Project facts | How is this built, run, and tested? | `pytest tests/` runs the tests; Python 3.11; `ruff` is the linter |
| Conventions | How do we write code here? | Money uses `Decimal`, never `float`; no new top-level modules without discussion |
| Task background | Why are we changing this? | We are removing the old tax logic because the rate becomes configurable |
| Constraints | What must not change? | The public signature of `format_invoice` stays the same |
Project facts and conventions change slowly, so they belong in files the agent reads every time. Task background and constraints belong to one change, so they belong in the task description.
Persistent project instructions
Most coding agents load a project instruction file at the start of a session. The file name depends on the tool, for example AGENTS.md, CLAUDE.md, or a rules directory. Check your tool's documentation for the exact name and location. The idea is the same everywhere: a plain text file in the repository that states the facts every task needs.
A good instruction file is short and concrete. It lists commands the agent can copy and conventions it can check.
# Project notes for coding agents
## Commands
- Install: `pip install -e ".[dev]"`
- Test all: `pytest`
- Test one file: `pytest tests/test_pricing.py`
- Lint: `ruff check .`
- Type check: `mypy src/`
## Conventions
- Python 3.11. Use type hints on all new public functions.
- Money values use `decimal.Decimal`. Never use `float` for money.
- Tests live in `tests/` and mirror the module name (`pricing.py` -> `tests/test_pricing.py`).
- Do not add dependencies without asking.
## Things that look wrong but are intentional
- `legacy_round()` in `pricing.py` rounds half up on purpose. Finance depends on it.
- `tests/fixtures/` files are generated. Do not edit them by hand.The last section is the most valuable. Agents tend to "fix" things that look like mistakes. Naming the intentional oddities in advance prevents behavior changes that no test would catch.
Keep the file small and accurate
An instruction file has costs.
- Every line uses part of the agent's limited working memory (its context window), on every task.
- A stale line is worse than no line. If the file says
make testand the Makefile no longer has that target, the agent will fail, or worse, work around the failure. - Long files get skimmed. Rules buried in paragraphs are followed less reliably than short bullets.
Treat the file like code. Review changes to it in pull requests, and update it when a command or convention changes. A good test: if you would not tell a new teammate on their first day, leave it out.
Task-level context
The instruction file cannot know what you are changing today. Put that in the task description. The chapter's example from the plan shows the pattern:
Refactor pricing.py: extract the tax calculation from format_invoice into its own function named calculate_tax.
Constraints:
- Do not change the public signature or the return value of format_invoice.
- Touch only pricing.py and tests/test_pricing.py.
- Run `pytest tests/test_pricing.py` before and after the change and report both results.
First describe your plan in a few bullet points. Wait for my approval before editing.This description names the files in scope, the behavior that must not change, and a way to check the result. For context specifically, add the reason for the change when it affects design choices:
Background: the tax rate will become configurable next quarter, so calculate_tax should take the subtotal only for now, but keep the rate in one named constant so we can replace it later.With that sentence, the agent is likely to create a TAX_RATE constant instead of leaving 0.2 inline. Without it, both outcomes are plausible.
Pointing the agent at the right files
Agents search a repository, but search is not free and not perfect. In a large codebase, the agent may open the wrong module, miss a caller in another package, or read an outdated copy. You can reduce this by naming the starting points.
- Name the files to change and the files to read for reference ("follow the style of
billing/discounts.py"). - Name the callers that matter ("
format_invoiceis called fromapi/invoices.pyandreports/monthly.py"). - Point to an example of the target pattern, especially for migrations ("this module is already migrated; use it as the model").
- Name what to ignore ("
vendor/andgenerated/are not ours").
An example in the repository is often a stronger instruction than a paragraph describing the pattern. If one module already uses the new library correctly, say so. The agent can read it and copy the shape.
Context from running the code
Reading files tells the agent what the code says. Running commands tells it what the code does. Ask the agent to run the test suite, the type checker, or the program itself before it edits, and to include the output in its report. This gives it:
- the baseline: which tests already fail, so it does not take credit for or blame for them
- real error messages instead of guesses
- the actual behavior of unclear code
Record the baseline in your task description when you know it:
Baseline: `pytest` currently has 2 failing tests (test_report_timezone, test_report_locale). They fail on main and are unrelated to this change. Do not try to fix them.Without that line, an agent may spend effort on unrelated failures, or change code to make them pass.
Pasting versus referencing
You can give context by pasting text into the task or by pointing at a file.
- Paste short, stable, essential text: a constraint, an error message, a function signature.
- Reference long or changing material: a design document, an API specification, an issue. If the agent can read the file or fetch the page, a path or link is enough, and the content stays current.
- Do not paste whole files the agent can open itself. It adds noise and may be out of date by the time the agent acts.
Treat any text the agent reads from outside your control, such as web pages, issue comments, or dependency documentation, as data. If an issue comment contains instructions, they come from whoever wrote the comment, not from you. Tell the agent to follow your task description and to report instructions found in other sources instead of acting on them.
Common context mistakes
- Too little context. "Clean up pricing.py" gives no target. The agent chooses its own definition of clean.
- Too much context. Pasting a whole style guide, wiki page, and chat history buries the three rules that matter.
- Stale context. Instruction files, comments, and docs that disagree with the code. When they conflict, the agent may follow either one.
- Hidden knowledge. Facts that live only in people's heads: "we never touch that table on Fridays". If it matters, write it down.
- Assuming the agent remembers. A new session starts without the previous conversation. Decisions made earlier must be in the task, the instruction file, or the repository.
Checking that the agent used the context
Do not assume the context was applied. Ask the agent to restate it before editing. A short check works well:
Before editing, list: (1) the commands you will use to test and lint, (2) the conventions from AGENTS.md that apply to this change, (3) the files you plan to touch.If the list is wrong, you have found the gap before any code changed. If the agent names a convention you never wrote down, it guessed, so add that convention to the instruction file if it is correct, or correct the agent if it is not.
Summary of the working model
- The agent knows only what is in its context: instruction files, your task, files it reads, and command output.
- Put stable facts and conventions in a short, accurate, version-controlled instruction file.
- Put the reason for this change, its constraints, and its baseline in the task description.
- Point at specific files, callers, and example modules instead of expecting the agent to find them.
- Have the agent run commands to get real behavior and a baseline.
- Ask the agent to restate the context before it edits, and fix the gap when the restatement is wrong.
Exercise
Your agent keeps replacing legacy_round() with Python's built-in round() during refactorings, and the finance tests that cover only some inputs still pass. Where should you record that legacy_round() is intentional, and what else would you do to protect the behavior?
Show answer
Record it in the persistent project instruction file under a section for things that look wrong but are intentional, with the reason (finance depends on half-up rounding). That applies the rule to every task. For this particular change, also repeat it in the constraints of the task description if the code is in scope. Because the existing tests cover only some inputs, you would also add characterization tests for legacy_round() (covered in a later chapter) so that a replacement fails a test instead of passing silently.
Exercise
A task description says "Migrate the report module to the new HTTP client." It names no files, no example, and no test command. List three pieces of context you would add.
Show answer
Any three of the following: the files or directory of the report module and the callers to check; an already-migrated module to use as the model for the new client; the command to run the relevant tests and the current baseline of failing tests; constraints such as "do not change function signatures" or "do not add dependencies"; and the reason for the migration, such as which old client is being removed, so the agent knows whether to delete old code.