Sub topic 4
Giving the agent the right context
This chapter assumes you have used chat in VS Code, you know what the agent loop is (plan, call tools, observe, repeat), and you are comfortable with Git and the terminal. It covers what the agent can see, how to add to it, and how to fix a session when it has the wrong picture.
Why context decides the result
The model behind the agent knows nothing about your project except what is in its current input. That input is called the context. It holds your prompt, the system instructions, the conversation so far, attached files, and the output of every tool call. The model has a fixed context window, a maximum amount of text it can consider at once, measured in tokens (small chunks of text).
Two failure modes follow from this:
- Too little context. The agent guesses at function names, invents APIs, or duplicates code that already exists.
- Too much or noisy context. Relevant details get buried, responses slow down, and old conversation history can crowd out new information.
The goal is not to attach everything. It is to give the agent the smallest set of material that makes the task unambiguous, and to let it fetch the rest.
Where context comes from
Context reaches the agent in three ways. You supply some of it, the editor adds some automatically, and the agent gathers the rest through tool calls.
| Source | Who adds it | Examples |
|---|---|---|
| Explicit attachments | You | Files, folders, selections, images, web pages |
| Implicit context | The editor | The active file, the current selection |
| Tool results | The agent | Search hits, file reads, terminal output, test failures |
| Instructions | Configuration | Custom instructions files (covered in a later chapter) |
In agent mode, tool results usually end up as the largest share. When the agent searches your code and reads five files, those five files now take up space in the window, whether or not they mattered.
Explicit attachments in VS Code
You attach context in two ways. The first is the Add Context button in the chat input, which opens a picker. The second is typing # in the prompt, which lists the available references. You can also drag a file from the Explorer onto the chat view.
Common references include these. Exact names and availability vary by VS Code version and extensions, so check the # list in your own editor.
| Reference | What it attaches | Best used when |
|---|---|---|
| `#file` | One named file | You know exactly which file matters |
| `#folder` | A directory | A feature spans several files in one place |
| `#selection` | The highlighted code | The task concerns one function or block |
| `#codebase` | A search across the workspace | You do not know where the relevant code lives |
| `#problems` | Current diagnostics from the Problems panel | Fixing compiler or lint errors |
| `#terminalLastCommand` | The last terminal command and its output | Explaining or fixing a failed command |
| `#changes` | Uncommitted source control changes | Reviewing or finishing in-progress work |
| `#fetch` | The content of a URL | The task depends on external documentation |
You can also attach screenshots and images if the selected model supports image input. This helps with UI bugs, error dialogs, and design mockups.
A prompt that combines references looks like this:
Refactor #selection to use the retry helper in #file:src/net/retry.ts.
Match the error handling style used in #file:src/net/client.ts.Files versus search
Attaching a file puts its content into the window up front. Using #codebase asks the editor to search your workspace and return the most relevant snippets, which the agent then reads. The trade-off:
- Attach files when you already know the location. It is deterministic and cheap in tool calls.
- Use search when you do not. It is flexible, but results depend on how the index ranks your query, so it can miss files with unusual naming.
In agent mode you often do not need #codebase at all, because the agent can call its own search and read tools. Naming the files you know about still saves it several exploratory steps.
Implicit context and its surprises
The editor can attach the active file or current selection automatically. This is convenient, but it causes a common error: you ask a question with an unrelated file open, and the agent treats that file as relevant.
Check the context chips shown in the chat input before you send. Remove anything that does not belong. Likewise, an old selection can linger, so deselect text in the editor if you want a general question treated generally.
What the agent adds by itself
When the task is open-ended, the agent explores. A typical sequence for "why does login fail for expired tokens?" is a text search for expired, a read of the auth module, a read of its tests, and a terminal run of the test suite. Each result is appended to the context.
You can see these steps in the chat as tool calls. Reading them tells you what the agent believes. If it never opened the file that holds the bug, you now know why its answer is wrong, and you can attach that file and ask again.
This is also why vague prompts are costly. "Improve the API" sends the agent on a wide search that fills the window with files you did not care about. Prompt-writing is covered in a later chapter. Here the point is that every tool result occupies space.
Keeping the window healthy
Long sessions degrade. The window fills with old file contents, abandoned approaches, and long test output. Some editors summarize or trim older messages automatically, and details can be lost when they do. Signs that the session has drifted:
- The agent forgets a constraint you stated early on.
- It re-reads files it already read.
- It re-introduces a bug you asked it to remove.
- It contradicts its own earlier decisions.
Practical countermeasures:
- Start a new chat for each distinct task. A fresh session carries no stale history.
- Put durable rules in an instructions file rather than in chat. Instructions are re-sent every time, so they survive a fresh session.
- Restate key facts after a long exchange, in one short message.
- Ask for a handoff summary before you reset: the goal, decisions made, files changed, and what remains. Paste it into the new chat.
- Prefer narrow attachments. Attach a function with
#selectioninstead of a 2,000-line file.
Controlling what the agent should not see
Context is also a data-handling decision. Anything in the window is sent to the model provider. Do not attach files that contain credentials, private keys, or customer data. If the agent reads a .env file through a tool call, those values enter the context too.
Mitigations:
- Keep secrets out of the workspace where possible, and load them from a secret manager or the environment.
- Use your organization's content exclusion settings if your plan provides them.
- Watch tool calls that read files you did not intend it to read, and deny them (approval is covered in a later chapter).
Worked example: fixing a failing test
Suppose npm test fails and you want the agent to fix it. Compare two approaches.
A weak prompt:
Tests are failing, fix it.The agent has no failure details, so it must run the tests itself, parse the output, and search for the cause.
A stronger prompt attaches exactly what you know:
The test in #file:src/users.test.ts fails after my last change.
See the output in #terminalLastCommand.
The likely cause is in #file:src/users.ts. Fix the source, not the test,
then run npm test again to confirm.This supplies the failing test, the real error text, the suspect file, and a constraint. Fewer exploratory tool calls are needed, and the answer is easier to check.
If you are unsure what changed, you can see your uncommitted edits with Git and attach them:
git diff --stat
git diff -- src/users.tsAttaching #changes gives the agent the same view without leaving chat.
Context across IDEs
Other editors expose the same ideas under different names. JetBrains IDEs, Cursor, and similar tools generally offer file and folder attachments, a way to reference selected code, and a codebase search. The syntax differs, for example @ mentions instead of # references. The principles in this chapter apply unchanged: attach what you know, let the agent search for what you do not, and reset when the session drifts.
Common mistakes
- Attaching an entire repository folder when one file is the target.
- Leaving an unrelated active file in the context chips.
- Continuing one chat across several unrelated tasks.
- Pasting terminal output by hand when a reference to the last command would be exact.
- Assuming the agent has read a file because it mentioned it. Check the tool calls.
Exercise
The agent keeps ignoring a naming convention you gave it 40 messages ago in a long chat, and it has started re-reading files it already opened. What is the likely cause, and what two steps would you take?
Show answer
The context window is crowded or has been trimmed or summarized, so the early constraint is no longer reliably in view. First, ask the agent for a short handoff summary (goal, decisions, files changed, remaining work) and start a new chat with it. Second, move the naming convention into a custom instructions file so it is sent with every session instead of depending on chat history.
Exercise
You want the agent to fix a bug in one function, but you do not know which file it is in. Which context approach fits, and what should you check afterward?
Show answer
Describe the bug and let the agent search, either by using #codebase or by letting it call its own search tools. Afterward, read the tool calls to confirm it opened the file that actually contains the function. If it did not, attach the correct file and repeat the request.