Everything an agent knows at a given step is what the harness put into the context window for that request. Context engineering is the practice of deciding what goes in, in what order, in what form, and what gets left out, summarised or fetched later. It matters because context is finite, costs money on every call, and degrades in quality when it is cluttered: models attend less reliably to details buried in long, noisy prompts. This lesson covers the layers of context, budgeting, just-in-time retrieval, compaction, persistent notes, sub-agents for isolation, and ordering for prompt caching.
- List the layers of an agent's context and what belongs in each
- Budget the context window and measure what consumes it
- Prefer just-in-time retrieval over preloading large content
- Apply compaction, persistent notes and sub-agents to long tasks
- Order context to take advantage of prompt caching
The layers of context
| Layer | Changes | Contents |
|---|---|---|
| System prompt | Rarely | Role, rules, safety policy, output format |
| Tool definitions | Rarely | Names, descriptions, schemas |
| Project instructions | Per project | Conventions, commands, gotchas (for example an AGENTS.md file) |
| Retrieved knowledge | Per task | Docs, code, records fetched for this task |
| Conversation history | Every turn | User messages, model replies, tool calls |
| Tool results | Every step | Outputs of commands, searches and reads |
Each layer competes for the same window. In long agent sessions, tool results usually grow fastest: a few test runs, file reads and search results can dwarf everything else. Context engineering starts with measuring which layer is consuming the budget.
Budgets and measurement
Give each layer a budget and enforce it when assembling the request. Log the token count of each layer on every call, so you can see when a session is approaching its limit and which layer caused it. Treat the window as a scarce resource even when the model offers a very large one: more context means more cost and latency on every step, and important details are easier to miss in a long, noisy prompt.
BUDGET = {"system": 3_000, "tools": 4_000, "project": 2_000,
"history": 40_000, "results": 20_000}
def assemble(state) -> list[dict]:
msgs = [system_msg(clip(state.system, BUDGET["system"]))]
msgs.append(project_msg(clip(state.project_notes, BUDGET["project"])))
history = recent_within(state.history, BUDGET["history"]) # newest turns first
if len(history) < len(state.history):
msgs.append(summary_msg(state.summary)) # compacted older turns
msgs += history
log_tokens({k: count_tokens(v) for k, v in by_layer(msgs).items()})
return msgsJust-in-time beats preloading
Early RAG systems stuffed every possibly relevant document into the prompt up front. Agents can do better: give them lightweight references (file paths, document titles, search tools) and let them fetch details when needed. A coding agent that can list directories, search for a symbol and read a range of lines needs far less context than one given the whole repository, and it reads what is relevant to the current step.
- Preload only what is needed on almost every step: rules, conventions, the task itself.
- Expose search and read tools with limits and offsets for everything else.
- Return file and document references in results, so the agent can choose to open them.
- Keep a short index (names and one-line descriptions) in context instead of full contents.
Long tasks: compaction, notes and sub-agents
- Compaction: when history nears its budget, summarise older turns into decisions made, files changed, open problems and next steps, then drop the raw turns. Clear old tool results first; they are rarely needed verbatim.
- Persistent notes: let the agent write a progress file or task list outside the context window and re-read it, so state survives compaction and even new sessions.
- Sub-agents: delegate a self-contained subtask (search the codebase for usages, read these ten documents) to a fresh agent with its own clean context, and return only a short result to the main agent.
- Structured state: keep facts the harness can track (current branch, files edited, test status) in data structures and render a compact view, rather than relying on the model to remember them from history.
Compaction loses information. Test it: run long tasks with and without compaction on your benchmark and check which details the summary dropped. Keep anything the user stated as a requirement verbatim.
Order for caching and clarity
Many providers can cache a prompt prefix that repeats across requests, which reduces cost and latency for the cached part. Put stable content first (system prompt, tool definitions, project instructions) and changing content last (history and new results), and avoid inserting timestamps or random IDs near the top, which break the cache on every call. The same ordering helps clarity: rules first, then background, then the current situation and the immediate request at the end.
Finally, evaluate context changes like any other harness change. A different summary prompt, a smaller result budget or a new project instruction can raise or lower task success; measure success, tokens per task and cost together on the benchmark before keeping the change.