Education › Evals & Harness › Stage 3: Harness fundamentals

Context engineering

System prompts, what to load when, compaction and summaries, memory files, token budgets and caching.

Intermediate to advanced ~40 min read Module 11 of 20

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.

After this module you can
  • 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

LayerChangesContents
System promptRarelyRole, rules, safety policy, output format
Tool definitionsRarelyNames, descriptions, schemas
Project instructionsPer projectConventions, commands, gotchas (for example an AGENTS.md file)
Retrieved knowledgePer taskDocs, code, records fetched for this task
Conversation historyEvery turnUser messages, model replies, tool calls
Tool resultsEvery stepOutputs 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.

STABLE PREFIX (CACHEABLE)CHANGES EVERY STEPtrimmedSystem promptTool definitionsProject notesHistoryRetrieved docsTool resultsModel requestprefix firstBudget + compactper-layer limits
Each request combines a stable, cacheable prefix with layers that change every step; the changing layers pass through budgets and compaction before the request is sent.
Assembling a request under per-layer budgets
python
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 msgs

Just-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.
Watch out

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.

Hands-on practice

Instrument and tighten an agent's context

  1. Add per-layer token logging to an agent loop (yours or the minimal loop from the anatomy lesson).
  2. Run five long tasks and chart which layer grows fastest.
  3. Cap tool results with a truncation note and re-run; compare success and tokens per task.
  4. Implement compaction that summarises history beyond a budget into decisions, changes, open issues and next steps.
  5. Add a persistent progress file the agent updates and re-reads; test a task across two sessions.
  6. Reorder the prompt so stable content comes first and measure the cache hit rate if your provider reports it.
Cheat sheet

Context engineering — at a glance

Main things to focus on

  • Context = everything the model knows at this step.
  • Measure tokens per layer; tool results usually grow fastest.
  • Preload rules and the task; fetch the rest just in time.
  • Compaction, persistent notes and sub-agents for long tasks.
  • Stable content first for caching; current request last.
  • Evaluate context changes on success, tokens and cost.

Layers

system promptRules, role, format
tool definitionsSchemas
project instructions (AGENTS.md)Conventions
history + tool resultsGrows every step

Techniques

per-layer budgetsEnforced at assembly
search/read tools with limitsJust-in-time
compaction summaryDecisions, changes, next steps
progress fileState outside the window
sub-agentIsolated context, short result

Caching

stable prefix firstCache hits
no timestamps at the topAvoid cache breaks
request lastClarity

Measure

tokens per layer per callFind the hog
tokens per taskCost
success with vs without compactionInformation loss

Common pitfalls

  • Preloading whole repositories or document sets.
  • Unbounded tool output in history.
  • Compaction that drops user requirements.
  • Timestamps at the top of the prompt breaking the cache.
  • Changing context policy without measuring task success.
Quiz

Check your understanding

5 questions · 4 to pass · answers are explained as you go. Your best score is saved on this device only.

Progress and quiz scores are saved in this browser only. Back up or restore on the hub.

Was this lesson useful? Tell me what to improve →