Back to Hub
Certification Study Notes

Context Engineering & Reliability

Cross-vendor study guide (Claude and Google ADK) covering per-turn context assembly, context budget and placement, sliding-window trimming, summary prefixes and compaction, tool-result clearing, scratchpads and structured note-taking, just-in-time retrieval, sessions, state and memory, subagent context isolation and caching.

Author: Michaël Bettan
Track: Agent Architecture / Foundation
Test Yourself: Context Engineering Practice Quiz →
00

Overview

Definition

Context engineering is the per-call discipline of choosing which tokens enter a model's finite context window (instructions, tool definitions, working state, retrieved material, history and tool results), in what form and in what order, and what is moved outside the window so a long-running agent stays coherent after hundreds of turns.

What context engineering solves for

A model is stateless: at each step it sees only what the harness placed in the window for that call. Agents running in a loop keep producing tokens (tool payloads, reasoning, drafts) and most of them stop mattering a few turns later. Left alone, the window fills, recall of the details that still matter drops, and the agent either hits the hard limit or slowly drifts away from its instructions. Context engineering keeps the window small, current and high-signal for the whole run.

Mental model

treat the window like a kitchen counter during a long dinner service. Only the ingredients for the dish being plated stay on the counter; finished pans go to the sink (clearing), prep notes go on the whiteboard (scratchpad), the pantry is opened only when a recipe calls for something (just-in-time retrieval), and a second cook works a separate station (subagent).

Per-turn context assembly
Stable prefix
instructions, tool schemas, examples
+
Working state & summary prefix
state, scratchpad excerpt, digest
+
Recent window
last turns, newest tool results
→
Model call
then offload notes, state and handles
┌──────────────────────── one model call (finite window) ────────────────────────┐
│  1. Stable prefix    instructions · tool schemas · examples       cacheable    │
│  2. Working state    task values read by key · scratchpad excerpt exact        │
│  3. Summary prefix   compacted digest of older turns              rolling      │
│  4. Recent window    last N turns · newest tool results           verbatim     │
│  5. Current input    user message or task brief                   last         │
└───────────────────────────────────────┬────────────────────────────────────────┘
                                        ▼
        offload what can wait: notes files · state · memory · fetchable handles
01

Prompt vs. Context vs. Memory

Layer/approachTypeRole & behavior
Prompt engineeringAuthoringWording, structure and examples of one instruction; written once, reused on every call
Context engineeringPer-turn curationSelects, orders, compresses, offloads and isolates everything in the window on every call
StateExact working dataKey/value values the harness reads and writes deterministically (IDs, flags, step outputs)
ScratchpadAgent-written notesFiles the agent writes and re-reads during a task (plan, progress, open questions); outlives a context reset, usually not the task
MemoryLong-term recallFacts extracted across sessions and fetched by search or a memory tool; recall is probabilistic and can be stale
Retrieval (RAG)Shared knowledgeDocuments valid for every user (policies, manuals), fetched up front or on demand

Context levers

Key rule

every token draws on the same attention budget. A bigger window raises the ceiling, but irrelevant tokens still lower recall of the relevant ones, so the goal is the smallest set of high-signal tokens for the current step.

Per-turn assembly workflow

  1. Load: read session events, the working state for this task and, if the task uses one, the current scratchpad.
  2. Reduce: apply the history policy (sliding window, summary prefix or compaction) and clear tool results that can be re-fetched.
  3. Fetch: pull in only the documents or memories the next step needs, or expose search tools and let the agent decide.
  4. Place: stable prefix first, then working state and the summary prefix, then recent turns, then the current input.
  5. Call: count tokens when close to the limit and reserve room for the output.
  6. Offload: after the call, write new decisions to state or the scratchpad and replace bulky results with handles.

When not to engineer context

02

Context budget and placement

Budget arithmetic

Placement

Note

Directional figures: the "about four characters per token" heuristic and vendor-reported quality gains from document placement are rules of thumb. Measure on your own prompts with the token counting APIs and an evaluation set.

03

Long sessions: sliding windows, summary prefixes and compaction

Symptoms of an overloaded session

History policies

PolicyHow it worksKeepsLosesFits
Sliding window (trimming)Send only the last N turns or last K tokens; drop older turnsRecent detail, verbatimEverything older, abruptlyChat where old turns rarely matter
Summary prefixA rolling digest of older turns is placed before the recent window and refreshed as turns age outGist of older turns plus recent detailExact wording of summarized turnsAssistants with long back-and-forth
Compaction (reset with summary)Near a threshold, summarize the whole conversation and continue in a fresh window seeded with the summaryDecisions, open issues, key artifactsRedundant tool output and chatterLong agentic runs with tool use
Overlapping compactionEach new summary covers a span that overlaps the previous oneContinuity across summary boundariesSome extra tokensEvent-based compaction in ADK

Tuning a compaction prompt

  1. Collect real traces: pick long, messy runs where a later step depended on an early detail.
  2. Maximize recall first: write the summary instructions so nothing that a later step used is dropped.
  3. Then raise precision: remove categories of content the agent never needed again (raw tool payloads, superseded drafts).
  4. Re-test on new traces: overly aggressive summaries lose details whose importance appears only later.

Vendor mechanisms

MechanismIdentifier and key parametersBehavior
Claude on-demand compactionTop-level compaction: {"type": "summarize", "instructions": ...} (beta compact-2026-09-04)Your app decides when; Claude returns a signed compaction block that you send first in later messages, in place of the summarized turns
Claude threshold compactionEdit compact_20260112 (beta compact-2026-01-12); trigger defaults to 150,000 input tokens; optional instructions; pause_after_compactionServer summarizes when input crosses the trigger; pausing returns stop_reason: "compaction" so you can inspect the summary or re-insert notes
Claude CodeAuto-compact (autoCompactWindow setting), /compact [focus], /context, /clearProject-root CLAUDE.md is re-read from disk after compaction, so durable rules belong there
Agent SDKcompact_boundary system message with compact_metadata (pre_tokens, trigger)Lets the harness log compactions and re-inject state afterwards
ADK event compactionEventsCompactionConfig(compaction_interval, overlap_size, summarizer) on App; token mode uses token_threshold with event_retention_sizeEvery compaction_interval completed events, older events are summarized; overlap_size re-includes earlier compacted events so summaries overlap; recent events stay verbatim

Common trap

relying on early turns to carry a rule once a sliding window or compaction is enabled. Restate durable rules in the system prompt or a re-read file such as CLAUDE.md, so trimming can never remove them.

04

Tool-result clearing and context editing

Claude context editing strategies

StrategyKey parametersBehavior
Tool-result clearing (clear_tool_uses_20250919, beta context-management-2025-06-27)trigger (when clearing starts), keep (recent tool uses kept, default 3), clear_at_least, exclude_tools, clear_tool_inputsReplaces older tool results with placeholders once the prompt crosses the trigger
Thinking-block clearing (clear_thinking_20251015)keep: {"type": "thinking_turns", "value": N} or "all"Drops thinking blocks from older assistant turns; listed first in edits
"context_management": {"edits": [{
  "type": "clear_tool_uses_20250919",
  "trigger": {"type": "input_tokens", "value": 60000},
  "keep": {"type": "tool_uses", "value": 4},
  "exclude_tools": ["memory"]
}]}

Scenario: shipment tracing at Larchmont Freight

A tracing agent calls a carrier API about 40 times per investigation; each response is a large JSON document.

Common trap

clearing with no breadcrumb. If an agent sees neither the result nor a placeholder or note, it assumes the lookup never happened and repeats it.

05

Scratchpads and structured note-taking

# trace.md (agent scratchpad)
Goal: locate pallet LF-88213; customer requires ground transport only
Done: origin scan Reno 11-02 06:10; hub scan Denver 11-03 21:44
Open: no scan since Denver; carrier ticket CT-5512 pending
Next: query Denver hub scan log; re-check ticket at 14:00

Ephemeral vs. Durable notes

KindLifetimeExamplesClean-up
Ephemeral scratchpadOne task or runWorking plan, intermediate tallies, hypotheses being testedDelete or archive when the task closes
Task progress fileUntil the task completes, across resets and sessionsprogress.md, to-do list, test statusRemoved at completion
Durable memoryAcross tasks and sessionsUser preferences, project conventions, lessons learnedConsolidated and expired by policy

Vendor mechanisms

Note-taking workflow

  1. Seed: at task start, create the notes file with the goal and constraints.
  2. Append at milestones: after each confirmed finding or decision, write one line; avoid logging every tool call.
  3. Re-read at boundaries: after compaction, clearing or a new session, read the file before acting.
  4. Prune: collapse completed sections so the file itself stays small.
  5. Close out: delete the ephemeral parts and promote only durable lessons to long-term memory.
06

Just-in-time retrieval

Up-front vs. Just-in-time vs. Hybrid

ApproachLatencyFreshnessRiskFits
Up-frontLowest at run timeAs fresh as the indexWindow filled with loosely relevant chunksStable corpora, single-shot Q&A
Just-in-timeHigher (extra tool calls)Reads the source directlyWasted calls and dead ends without good tools and heuristicsCodebases, large datasets, fast-changing sources
HybridMediumMixedTwo systems to maintainSome essentials preloaded, the rest explored on demand

Scenario: policy lookups at Fernhill Insurance

An underwriting assistant answers questions over 3,000 policy documents that change weekly.

Note

Illustrative figures: the scenario numbers are invented to show the pattern; measure retrieval cost and quality on your own corpus.

07

Session vs. State vs. Memory

StoreHoldsLifetimeRecall
Session (history)The ordered turns and tool calls of one conversationOne conversation (resumable)Replayed into the window, usually trimmed or compacted
StateExact key/value working dataSession, user or app scopeDeterministic read by key
MemoryExtracted facts about a user or domain, across sessionsLong term, with consolidation and expirySearch (similarity or tool call); probabilistic
Files and artifactsLarge outputs, scratchpads, notesUntil deletedRead by name or path

Cross-vendor map

ConcernClaudeGoogle ADK and Agent Platform
StatelessnessThe Messages API keeps nothing between calls; the client resends history every timeThe Runner loads session events from a SessionService before each model call
Session handleAgent SDK and Claude Code session IDsSession keyed by app_name, user_id, session_id
Session storageLocal session transcripts (Agent SDK, Claude Code); your own database for raw API appsInMemorySessionService (dev), DatabaseSessionService, VertexAiSessionService (Agent Platform Sessions)
Exact stateYour application store, or files the agent readssession.state with prefixes: none (session), user:, app:, temp: (never persisted)
Long-term memoryMemory tool (memory_20250818): client-side files under /memories; Claude Code CLAUDE.md hierarchy plus auto memory (MEMORY.md)MemoryService: InMemoryMemoryService (dev, keyword match), VertexAiMemoryBankService (Memory Bank: extraction and consolidation), VertexAiRagMemoryService
Memory read pathThe agent calls the memory tool when it decides toload_memory (agent decides) or PreloadMemoryTool (every turn)
Large outputsFiles API, local filesArtifactService (versioned artifacts)

Where does it belong?

InformationStoreWhy
Ticket ID, approved budget, chosen optionStateMust be exact; read by key every turn
"Prefers reports in French"User-scoped state or long-term memorySurvives sessions; small and stable
Facts learned over many conversationsLong-term memory with consolidationNeeds dedup and updates when facts change
A 40-page contractFile or artifact plus just-in-time readsToo large to replay; open sections on demand
Today's working plan for a multi-hour taskScratchpad fileAgent-curated; survives compaction
Value needed only within this turntemp: state or a local variableMust not leak into the next turn
The tone of yesterday's chatNothingNo future decision depends on it

Memory write policy

Common trap

in ADK, user: and app: state looks persistent but disappears on restart if InMemorySessionService is still configured. Durable scopes need DatabaseSessionService or VertexAiSessionService.

08

Subagent context isolation

Subagent context isolation
            ┌───────────── lead agent window ─────────────┐
            │ plan · state · digests from subagents (~2k) │
            └───────┬───────────────┬───────────────┬─────┘
             brief  │        brief  │        brief  │
            ┌───────▼─────┐ ┌───────▼─────┐ ┌───────▼─────┐
            │ subagent A  │ │ subagent B  │ │ subagent C  │
            │ 40k explore │ │ 25k explore │ │ 30k explore │
            └───────┬─────┘ └───────┬─────┘ └───────┬─────┘
                    └──── digest ───┴──── digest ───┘

Writing the brief and the digest

Scenario: dependency upgrade at Pinecrest Labs

A lead agent upgrades a logging library across 30 services in one repository.

Isolation mistakeConsequenceFix
Lead forwards its full transcriptSubagent starts half full of irrelevant historyWrite a fresh, focused brief
Subagent returns everything it readLead window floods; isolation wastedAsk for a short digest with handles
Brief omits the scope boundarySubagents overlap or wanderState what is in and out of scope
Subagent used for a tiny lookupExtra latency and tokens for no gainCall the tool directly
09

Choosing a strategy

Task shapeFirst leverAdd when needed
Long conversation with steady back-and-forthSummary prefix or compactionDurable rules in the system prompt
Tool-heavy run where payloads dominateTool-result clearingNotes file for findings worth keeping
Iterative work with clear milestones (coding, migrations)Structured note-takingCompaction at a threshold
Broad research or analysis that parallelizesSubagents with digestsNotes file in the lead agent
Large or fast-changing corpusJust-in-time retrievalSmall preloaded catalog (hybrid)
Short task that fits comfortablyNothingMeasure before adding machinery
10

Caching and cost

LeverSavesCosts
Prefix cachingInput price and latency on repeated prefixesCache writes; discipline about ordering
Tool-result clearingWindow space in tool-heavy runsCache invalidation at each clear
CompactionWindow space in long sessionsSummarization call; detail loss
Just-in-time retrievalTokens spent on unused contextExtra tool calls and latency
SubagentsLead window spaceExtra calls and tokens overall

Note

Pricing changes: cache multipliers, minimum cacheable lengths and lifetimes differ by model and change over time. Check the current pricing pages before quoting numbers.

11

Security and operations

Threats specific to context and memory

Controls

Operational metrics

MetricSignal
Tokens per call and per sessionBudget pressure; candidates for clearing or isolation
Compaction and clearing events per sessionSessions that should use notes or subagents
Repeated identical tool callsResults cleared without a breadcrumb or note
Cache hit ratePrefix instability (a timestamp in the system prompt)
Notes file size over timeScratchpad turning into a transcript
12

Failure modes and anti-patterns

SymptomRoot cause → fixTempting wrong answer
Agent ignores a rule stated in turn 2 after many turnsSliding window dropped it → move durable rules to the system prompt or CLAUDE.mdRaising the window size
A subtle early decision vanishes after compactionCompaction prompt tuned for brevity → tune for recall on real traces, then trimDisabling compaction entirely
Agent repeats the same lookup over and overResults cleared with no note → keep tool calls visible and log findings to a notes fileTurning clearing off
Window fills with raw API payloadsNo clearing and verbose tools → enable tool-result clearing; paginate or filter toolsTelling the model to skim
Answers quote outdated policy textUp-front retrieval from a stale index → just-in-time reads from the sourceRetrieving more chunks
Lead agent window floods during researchSubagents return everything they read → ask for short digests with handlesForwarding the lead transcript to subagents
Subagent re-explores what the lead already knowsBrief lacked identifiers and scope → write a focused briefGiving the subagent the whole history
Scratchpad grows to thousands of linesNotes used as a log → milestone entries only, prune completed sectionsCompacting the notes file into memory
Old hypotheses resurface in new tasksEphemeral notes promoted to memory → close out and promote durable lessons onlyBigger memory retrieval limits
user: preferences vanish after deployInMemorySessionService still configured → durable session serviceMoving preferences into temp:
Cache hit rate near zeroTimestamp in the system prompt → move dynamic values after the stable prefixRaising the cache lifetime
A vendor email's instruction applies in later sessionsMemory poisoning → extract facts only, validate writes, auditTelling the model to ignore instructions
13

Glossary

Context techniques

Notes, state and memory

Caching

14

Practice quiz and self-assessment

Audio Deep Dive & Study Downloads

Listen to the 65-minute Context Engineering & Reliability audio deep dive, open the 2-column study guide PDF, 21-slide deck, and sketchnote infographic in the Hub Viewer, or test yourself on scenario-based multiple-choice questions across every section.

Context Engineering & Reliability (Video Walkthrough)
Context Engineering & Production Agent Reliability (Podcast)
Open Study Notes, Slide Deck & Infographic in Hub Viewer Launch the practice quiz →

Self-assessment questions (click to reveal)

Q1. A support assistant keeps only the last 12 turns in its window. Users complain that it forgets the "metric units only" instruction they gave at the start. What is the structural fix?

Durable instructions must not live only in early turns once a sliding window is active. Move the rule into the system prompt or user-scoped state (or a re-read file such as CLAUDE.md) so trimming can never drop it.

Q2. Why is tool-result clearing usually tried before summarization in a tool-heavy agent run?

Clearing removes raw payloads the agent has already acted on without asking a model to rewrite anything, and the tool calls stay visible so the agent can re-fetch. Summarization paraphrases and can drop subtle details.

Q3. What belongs in an agent's scratchpad file, and what should happen to it when the task ends?

Milestone-level notes: the goal, confirmed findings, open questions and next steps, re-read after compaction or a reset. When the task closes, delete the ephemeral parts and promote only durable lessons to long-term memory.

Q4. When does just-in-time retrieval beat preloading the top retrieved chunks?

When the corpus is large or changes often: the agent keeps lightweight references (paths, IDs, queries) and opens only what a step needs, reading the current source. The trade-off is extra tool calls and latency.

Q5. A research subagent reads 40k tokens of sources. What should it hand back to the lead agent?

A condensed digest (often 1,000 to 2,000 tokens) with what it found, handles to where the details live and what it did not check, so the lead's window holds the plan and digests instead of raw exploration output.