Sub topic 1
How Coding Agents Read and Use Context
Prerequisites
This chapter assumes you have:
- Basic software development experience in at least one language.
- Familiarity with Git, including branches and diffs.
- Some experience prompting an AI coding assistant or agent.
- Basic knowledge of automated tests, such as running a test suite and reading a failure.
You do not need to know anything about specs yet. This chapter explains the mechanism that makes specs useful. Later chapters build on it.
What "context" means for an agent
A coding agent is a program that wraps a large language model (LLM) with tools. The tools let it read files, search a codebase, edit files, and run commands. The model itself has no memory of your project. Everything it knows about your task at a given moment is the text sent to it in its current request. That text is the context.
The model reads the context and produces the next piece of output. That output is either text for you or a request to call a tool, such as "read src/auth.py". The agent runs the tool and appends the result to the context. Then it calls the model again. This cycle repeats until the model decides the task is done.
This loop explains most agent behavior you will see. The agent can only act on what is in its context at each step. If a fact is not there, the model fills the gap with a guess based on its training data.
What goes into the context
Context for a coding agent comes from several sources. Some you control directly. Others the agent gathers on its own.
| Source | Who supplies it | Typical content |
|---|---|---|
| System prompt | The tool vendor | Tool definitions, general behavior rules |
| Project instruction files | You, committed to the repository | Conventions, commands, constraints |
| Your prompt | You, per task | The task description |
| Files the agent reads | The agent, through tools | Source code, tests, configuration |
| Search and command output | The agent, through tools | Grep results, test failures, build logs |
| Conversation history | Accumulated during the session | Earlier prompts, replies, and tool results |
Two points matter for spec-driven work.
First, only some of this is deterministic. The system prompt and your instruction files are the same every time. The files the agent decides to read are not. Two runs of the same prompt can load different files, and so produce different code.
Second, your prompt is a small part of what the model sees. A short prompt such as "add password reset" sits next to thousands of lines of code, logs, and history. The model has to infer which parts matter.
The context window and its limits
The model can only process a fixed amount of text per request. This limit is the context window, measured in tokens. A token is a chunk of text, roughly three or four characters of English. Code often uses more tokens per line than prose does.
Everything counts against the window: instructions, files read, tool output, and the agent's own earlier replies. When the window fills, the agent has to drop or summarize something. Different tools handle this differently. Common strategies are:
- Truncating the oldest messages.
- Replacing earlier history with a model-written summary.
- Starting a fresh session and carrying over only selected notes.
Each strategy loses information. A summary may omit a constraint you stated early in the session. Truncation may drop it entirely. The agent will not tell you what it forgot, because from its point of view the information never existed.
Window size is not the only limit. Models also use long contexts unevenly. Details buried in the middle of a very long context are more likely to be missed than details near the start or end. A bigger window does not remove the need to put important facts where the agent will find them and to keep irrelevant material out.
How agents find relevant code
Because the whole repository rarely fits in the window, the agent must choose what to load. It typically uses a mix of these techniques:
- Explicit references. You name a file or paste a path in the prompt, and the agent reads it.
- Text search. The agent runs something like
grepfor a function name or an error string. - Directory and symbol listing. The agent lists files or extracts function signatures to get an outline without reading every line.
- Semantic search. Some tools index the code and retrieve passages by meaning rather than exact text.
- Following references. The agent reads a file, sees an import, and opens the imported module.
All of these can miss things. Text search misses code that uses different words for the same idea. Following imports misses behavior that lives in configuration or in another service. The result is a common failure: the agent implements a feature correctly in isolation but duplicates an existing helper or ignores an established pattern, because it never opened the file that showed the pattern.
You can lower this risk by naming the relevant files and patterns yourself. A spec is a durable way to do that, since it can list the modules the work must touch and the conventions it must follow.
Why the same prompt gives different results
Now the source of inconsistency is visible. Consider the prompt "add a password reset feature." Between two runs, these can differ:
- Which files the agent opened first, and so which patterns it saw.
- How it interpreted undefined terms, such as how long a reset link should last.
- Which edge cases it thought of. Does an unregistered email get a different response? What happens to a link used twice?
- Where in the session a clarifying detail appeared, and whether it survived summarization.
- The model's own sampling. Most models choose output with some randomness, so identical context can still yield different text.
None of this is a defect. It is how the system works. The prompt left decisions open, and the agent filled each one with a plausible guess. Some guesses will match what you wanted and some will not. You only learn which after reading the code.
Context quality over context quantity
It is tempting to respond by giving the agent more: paste in the whole design doc, the full API reference, every related file. This often backfires. Irrelevant text uses window space, dilutes the important details, and can pull the agent toward the wrong pattern.
Good context for an agent is:
- Specific. "Reset links expire after 30 minutes" beats "links should expire reasonably soon."
- Checkable. The agent, and you, can tell whether the output satisfies it.
- Stable. It lives in a file, not in a single chat message.
- Scoped. It covers the current task, not the whole project history.
- Consistent. It does not contradict other context. If your instruction file says "use unittest" and the existing tests use pytest, the agent has to guess which to follow.
These five properties are exactly what a spec provides. That is the link between this chapter and the rest of the tutorial.
Instruction files as persistent context
Most agent tools can load certain files automatically at the start of every session. These are project instruction files. Names vary by tool, and AGENTS.md is a common convention. The contents are placed in the context before your first prompt, so they act as standing rules.
A minimal example:
# AGENTS.md
## Workflow
- Read the relevant spec in `specs/<feature>/` before changing code.
- Work on one task from `tasks.md` at a time and stop for review after each.
- Do not change requirements. If one looks wrong, say so and ask.
## Conventions
- Run `pytest` before reporting a task as done.
- Keep new modules under `src/` and tests under `tests/`.Instruction files cost tokens in every session, so keep them short and limited to things that are true across tasks. Task-specific details belong in the spec for that task. A later chapter covers instruction files in detail. For now, note the pattern: stable rules go in instruction files, and feature-specific behavior goes in specs.
Context as a design constraint for specs
Knowing how agents use context gives practical rules for writing specs.
- Put the spec in the repository. A file the agent can open at any point survives summarization and new sessions.
- Point to it explicitly. Name the spec file in the prompt or the instruction file. Do not rely on the agent finding it.
- Keep each document focused. Separate requirements, design, and tasks so the agent can load only what the current step needs.
- Work in small units. A task that touches three files leaves room in the window for the code, the tests, and the output. A task that touches thirty does not.
- Make claims verifiable. Context tells the agent what to aim for. Tests tell both of you whether it got there. The next chapters cover this.
- Start fresh sessions between tasks when needed. A new session with the spec and the current task list is often more reliable than a long session with a degraded history.
Worked example: tracing a context gap
Suppose you ask an agent: "Add password reset by email." The repository already has a send_email helper in src/notifications/mail.py and a convention that all tokens are created with secrets.token_urlsafe.
Here is a plausible run:
- The agent greps for "password" and finds the login module.
- It reads the login module and a user model.
- It writes a new
smtplibcall inline in the reset code, because it never openedsrc/notifications/mail.py. - It generates a token with
uuid.uuid4(), because nothing in its context mentioned the token convention. - It picks a 24-hour expiry, because you did not specify one.
Each of the three problems comes from a context gap, not from bad code generation. Now compare the same task with three additions: an instruction file that says "use src/notifications/mail.py for all email and secrets.token_urlsafe for tokens", and a requirement that says "the system SHALL send a reset link that expires after 30 minutes." The agent no longer has to guess any of the three decisions.
The fix did not make the model smarter. It changed what the model could see.
Summary of the mechanism
- The agent acts only on the text in its current context.
- Context comes from fixed sources (system prompt, instruction files) and gathered sources (files, search, command output, history).
- Gathered context varies between runs, and long sessions lose information.
- Prompts that leave decisions open get those decisions filled by guesses.
- Specific, checkable, stable, scoped, and consistent context reduces guessing.
The next chapter looks at how this inconsistency shows up as drift across prompts, and why a written spec addresses it.
Exercise
An agent was told early in a long session, "never modify files under migrations/." Two hours later it edits a migration file. Give two likely context-related causes, and one change to your workflow that prevents the problem.
Show answer
Likely causes: (1) The early message was truncated or replaced by a summary that dropped the constraint, so it was no longer in the context. (2) The constraint was in the context but was diluted or overlooked among a large amount of later tool output and file content. A preventive change is to move the rule into a project instruction file such as AGENTS.md, which is loaded at the start of every session, and optionally to add a check that fails when files under migrations/ change, so a violation is caught even if the rule is forgotten.
Exercise
List which of these an agent gathers on its own and which you supply: system prompt, AGENTS.md, grep results, your task prompt, test failure output.
Show answer
You supply AGENTS.md and your task prompt. The agent gathers grep results and test failure output by running tools. The system prompt is supplied by the tool vendor, so neither you nor the agent writes it during the session.
Exercise
Why can two runs of the identical prompt "add password reset" produce different code, even with the same repository? Name three reasons.
Show answer
Any three of: the agent may open different files and see different existing patterns; undefined details such as link expiry are filled with different guesses; different edge cases occur to the model; a clarification may be lost to summarization at different points; the model's output sampling is partly random.