CCDV-P Study Guide
Free study guide for the Claude Certified Developer - Professional (CCDV-P) exam: 25 lessons, one per official skill, on running Claude systems in production. One chapter per exam domain, one page per lesson, in the order the official exam guide lists them.
1. Domain 1: Advanced Agent Architecture and Orchestration
1.4. 1.4 Context and memory architecture for long-running agents
CCDV-P · Domain 1 · Lesson 1.4 · 20 min read
Keep a 200-turn, 340-tool agent accurate and under budget with tool search, context editing, compaction, the memory tool and cache-safe instruction changes.
Why turn 200 costs more than the first fifty turns together
Larkspur Software sells workflow-automation software to enterprises, and inside the product sits a support agent that helps customer admins fix their integrations. It can reach all 340 of them as tools, from crm_get_sync_status to sso_test_connection, and a stubborn setup problem can keep an admin talking to it for 200 turns. Dalia, the engineer who owns the agent's budget, has a monthly ceiling of $150,000. On the 20th the month stands at $131,000, and the forecast says $198,000.
The cause is the shape of every request. The Messages API is stateless, so each turn resends everything: the 340 tool definitions (about 61,000 tokens), the system prompt, and the whole history, including every log excerpt a tool ever returned. By turn 120 one request carries over 200,000 tokens, most of it stale. Cost grows faster than the conversation, and quality falls with it: the docs warn that tool selection degrades past 30 to 50 tools, and that response quality degrades as a conversation grows.
A bigger window or a bigger model buys time, not a fix. Dalia needs a context policy: a decision, for each kind of content, about where it lives. Some belongs in the cached prefix, some in the live window, some in a summary. Some should be cleared, some kept in long-term memory, and some kept out of context until Claude searches for it.
Change instructions without breaking the cache
Start with the question Dalia's usage data raised: why did spend jump in the same week the cache hit rate fell? Prompt caching, as you know from Foundations, reuses the start of a request that has not changed. That start is assembled in a fixed order: tools, then system, then messages. A change at one level invalidates that level and everything after it.
Larkspur's product team had added an incident notice to the system prompt, so the agent mentions a provider outage before troubleshooting. Each time the notice changed, every open conversation paid a cache write on the system prompt and the entire history behind it. The usage records show it plainly: cache_creation_input_tokens spikes and cache_read_input_tokens collapses minutes after each notice update.
The cache prefix and where a change lands
system MESSAGEappended at the end, prefix untouchedThe fix is a mid-conversation system message: a message with role: "system", appended to messages where the instruction starts to apply. Nothing earlier changes, so the next request still reads the whole prefix from cache. It must follow a user turn directly (in an agent loop, the user message carrying tool results counts) and it applies from then on. It keeps operator authority: when a system message and a user message conflict, the system instruction wins. That is why smuggling the notice into a user message is the wrong shortcut. Check your model first: the docs list the supported models, among them Claude Opus 5.5, Sonnet 5.5 and Haiku 5.5, and say it is not available on Claude Sonnet 5, which should use the top-level system field.
{"role": "system", "content": "Incident notice: billing-provider webhooks are delayed by up to 40 minutes. Say so before troubleshooting any billing sync."}
Tools follow the same logic. Editing the tools array rewrites the entire cache, so a tool set that must change mid-session is declared in full up front. A system message then carries tool_addition or tool_removal blocks that switch tools on or off. This is a beta behind the mid-conversation-tool-changes-2026-07-01 header, or inline-tools-2026-09-15, which also lets a tool_addition define a new tool inline.
Keep 340 tools out of the window: tool search
The next question is what to do when tool definitions are the largest thing in every request. A typical Larkspur conversation uses four to six integrations, yet all 61,000 tokens of definitions ride along on every turn. And with 340 similar tools in view, the agent sometimes calls crm_get_sync_status when crm_get_sync_errors was the right one.
The mechanism is the tool search tool with deferred loading. You mark most tools defer_loading: true, and the API keeps them out of the context: Claude starts with only the search tool and the few tools you left loaded. When it needs something else, it searches. The regex variant (tool_search_tool_regex_20251119) takes Python regex patterns; the BM25 variant (tool_search_tool_bm25_20251119) takes natural-language queries. The API returns up to five matches by default as tool_reference blocks, expands them into full definitions, and Claude calls the one it needs.
Think of a reference library. You do not carry every book to your desk; you consult the catalogue and fetch the three you need. Precisely: defer_loading controls what enters the context window, not what you send. You still send every definition on every request, because the API needs them to search and to expand references. And because a discovered tool is appended inline as a tool_reference block, not inserted into the prefix, the cache survives every discovery.
In the request below, look at the loop that adds defer_loading and at where the cache breakpoint sits.
tools = [
{"type": "tool_search_tool_bm25_20251119", "name": "tool_search_tool_bm25"},
account_get_workspace, integration_list_connected, ticket_escalate, # used in most conversations
]
for definition in INTEGRATION_TOOLS: # the other 337 tools
tools.append({**definition, "defer_loading": True}) # sent every time, loaded only when found
response = client.messages.create(
model=MODEL, max_tokens=2048, tools=tools, messages=messages,
# A deferred tool cannot carry cache_control; this breakpoint caches loaded tools and system
system=[{"type": "text", "text": SYSTEM_PROMPT, "cache_control": {"type": "ephemeral"}}],
)
The rules that make it work: keep your three to five most-used tools loaded, and never defer every tool, which returns a 400 error. A request can carry up to 10,000 deferred tools. Search matches only tool names, descriptions and argument names and descriptions, so Larkspur prefixes each name by integration (crm_, billing_, sso_) and writes descriptions in admins' words. If built-in search is not enough, your own tool can return tool_reference blocks in a tool_result, for example from an embedding search. Tools from MCP servers through the MCP connector are deferred once, in the toolset's default_config.
Clear what has gone stale: context editing
After turn 40, what in Larkspur's history still matters? Most of the bulk is tool results: webhook logs, sync reports and field mappings that the agent read once and acted on. Context editing clears such content by rule. The API applies it on the server before the prompt reaches Claude, and your client keeps the full, unedited history. You enable it with the context-management-2025-06-27 beta header and list strategies in context_management.edits.
| Strategy | What it clears | Settings that matter |
|---|---|---|
clear_tool_uses_20250919 |
The oldest tool results, replaced with a placeholder; inputs too if you ask | trigger (default 100,000 input tokens), keep (default 3 tool uses), clear_at_least, exclude_tools, clear_tool_inputs |
clear_thinking_20251015 |
Thinking blocks from earlier turns | keep: a number of thinking turns, or "all" |
Memorise the two strategy names and what each clears; recognise the settings when an option names them.
The cost is the cache. Clearing changes the prompt from the point where it happens, so everything after that point is written to the cache again. A rule that clears a few thousand tokens every other turn pays repeated cache writes for almost no saving. That is what clear_at_least is for: the edit runs only if it frees at least that many tokens. Thinking works the same way: keeping thinking blocks preserves cache hits, and clearing them invalidates the cache where the clearing happens.
Here is Larkspur's setting. Note the minimum per clear and the excluded tool.
response = client.beta.messages.create(
model=MODEL, max_tokens=2048, system=system, tools=tools, messages=messages,
betas=["context-management-2025-06-27"],
context_management={"edits": [{
"type": "clear_tool_uses_20250919",
"trigger": {"type": "input_tokens", "value": 120000},
"keep": {"type": "tool_uses", "value": 4}, # recent results stay word for word
"clear_at_least": {"type": "input_tokens", "value": 30000}, # each clear must pay for its cache write
"exclude_tools": ["account_get_workspace"], # tenant config stays all conversation
}]},
)
The response JSON reports each clear in context_management.applied_edits, with counts such as cleared_tool_uses and cleared_input_tokens, so Dalia charts them beside the cache read rate. A cleared result is gone from Claude's view; if the agent needs it again, it calls the tool again. And when the memory tool is present, Claude receives a warning as the threshold nears, so it can save what matters first.
Summarise what is long: compaction
Clearing removes tool output, but what about the conversation itself? A hundred turns of an admin explaining their setup, steps tried, and decisions made cannot be cleared without losing the thread. They must be condensed. Compaction replaces older turns with a summary that Claude writes on the server, so you write no summarisation code. It comes in two server-side forms, and you can still run your own.
Three ways to summarise a long conversation
On demand compact-2026-09-04
compaction: {"type": "summarize"}compaction block returns, stop_reason "compaction"messages; summarised turns removedYou choose when; it can run in the background
At a threshold compact-2026-01-12
compact_20260112 edit in context_managementtrigger (default 150,000)One parameter; runs inside the request that hits it
Your own summariser
Full control, and all of the code to maintain
Anthropic's docs recommend on-demand compaction wherever it is available: your code decides when, it can keep recent turns word for word, and it can run while the conversation continues. Threshold compaction suits a team that wants the API to manage context inside ordinary requests; its trigger cannot go below 50,000 tokens. Client-side summarisation is the oldest option, and the SDK tool runner's compaction_control setting that automated it is deprecated in TypeScript and Ruby and already gone from Python. Keep your own summariser only if it already works and replaces the whole history.
Both server forms accept instructions, which replace the default summarisation prompt entirely. Larkspur's tell Claude to keep integration ids, error codes, steps already tried and failed, and every decision the admin confirmed. Compaction is not free: the summarisation call is billed and reported as a compaction entry in usage.iterations, so sum the iterations to count cost. With threshold compaction, a cache breakpoint at the end of the system prompt keeps that part cached, and only the new summary is written.
Memory: what must outlive the conversation
Larkspur's admins come back week after week, and each new conversation rediscovers the same facts. This tenant's CRM uses a custom field mapping; that one's SSO runs through a particular identity provider; last month's fix was a webhook secret rotation. Compaction cannot help, because a summary lives inside one conversation's history. Facts that must cross conversations belong in memory.
The memory tool ({"type": "memory_20250818", "name": "memory"}) gives Claude a directory of files under /memories. Claude requests operations (view, create, str_replace, insert, delete, rename), and your application executes them against storage you control, such as a per-tenant folder or database rows. When the tool is present, the API tells Claude to check its memory directory before starting work. Think of the site file a field engineer keeps for each client: not a log of every visit, but the five facts the next visit needs.
| Content | Where it lives | Why |
|---|---|---|
| Verified tenant facts: field mappings, identity provider, known quirks | Memory, per tenant | Still true next month |
| Today's logs and sync reports | Context, then cleared | Stale once acted on |
| This conversation's steps and decisions | Context, then the compaction summary | Needed until the conversation ends |
| Instructions and incident notices | System prompt or mid-conversation system message | Operator authority, cache-safe |
| Secrets, tokens, raw personal data | Not in memory at all | A file store is the wrong place for them |
Because your code runs every memory operation, the safeguards are yours. The handler maps /memories to the current tenant only and rejects any path that escapes it, such as /memories/../billing.env. It strips sensitive data before writing, caps file sizes and expires files nobody has read in months. Memory is written by the model from what it read, which makes it an input you must treat with care; a later lesson treats that as an attack surface.
The exam traps
Each trap either spends tokens to avoid a decision or saves tokens in the wrong place.
- ✗ Moving to a larger context window or a bigger model when long conversations get costly and worse. ✓ Change what goes into the window: defer tools, clear stale results, compact the history. A bigger window holds more stale content at full price.
- ✗ Editing the top-level system prompt to add a mid-session instruction. ✓ Append a
role: "system"message after a user turn. Editing the system prompt rewrites the cache for the whole history behind it. - ✗ Removing rarely used tools from the
toolsarray to save tokens. ✓ Defer them and add tool search. Editingtoolsinvalidates the entire cache, and deferred definitions are still sent but stay out of the context. - ✗ Clearing tool results on a low trigger with no minimum. ✓ Set
clear_at_leastand a sensibletrigger. Tiny, frequent clears pay a cache rewrite each time. - ✗ Counting on a compaction summary to carry facts into next week's conversation. ✓ Store durable facts in memory. A summary lives in one conversation's history.
- ✗ Writing whole transcripts, or the API key an admin pasted, into memory. ✓ Write distilled, verified facts per tenant and keep secrets out. Memory is reloaded into future contexts.
Put it together: set Larkspur's context policy
You now have every lever, and Dalia's job is to match each one to evidence. Here is the policy she writes up, one row per symptom.
| Symptom in the data | Option | What it costs |
|---|---|---|
| Tool definitions are the largest share of input; wrong tools picked | Tool search with defer_loading |
A search step before a tool's first use; names and descriptions must be findable |
| Cache writes spike whenever an instruction changes | Mid-conversation system message | Model support to check; the message stays in history from then on |
| Stale tool results fill the window | clear_tool_uses_20250919 with clear_at_least |
Cache rewrite from the clear point; a cleared result must be fetched again |
| Old thinking blocks pile up | clear_thinking_20251015 |
Cache invalidated where thinking is cleared |
| The conversation nears its budget and quality drifts | Compaction, on demand or at a threshold | A billed summarisation call; detail the summary leaves out |
| Each new conversation rediscovers the same tenant facts | Memory tool | A handler, per-tenant storage, path validation and expiry to own |
The rest of the guide builds on this policy. Cost architecture at scale (6.1) takes cache diagnostics from one agent to a fleet of applications and tenants. Threat defense (7.2) treats memory as a store an attacker may try to poison through content the agent reads. Retrieval and knowledge grounding (2.4) decides what knowledge reaches the window in the first place.
Key takeaways
- ✓ A long-running agent resends tools, system prompt and history on every turn, so a context policy decides where each kind of content lives instead of buying a bigger window.
- ✓ The cache covers
tools, thensystem, thenmessages; change instructions with an appendedrole: "system"message and tools withtool_additionandtool_removal, so the prefix never changes. - ✓ Tool search with
defer_loadingkeeps hundreds of tools out of the context while every definition is still sent, and discovered tools arrive inline without breaking the cache. - ✓ Context editing clears old tool results or thinking on the server; each clear rewrites the cache from that point, so set
clear_at_leastand exclude results that stay relevant. - ✓ Compaction replaces older turns with a server-written summary, on demand or at a threshold, at the cost of one billed call and some detail.
- ✓ The memory tool keeps distilled, verified facts across conversations in storage your application controls, with path checks, no secrets and expiry.
Practise this
Practice questions for CCDV-P are being written and are not in this course yet. Read this lesson on the web to answer its check questions, with every option explained: https://claude.termidy.com/learn/ccdv-p/advanced-agent-architecture/context-memory-architecture/.