Papa Programmer
Lesson 11 of 11

Context for a code assistant

9 min read

Optional

The repository does not fit

A modest project has hundreds of files and millions of tokens of code. The window holds a small part of that, and quality falls well before it is full, as How context goes wrong explains. So the first question for any coding task is which small part to show.

Code differs from prose in a way that helps. It has structure: files, functions, names and imports. A name that appears in the task usually points at the file to read. That makes selection cheaper and more reliable than for free text.

What a code assistant needs

Most coding contexts are built from the same parts.

What it holdsHow it is chosen
RulesProject conventions, commands to run, things to avoidA short file kept in the repository, sent every time
TaskWhat to change, and how to tell it workedWritten by the user
FilesThe code to read and changePicked by name, search or imports
OutlinesNames and signatures of nearby filesGenerated from the code
FeedbackTest output, error messages and diffsProduced by running the code
The parts of a coding context

The rules file deserves care. A short page that says how to run the tests, where things live and what style to follow is read on every request, so every word of it is paid for each time. Keep it to what the assistant cannot work out for itself. The AGENTS.md convention, described at agents.md, gives tools a shared place to put it.

Full text for a few files, outlines for the rest

You rarely need every line of every file. To change a function, you need that function in full and the shape of the code around it. An outline is a list of the names and signatures in a file, a few lines in place of a few hundred. It tells the model that load_order exists and what it takes, without paying for its body.

The program below holds a tiny project and a task. It sends in full any file that mentions a word from the task, and it shows the others as outlines made from their function headers.

python
import re

repo = {
	"refunds.py": "def refund(order, amount):\n    if amount > order['total']:\n        raise ValueError('too much')\n    return order['total'] - amount\n",
	"orders.py": "def load_order(order_id):\n    return {'id': order_id, 'total': 100}\n\ndef list_orders(customer):\n    return []\n",
	"shipping.py": "def estimate(days):\n    return days + 2\n\ndef track(code):\n    return 'in transit'\n",
	"emails.py": "def send_receipt(order):\n    return 'sent'\n",
}

task = "Add a refund limit of 500 to refund()"
wanted = [word for word in re.findall(r"[a-z]+", task.lower()) if len(word) >= 4]

full = [name for name, text in repo.items() if any(word in text.lower() for word in wanted)]
outlines = {name: re.findall(r"^def .*", text, re.M) for name, text in repo.items() if name not in full}

print("in full:", full)
for name, lines in outlines.items():
	print("outline:", name, lines)

everything = sum(len(text) for text in repo.values())
sent = sum(len(repo[name]) for name in full) + sum(len(line) for lines in outlines.values() for line in lines)
print(f"{sent} of {everything} characters sent")

It prints:

text
in full: ['refunds.py']
outline: orders.py ['def load_order(order_id):', 'def list_orders(customer):']
outline: shipping.py ['def estimate(days):', 'def track(code):']
outline: emails.py ['def send_receipt(order):']
241 of 366 characters sent

Only refunds.py is sent in full, because the task names refund. The other files appear as one-line outlines, so the model knows that load_order and send_receipt exist if it needs them. About a third less is sent here. In a real project the saving is far larger, because an outline is a few lines for a file of hundreds.

A word match is a weak way to choose files. Real tools also follow imports, search for symbols, and rank by recent edits. The principle holds: full text where the work is, outlines everywhere else.

Fetch on demand

An agent does not have to be given everything in advance. It can be given a way to look. With a search tool and a file reader, it begins with the task and a list of paths, then searches and opens files as it learns what matters. Each result enters the context only when asked for. This is called just-in-time retrieval, and it is how most coding agents work.

Load it in advanceFetch it on demand
How it worksPick files first, then send themGive search and read tools, let the agent look
SpeedOne request, then an answerSeveral steps before an answer
RiskWrong files chosen, and no way to recoverWandering and extra cost if the task is vague
FitsSmall, well-understood tasksLarge codebases and open-ended tasks
Two ways to supply code

Many systems combine the two: a small set loaded first, and tools for the rest. The Anthropic essay Building effective agents discusses the trade-off, and the Agent loopThe cycle an agent repeats: look at the goal and history, decide the next action, run it and read the result. The program runs the loop. The model only makes the decision. is the cycle of searching, reading and acting that The agent loop describes.

Keep feedback short

Test output is the most useful context a coding assistant can get, and the most wasteful when raw. A failing test run can print thousands of lines. Send the failing test name, the assertion and the few lines of stack trace nearest your own code. The same advice applies to every tool result, as Tool results in context covers.

Clear out what you have finished with

As a task grows, early reads pile up. A file read in step two is not needed in step twenty. A long task can replace finished reads with a note, such as "refund() checked, no limit exists", and restart from the note. Splitting a big job into smaller tasks, each starting with a clean context and the same rules file, is often the better choice. Context window optimisation covers these methods.

Trust nothing from outside the repo

Text inside a file, a comment, an issue or a web page can carry instructions meant to redirect the assistant. Treat it as data, and limit what the AI agentA program that uses a language model to work toward a goal. It chooses its own steps, uses tools to act, reads the results and repeats until the goal is met or a limit stops it. may do without asking. Keep write access narrow and require approval for risky steps, as Permissions and human approval explains.

Full text where you workSend the files the task touches, and outlines for the rest.
Let the agent lookSearch and read tools bring code in only when it is needed.
Trim the feedbackSend the failing line and the nearest stack frames, not a thousand lines of output.

Your reading position is saved

0%

0 of 11 complete

Contents

Learning tools