Task Statement 5.4·Domain 5 — 15% of exam
Codebase Exploration & Context Degradation
Manage context effectively in large codebase exploration
Official Exam Guide Objectives
Task 5.4: Manage context effectively in large codebase exploration.
Knowledge of
- Context degradation in extended sessions: models start giving inconsistent answers and referencing "typical patterns" rather than specific classes discovered earlier
- The role of scratchpad files for persisting key findings across context boundaries
- Subagent delegation for isolating verbose exploration output while the main agent coordinates high-level understanding
- Structured state persistence for crash recovery: each agent exports state to a known location, and the coordinator loads a manifest on resume
Skills in
- Spawning subagents to investigate specific questions (e.g., "find all test files," "trace refund flow dependencies") while the main agent preserves high-level coordination
- Having agents maintain scratchpad files recording key findings, referencing them for subsequent questions to counteract context degradation
- Summarizing key findings from one exploration phase before spawning sub-agents for the next phase, injecting summaries into initial context
- Designing crash recovery using structured agent state exports (manifests) that the coordinator loads on resume and injects into agent prompts
- Using /compact to reduce context usage during extended exploration sessions when context fills with verbose discovery output
What You Need to Know
Exploring a large codebase is about as context-hungry as agent work gets. Unfamiliar repositories, dependency chains, legacy systems — extended sessions of this kind produce a characteristic failure called context degradation, and it is not about running out of room. The model loses its hold on what it found earlier as the context fills with the verbose output of finding it.
Context Degradation
It shows itself in a recognisable way: the agent begins describing patterns instead of naming things. Several modules in, you get "this follows the typical repository pattern" where earlier you would have had "the OrderRepository class at src/repos/order.ts implements the base Repository<T> interface with custom caching in the findById method."
This happens because:
- Every step of exploration emits bulk — whole files, search hits, directory listings.
- All of it stays in the conversation.
- The precise things found early sink beneath it as newer, larger output arrives.
- Attention follows the recent material, and the specific references stop being reachable.
The critical insight: this is not a capacity problem, and a larger window does not address it. Nothing has been evicted for lack of space — the specifics are still present and simply no longer prominent, having been buried under everything that arrived afterwards. A bigger window buries them at greater depth.
Scratchpad Files
The main defence is to write findings down outside the conversation. The agent records what matters to a file and consults it later, which puts that knowledge somewhere accumulation cannot reach.
# Exploration Scratchpad — Order Service
## Key Classes
- `OrderRepository` — src/repos/order.ts; implements `Repository<T>`, caches inside findById
- `OrderService` — src/services/order.ts; sits over OrderRepository and PaymentGateway
- `RefundProcessor` — src/services/refund.ts; calls OrderService.getOrderWithItems()
## Dependency Chain
RefundProcessor → OrderService → OrderRepository → PostgreSQL
RefundProcessor → PaymentGateway → Stripe API
## Critical Findings
- Nothing retries when the Stripe call fails inside RefundProcessor
- OrderRepository keys its cache on orderId and never invalidates on a status change
- Coverage is lopsided: OrderService 87%, RefundProcessor 12%Reading that file is how the agent recovers a detail rather than searching its own context for it. The timing matters as much as the technique: this is set up at the beginning of an extended exploration, because by the time degradation is visible the findings worth writing down have already blurred.
Subagent Delegation
The second defence is to move the verbose work elsewhere. Rather than the main agent reading every file and running every search itself — filling its own context with the output of both — specific questions go to subagents:
- "Which test files cover the order service, and what coverage do they report?"
- "Follow a refund from the API endpoint through to the database and name every service it passes through"
- "List the external API integrations and describe how each one handles failure"
Each one works in a context of its own, where it can be as verbose as the task requires, and returns a summary. Only that summary reaches the coordinator.
Parallelisation is the obvious read and it is the lesser benefit. What actually matters is isolation: exploration is inherently noisy, and delegating it keeps the noise out of the context doing the reasoning.
Summary Injection Between Phases
Exploration that proceeds in phases — architecture first, then specific components — should carry its conclusions forward. Summarise what phase one established and inject that into the prompts of the phase two subagents.
Skip it and phase two starts cold, re-deriving the architecture before it can begin its actual work, at the cost of the exploration phase one already paid for. Worse, a subagent without that background asks the wrong questions, because knowing which components matter is itself a phase one finding.
Phase 1 Summary (injected into Phase 2 subagent prompts):
- Architecture is layered throughout: Controllers → Services → Repositories → Database
- A refund travels RefundController → RefundProcessor → OrderService → PaymentGateway
- Open concern: nothing in RefundProcessor retries a failed external call
- For phase 2: examine how RefundProcessor and PaymentGateway handle errorsThe /compact Command
Claude Code offers /compact for exactly this situation: it summarises the conversation so far, reclaiming the space that file contents, search output and directory listings have taken up.
Run it during a long exploration rather than at the point of exhaustion. Waiting until the window is full treats it as a capacity measure, and its real value is protecting the quality of what remains — compacting before the specifics get buried is what keeps them retrievable.
Crash Recovery via Structured State Manifests
Long sessions end unexpectedly — a crash, a dropped connection, context that ran out. With nothing persisted, the exploration is simply gone and repeats from the beginning.
Structured state persistence prevents that. Each agent writes its position to a known file, a manifest recording:
- Ground already covered — which files were opened, which searches ran
- The findings established so far
- Which phase it is in, and what comes next
- Questions still open and anything left unresolved
{
"sessionId": "explore-order-service-001",
"phase": 2,
"exploredPaths": [
"src/repos/order.ts",
"src/services/order.ts",
"src/services/refund.ts"
],
"keyFindings": {
"architecture": "Layered: Controllers → Services → Repositories → DB",
"criticalIssue": "RefundProcessor has no retry logic for Stripe API failures",
"testCoverage": {"OrderService": "87%", "RefundProcessor": "12%"}
},
"nextSteps": [
"Investigate PaymentGateway error handling",
"Review RefundProcessor test files",
"Check cache invalidation logic in OrderRepository"
]
}Resuming means loading the manifest into the new agent's prompt. Note what exploredPaths buys beyond the findings themselves: it stops the resumed session re-reading files whose conclusions are already recorded, which is where the cost of a naive restart actually sits.
Deep Dive
Structured note-taking (agentic memory) — the official name for scratchpad files
What this lesson calls "scratchpad files" is Anthropic's second named long-horizon technique: "structured note-taking, or agentic memory, is a technique where the agent regularly writes notes persisted to memory outside of the context window." The demonstrated case is Claude playing Pokémon — "after context resets, the agent reads its own notes and continues multi-hour training sequences or dungeon explorations" — the same mechanism this lesson applies to a codebase: persist the OrderRepository-at-src/repos/order.ts-level detail somewhere the model re-reads, rather than trusting it to survive in a filling context window. Anthropic's guidance on choosing between the three long-horizon techniques is explicit that note-taking "excels for iterative development with clear milestones" — a good fit for phased codebase exploration.
Sourceanthropic.com › effective-context-engineering-for-ai-agentsfetched 2026-07-30
Sub-agent architectures as the third long-horizon technique
Subagent delegation for exploration is the third documented technique: "rather than one agent attempting to maintain state across an entire project, specialized sub-agents can handle focused tasks with clean context windows." The token economics are explicit — "each subagent might explore extensively, using tens of thousands of tokens or more, but returns only a condensed, distilled summary of its work" to the coordinator. This is the mechanism behind this lesson's claim that subagent delegation is "primarily about context isolation" rather than parallelisation: the coordinator's context stays clean regardless of how much verbose exploration happened inside the subagent.
Sourceanthropic.com › effective-context-engineering-for-ai-agentsfetched 2026-07-30
/compact and /clear — exact command behaviour in Claude Code
Claude Code exposes two distinct commands for managing a filling context, and they do different things. /clear "start[s] fresh with an empty context" while Claude Code "saves the previous conversation" so it stays resumable via /resume. /compact [instructions] instead "replace[s] history with a summary, optionally focused on what you specify" — for example /compact Focus on the API changes — giving the developer control over what survives compaction rather than accepting a generic summary. Best-practice guidance says to "use /clear frequently between tasks to reset the context window entirely" and, "for more control, run /compact <instructions>, like /compact Focus on the API changes".
Sources: https://code.claude.com/docs/en/sessions (command definitions) · https://code.claude.com/docs/en/best-practices (when to clear vs compact, and the example) (fetched 2026-07-30)
Checkpoints and /rewind — a different recovery mechanism from state manifests
Claude Code separately checkpoints code state automatically: "every user prompt creates a new checkpoint," and /rewind (or pressing Esc twice on an empty prompt) opens a menu to restore code and conversation, conversation only, or code only, to that point. This is explicitly "local undo," not version control — "Checkpointing does not track files modified by bash commands... Only direct file edits made through Claude's file editing tools are tracked" — and checkpoints are saved with the conversation, so /rewind still works after a session resume. This is a different tool from the structured state manifest this lesson describes for crash recovery: checkpoints undo code changes within a session; manifests persist exploration findings across a coordinator's resume.
Sourcecode.claude.com › checkpointingfetched 2026-07-30
Subagent context isolation — the exact mechanics
At the SDK level, "each subagent runs in its own fresh conversation. Intermediate tool calls and results stay inside the subagent; only its final message returns to the parent." Even more specifically, "a subagent's context window starts fresh, with no parent conversation, but isn't empty. The only content you pass from parent to subagent is the Agent tool's prompt string" — it still gets its own system prompt, project CLAUDE.md, and tool definitions, but it does not inherit the parent's conversation history or tool results, and so does not automatically inherit the coordinator's accumulated findings. This is precisely why this lesson's summary-injection step between exploration phases is necessary: without explicitly building the Phase 1 summary into the Phase 2 subagent's prompt, that subagent starts from nothing.
Sourcecode.claude.com › subagentsfetched 2026-07-30
Quick Reference
| Fact | Value |
|---|---|
| Context degradation | Model references "typical patterns" instead of specific findings; not a token-limit problem |
| Scratchpad files = | Structured note-taking / "agentic memory" (Anthropic's official term) |
| Note-taking best fit | Iterative work with clear milestones |
| Subagent delegation = | The third long-horizon technique — clean, isolated context windows per subtask |
| What returns from a subagent | Only its final distilled message; verbose exploration stays inside it |
/clear | Empty context, previous conversation saved and resumable via /resume |
/compact [instructions] | Replace history with a (optionally focused) summary |
| Checkpoints | Auto-created per prompt; /rewind restores code/conversation/both — "local undo," not git |
| Checkpoint blind spot | Does not track changes made via Bash commands (rm, mv, etc.) |
| Subagent context at spawn | Fresh — no parent conversation; only the Agent tool's prompt string is passed in |
| Crash recovery mechanism | Structured state manifest per agent, loaded by the coordinator on resume |
Exam Traps
Practice Scenario
A developer productivity agent is exploring an unfamiliar codebase. After investigating several modules, it starts referencing 'typical repository patterns' instead of the specific class names and dependency chains it discovered earlier. What is the most effective mitigation?
Build Exercise
Build a Context-Resilient Codebase Explorer
Difficulty: Advanced (3/4)
60 minutes
- Create a coordinator agent that delegates specific codebase exploration tasks to subagents (e.g., find test files, trace dependency chains, identify external integrations)
Why: Subagent delegation is primarily about context isolation, not parallelisation. The main agent context stays clean for high-level coordination while subagents handle verbose exploration. This directly prevents context degradation by keeping verbose file contents and search results out of the coordinator context.
You should see: A coordinator function that spawns subagents with specific, focused investigation prompts. Each subagent returns a structured summary (key findings, file paths, class names) rather than raw verbose output. The coordinator context should remain clean.
- Implement scratchpad file management: agents write key findings (class names, file paths, dependency chains) to a known file and read it before subsequent exploration steps
Why: Scratchpad files are the primary mitigation for context degradation. They persist knowledge outside the conversation context, making it immune to the attention shift that causes the model to reference typical patterns instead of specific class names and file paths it discovered earlier.
You should see: An agent that writes structured findings to a scratchpad file after each exploration step and reads the scratchpad at the start of each subsequent step. The scratchpad should contain specific class names, file paths, and dependency chains, not summaries.
- Build summary injection logic: after Phase 1 exploration, summarise findings and inject the summary into Phase 2 subagent prompts
Why: Summary injection prevents the cold start problem where Phase 2 subagents duplicate Phase 1 exploration because they were not given previous findings. It ensures Phase 2 agents have the architectural understanding needed to ask the right questions without rediscovering the system structure.
You should see: A Phase 1 summary document that captures the high-level architecture, key concerns, and specific investigation targets for Phase 2. This summary is injected into the initial prompt of every Phase 2 subagent.
- Implement crash recovery: each agent exports structured state (explored paths, key findings, next steps) to a manifest file that the coordinator loads on resume
Why: Extended exploration sessions can fail from crashes, network interruptions, or context exhaustion. Without recovery mechanisms, all progress is lost. Structured state manifests enable the coordinator to resume from the last checkpoint rather than restarting from scratch.
You should see: A manifest file in JSON format containing the session ID, current phase, explored paths, key findings, and next steps. On resume, the coordinator loads this manifest and injects it into agent prompts so exploration continues from where it left off.
- Test context degradation by running an extended exploration session across multiple modules and verify that scratchpad files preserve specific class names and file paths that would otherwise degrade to generic descriptions
Why: This validates that the scratchpad mitigation actually works against context degradation. The observable symptom is the model referencing typical patterns instead of specific classes and paths. You need to confirm that scratchpad files prevent this degradation.
You should see: Two comparison runs: one without scratchpad files where the agent degrades to generic references after exploring 4-5 modules, and one with scratchpad files where the agent maintains specific class names and file paths throughout the entire session.
Sources
- Claude Certified Architect Foundations Exam Guide — Domain 5, Task Statement 5.4 — Anthropic
- Claude Code Documentation — Context Management — Anthropic
- Claude Code Documentation — Commands — Anthropic
- Effective Context Engineering for AI Agents — Anthropic
- Claude Code — Sessions — Anthropic
- Claude Code — Checkpointing — Anthropic
- Agent SDK — Subagents — Anthropic
Appendix A — Build Exercise Step Hints
Progressive hints revealed by the "Stuck? Get a nudge" control on each step.
Step 1. Create a coordinator agent that delegates specific codebase exploration tasks to subagents (e.g., find test files, trace dependency chains, identify external integrations)
Why: Subagent delegation is primarily about context isolation, not parallelisation. The main agent context stays clean for high-level coordination while subagents handle verbose exploration. This directly prevents context degradation by keeping verbose file contents and search results out of the coordinator context.
You should see: A coordinator function that spawns subagents with specific, focused investigation prompts. Each subagent returns a structured summary (key findings, file paths, class names) rather than raw verbose output. The coordinator context should remain clean.
Stuck? Get a nudge
Step 2. Implement scratchpad file management: agents write key findings (class names, file paths, dependency chains) to a known file and read it before subsequent exploration steps
Why: Scratchpad files are the primary mitigation for context degradation. They persist knowledge outside the conversation context, making it immune to the attention shift that causes the model to reference typical patterns instead of specific class names and file paths it discovered earlier.
You should see: An agent that writes structured findings to a scratchpad file after each exploration step and reads the scratchpad at the start of each subsequent step. The scratchpad should contain specific class names, file paths, and dependency chains, not summaries.
Stuck? Get a nudge
Step 3. Build summary injection logic: after Phase 1 exploration, summarise findings and inject the summary into Phase 2 subagent prompts
Why: Summary injection prevents the cold start problem where Phase 2 subagents duplicate Phase 1 exploration because they were not given previous findings. It ensures Phase 2 agents have the architectural understanding needed to ask the right questions without rediscovering the system structure.
You should see: A Phase 1 summary document that captures the high-level architecture, key concerns, and specific investigation targets for Phase 2. This summary is injected into the initial prompt of every Phase 2 subagent.
Stuck? Get a nudge
Step 4. Implement crash recovery: each agent exports structured state (explored paths, key findings, next steps) to a manifest file that the coordinator loads on resume
Why: Extended exploration sessions can fail from crashes, network interruptions, or context exhaustion. Without recovery mechanisms, all progress is lost. Structured state manifests enable the coordinator to resume from the last checkpoint rather than restarting from scratch.
You should see: A manifest file in JSON format containing the session ID, current phase, explored paths, key findings, and next steps. On resume, the coordinator loads this manifest and injects it into agent prompts so exploration continues from where it left off.
Stuck? Get a nudge
Step 5. Test context degradation by running an extended exploration session across multiple modules and verify that scratchpad files preserve specific class names and file paths that would otherwise degrade to generic descriptions
Why: This validates that the scratchpad mitigation actually works against context degradation. The observable symptom is the model referencing typical patterns instead of specific classes and paths. You need to confirm that scratchpad files prevent this degradation.
You should see: Two comparison runs: one without scratchpad files where the agent degrades to generic references after exploring 4-5 modules, and one with scratchpad files where the agent maintains specific class names and file paths throughout the entire session.
Stuck? Get a nudge
Appendix B — Interactive Study Prompts
Two prompts to paste into Claude. B1 drills the judgement the exam actually measures; B3 reviews the work you produced for the Build Exercise above. The exam simulator between them is the interactive quiz on this page.
B1. Concept Check — Discrimination Drill
You are examining me for the Claude Certified Architect – Foundations (CCAR-F) exam, Domain 5: Context Management & Reliability (15% of the exam), Task Statement 5.4: Codebase Exploration & Context Degradation. Use British English throughout.
What this exam actually measures. Not one item on the official exam asks what something is. Every item drops you into a production system that is already misbehaving, offers four defensible engineering responses, and asks which is best. The skill being tested is proportionality: fix the root cause with the cheapest instrument that gives the guarantee the situation demands. So do not quiz me on definitions. Make me choose between options that are both defensible, then attack whatever I chose.
How to run this session.
- One question at a time. Stop and wait. Never answer your own question, and never move on until I have committed.
- Never reveal which option is right before I commit to one.
- Do not praise me. A correct answer earns "Yes" and the next question. If I am right for the wrong reason, say so — that is the failure that costs marks on exam day.
- When I am wrong, quote the exact phrase in my answer that gave it away, correct it in one sentence, and move on. One correction at a time.
- If I write something fluent but empty, name it: "That is a restatement, not a reason."
- Set every scenario inside one of the exam's production contexts: Code Generation with Claude Code over an unfamiliar repository, the Multi-Agent Research System (a coordinator delegating to web-search, document-analysis, synthesis and report-generation subagents that produce cited reports), the Customer Support Resolution Agent (Agent SDK, MCP tools
get_customer,lookup_order,process_refund,escalate_to_human, held to an 80%+ first-contact resolution target), or Structured Data Extraction over batches of documents.
Session plan — about twelve questions.
Round 1 — Anchor (1 question). One concrete question to check I have actually read the material. If I cannot answer it, stop the session and tell me to read the lesson before continuing.
Round 2 — Discrimination (5 questions). Each one: describe a symptom in one of the contexts above, with a number or a log observation in it. Offer exactly two responses, both defensible. Ask me to pick one and justify it in a single sentence. Then argue the case for the option I rejected as strongly as you can, and ask whether I am holding or changing my answer. Only after I answer that, tell me which is right and why the other one is the more tempting trap.
Round 3 — Proportionality (2 questions). Both turn on the size of the instrument, which is where this domain is decided: adjust how the agent works or build new machinery, carry on autonomously or stop and involve a person. Ask the first where the cheap fix is genuinely enough — instructing the agent to keep a scratchpad from the outset, running /compact with focused instructions, narrowing what a subagent is asked to investigate — and a larger-context model, a vector store over the repository or a bespoke memory service would be over-engineering aimed at the wrong cause. Ask the second on a symptom that reads the same but where the agent is about to act on degraded understanding in a way that corrupts a production branch or deletes work, so a self-managed mitigation is not enough and a state export plus a human checkpoint before the change is what the situation demands. Tell me which was which only after I have answered both. If I reach for the elaborate option both times, or the cheap one both times, that is the finding — say so.
Round 4 — Code review (3 questions). Present a colleague's confident proposal containing one of the trap errors listed below, written the way a teammate would write it in a pull request. Ask me what is wrong with it. Do not signal that anything is wrong.
Round 5 — Verdict. Rate me green, amber or red on each concept below. Name the single weakness most likely to cost me marks, and give me one specific next action: a section of this lesson to re-read, or a step of the Build Exercise to redo. If I am not ready for this task statement, say so plainly.
Concepts in scope
- Context degradation — in a long session the agent starts describing typical patterns instead of naming the class, path and dependency chain it found an hour earlier; the cause is verbose discovery output crowding out earlier precision, not a token budget running out.
- Scratchpad files — the primary mitigation: findings written to a file and read back before the next step, so the knowledge lives outside the conversation and is immune to what happens inside it, adopted from the start of a long session rather than once things go wrong.
- Subagent delegation for context isolation — each investigation runs in its own context and returns a condensed summary, so the coordinator never carries the verbose exploration; parallel execution is a side effect, not the reason.
- Summary injection between phases — a subagent begins with a fresh context and inherits only the prompt it is given, so Phase 1 findings have to be written into the Phase 2 prompt or that ground gets covered again.
/compactused proactively — the command replaces history with a summary, optionally focused on what you specify, and it exists to protect the quality of a long session rather than to rescue one at the limit.- State manifests for crash recovery — each agent exports explored paths, findings, current phase and next steps to a known location, and the coordinator reloads that on resume and injects it into the prompts.
Trap errors to plant in Round 4
- Answering context degradation by moving the session to a model with a larger context window.
- Treating subagent delegation as a parallelisation trick and missing that the benefit being bought is an isolated context.
- Restarting a degraded session for a clean slate without exporting what has been learned first.
- Holding
/compactback until the context is nearly exhausted rather than using it during the session.
Stay inside the material above. If I raise something outside it, tell me it is out of scope for this task statement and return to the drill. Begin with Round 1.
B2. Exam Simulator
Exam simulator
Question 1 of 10
Scenario · Code Generation with Claude Code
Ninety minutes into exploring an unfamiliar service, the agent starts answering with "this follows the usual repository pattern" rather than naming OrderRepository at src/repos/order.ts, which it read and described forty turns earlier. What is the most effective mitigation?
B3. Build Coach — Code Review
The Build Exercise and its hint ladder are already on this page. This prompt is for the one thing the page cannot do: review the code and the artefacts you actually produced.
You are a staff engineer reviewing my implementation of a build exercise for the Claude Certified Architect – Foundations exam, Domain 5, Task Statement 5.4: Codebase Exploration & Context Degradation. Use British English throughout.
I am building a context-resilient codebase explorer: a coordinator that hands narrow investigations to subagents and keeps only what they distil, agents that write specific findings to a scratchpad and read it back before the next step, a Phase 1 summary carried into every Phase 2 prompt, a state manifest the coordinator reloads after a crash, and a paired run that shows what the scratchpad is actually buying.
It has to satisfy all of the following:
- Subagents given narrow, specific investigations that hand back structured findings — class names, paths, chains — with the raw file contents left behind in their own contexts.
- A scratchpad holding those specifics rather than a paraphrase of them, written after each discovery and read at the start of the next step.
- A Phase 1 summary carrying the architecture, the dependency chains and the Phase 2 objective, built into the Phase 2 prompt rather than assumed.
- A manifest with the session identifier, phase, explored paths, findings and next steps, written often enough that a crash costs one step rather than a phase.
- Two comparison runs where the unequipped agent falls back on generic descriptions after several modules while the equipped one still names classes and paths.
How to review.
- Ask me to paste what I produced: the coordinator and subagent code, the scratchpad file with its real contents, the Phase 2 prompt with the summary in it, and my manifest. If I have pasted nothing, ask for it and nothing else. Do not write the implementation for me, do not offer a reference solution, and do not fill in a step I have skipped.
- Work through the criteria above in order. For each one, quote the line of my code or my artefact that satisfies it, or say plainly that nothing does.
- Then hunt for the failure modes below. Each is a real production bug, not a style preference.
- Rank everything you find: (1) would fail in production, (2) would lose marks on the exam, (3) style. Give me the first item under (1) and then stop — wait for my fix before giving me the next one.
- If my work satisfies everything, do not congratulate me. Change the requirements — the session crashes mid-way through Phase 2, and one Phase 1 finding turns out to have been wrong — and make me handle it.
- If I ask you to just write it for me, refuse once and give me the smallest nudge that would unblock me instead.
Failure modes to probe
- A scratchpad written but never read back, which makes it a log rather than a mitigation.
- Scratchpad entries condensed into prose, which reintroduces exactly the vagueness the file exists to prevent.
- Subagents returning their raw exploration to the coordinator, which puts the verbose output straight back into the context you were protecting.
- Phase 2 prompts written as though the subagent already knows the architecture, when its context starts fresh and inherits only the prompt string.
- A manifest written once at the end of a phase, so a crash halfway through costs everything since the last boundary.
Start by asking me for what I produced.