Testing Write, Select, Compress, and Isolate in the Claude Agent SDK Deep Search Agent
By Youssef Hosni
Published: 2026-08-28
URL: https://todatabeyond.substack.com/p/evaluating-context-engineering-for
An agent can return a correct report while carrying a poor context architecture. It may retrieve fifteen documents when two contain the necessary evidence, expose dozens of irrelevant tools, preserve a stale memory, keep old tool output active, or send a subagent the parent agent’s entire trajectory. A final-answer grader can mark the run successful without detecting any of those problems.
Part 1 introduced Write, Select, Compress, and Isolate as four operations for controlling context. Part 2 implemented them in a Claude Agent SDK research agent. This final part evaluates those operations directly. The central question is narrower than generic agent evaluation: how do we know that the context given to an agent is actually the right context?
We will use the same research-agent codebase and preserve Part 2’s open-ended task, “Compare the main approaches for long-term memory in production AI agents and explain their trade-offs,” as the end-to-end regression. Controlled fixtures then test individual context policies with known relevant facts, distractors, contradictions, and expected handoffs. This two-level design is necessary because a broad report can reveal whether the system finished, but it cannot identify why a retrieval or memory policy worked.
Get All My 9 Books With 60% Off
Table of Contents:
-
Why Outcome Success Is Not Enough
-
Instrument the Context Pipeline
-
Evaluate Write: Did We Preserve What Matters?
-
Evaluate Select: Retrieval, Evidence Use, and Tool Exposure
-
Evaluate Compress: Did Necessary Information Survive?
-
Evaluate Isolate: Keep Unnecessary State Outside
-
Stress-Test the Four Context Failure Modes
-
Run Context Ablations
-
Build a Scorecard and Optimize the Policy
-
From Naive to Engineered to Evaluated
Get all my 10 AI Courses with 60% off
Want to Go Deeper into Context Engineering?
I am hosting a 3-hour live workshop on Context Engineering, where we will move from the concepts into implementation. You will apply the techniques covered in this series by building a real AI agent, engineering its context throughout the workflow, and evaluating how well the agent performs.
Date: Sunday, 30 August · 18:00–21:00 EEST
1. Why Outcome Success Is Not Enough
Part 2 already gives us a concrete warning. Both the naive and context-engineered research agents produced acceptable artifacts in all three runs. If we measure only task completion, the two systems appear equal:
# measurements/part2-agent-comparison.json
Naive Context-engineered
Artifact success 3 / 3 3 / 3
Mean final context 17,184 32,668 tokens
Mean estimated cost $0.663 $3.270
SDK success result 3 / 3 1 / 3
The engineered version performed more work: it spawned three subagents, wrote workspace artifacts, called more tools, and sometimes needed another query to complete the report contract. Its mean local cost estimate was 4.93 times the naive estimate, and two runs ended with an SDK budget subtype even though the final report artifact passed. These measurements do not prove that context engineering is harmful. They prove that adding memory, retrieval, and subagents does not automatically create an efficient architecture.
Outcome quality asks whether the final report is correct, complete, and properly cited. Context quality inspects the pipeline that produced it. For each model decision, good active context has five properties:
-
Relevant: each item is related to the current decision.
-
Sufficient: the necessary evidence and constraints are present.
-
Correct: supplied information is accurate and current enough for the task.
-
Consistent: contradictions are removed, resolved, or made explicit.
-
Efficient: irrelevant tokens do not substantially exceed the information required.
These properties interact. A context containing one correct fact may be precise but insufficient. A context containing every available document may have perfect recall but poor precision and unnecessary cost. The evaluation target is therefore not “smallest context.” It is the smallest context that preserves the evidence required for the next decision.
The separation between context precision and recall also appears in the RAGAS evaluation framework. More broadly, the Lost in the Middle study found that access to longer context does not make the position of relevant evidence irrelevant. Both results support measuring context composition rather than treating capacity as context quality.
Get all my 10 AI Courses with 60% off
Figure 1 — Outcome evaluation inspects the final answer. Context evaluation inspects which information moved from the available environment into the model’s active context before that answer.
A correct answer is necessary evidence of agent quality, but it is not evidence that the context pipeline was selective, robust, or economical.
Get All My 9 Books With 60% Off
2. Instrument the Context Pipeline
An evaluation harness needs more than application logs. “Called search_memory” tells us which action occurred, but not which instructions, schemas, memories, knowledge chunks, tool results, or history were active when Claude selected it. We need a context trace for each trial.
Anthropic’s agent-evaluation guidance separates a task, repeated trials, graders, a transcript, and the outcome. The transcript is particularly important for agents because two runs can reach the same answer by different tool trajectories. Our trace adds context-specific fields to that structure:
# context_eval/runtime.py
async def run_client_query(*, prompt, options, trace, snapshot_label=”final”):
async with ClaudeSDKClient(options=options) as client:
await client.query(prompt)
async for message in client.receive_response():
trace.observe(message)
if snapshot_label:
trace.observe_context(
snapshot_label,
await client.get_context_usage(),
)
A snapshot separates system-prompt, system-tool, MCP-tool, memory-file, message, and free-space tokens. That breakdown lets us test a claim such as “tool search reduced schema exposure” instead of inferring it from a lower bill. We use the SDK’s structured-output contract because deterministic graders are more reliable when they compare evidence IDs and expected actions rather than parse prose.
The trace is not a prompt dump for permanent retention. Raw traces can contain user data, tool payloads, and secrets, so a production implementation needs access controls, redaction, and a retention policy. The publishable dataset removes the SDK’s visual grid representation from snapshots but preserves the token categories and scored outputs needed to reproduce every result in this article.
Get all my 10 AI Courses with 60% off
Figure 2. A context trace joins what the model received, what it did, and what the run produced. This makes the context policy observable rather than inferred from the final answer.
Get All My 9 Books With 60% Off
3. Evaluate Write: Did We Preserve What Matters?
Write decides what becomes durable state. The test must penalize two different failures: storing noise and failing to store a fact needed later. Those are write precision and write recall.
The fixture contains ten observations: three verified durable facts, three temporary facts, three irrelevant observations, and one contradicted statement. The model must return IDs for the items it would persist. A code-based grader compares that set with the three gold IDs:
# context_eval/scoring.py
def selection_metrics(selected, gold):
selected_ids = set(selected)
gold_ids = set(gold)
true_positive = len(selected_ids & gold_ids)
false_positive = len(selected_ids - gold_ids)
false_negative = len(gold_ids - selected_ids)
precision = true_positive / len(selected_ids) if selected_ids else 0.0
recall = true_positive / len(gold_ids) if gold_ids else 1.0
return {
“precision”: precision,
“recall”: recall,
“false_positive”: false_positive,
“false_negative”: false_negative,
}
The same function is useful for writing and retrieval because both operations select a subset from an available collection. Their interpretation differs: a false positive in Write can become durable context poisoning, while a false negative means a later step may have no way to recover a required decision.
Across two live trials, the agent selected all three durable facts and rejected all seven other observations. Write precision and recall were both 100%, and the contradicted item was never persisted. This is a passing fixture, not proof that arbitrary memory writing is solved. The realistic next step is to expand the fixture with paraphrases, partially verified claims, changing facts, and adversarial instructions, then repeat each case enough times to estimate variance.
Get all my 10 AI Courses with 60% off
Figure 3. Write precision measures whether stored items deserved persistence; write recall measures whether every durable fact crossed into the scratchpad or memory store.
Evaluate the write decision when it occurs. Waiting until a stale or unsupported memory causes a future failure makes the source of the error harder to identify.
Get All My 9 Books With 60% Off

