Task Statement 5.4·Domain 5 — 15% of exam
Codebase Exploration & Context Degradation
Manage context effectively in large codebase exploration
Official Exam Guide Objectives
The objectives below are quoted from Anthropic's Claude Certified Architect – Foundations exam guide, v1.1. Read the exam guide summary for the full blueprint.
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.
One rule underlies every technique in this task statement: anything that must survive the session must live outside the session. What sits only in the context window degrades, gets compacted, and is lost in a crash; what sits on disk does not.
| Inside the context window | Its durable counterpart outside it |
|---|---|
| Conversation history | A scratchpad file of findings |
| Tool results (file contents, search hits) | Structured findings written to disk, or a subagent's distilled summary |
| The agent's picture of where the work stands | A manifest the coordinator reloads on resume |
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.
The degradation signature
An extended session does not fail loudly. A stem will describe one or more of these:
| Symptom | What it means |
|---|---|
| "Typically, a service like this would have a repository layer…" | It is answering from general priors, not from what it read |
| Different answers to the same question early and late in the session | The earlier specifics are no longer effectively in play (the guide's "inconsistent answers") |
| Class and file names turn vague or slightly wrong | Specific identifiers have been replaced by plausible ones |
| It re-reads files it has already read | The earlier read is no longer usable |
Confident answers with no file:line reference | The evidence has faded; only the conclusion remains |
The guide names the tell outright: referencing "typical patterns" rather than the specific classes discovered earlier. When a stem says that, the answer is a context-management technique — a scratchpad, subagent delegation, /compact — not a stronger model and not an instruction to try harder.
Degradation is not attention dilution
A different failure looks similar and has a different fix. Degradation happens over time: a long session loses the prominence of what it found early. Attention dilution happens in a single pass that is given too many things to judge at once: a review of 14 files that is thorough on some, superficial on others and contradictory between them. That is task statement 4.6, and its fix is to split the work into focused passes (one per file, then an integration pass), not to keep a scratchpad. Read the stem for which it is: a long session drifting from specifics, or one pass spread across many items.
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:14; implements `Repository<T>`, caches inside findById (:52)
- `OrderService` — src/services/order.ts:9; sits over OrderRepository and PaymentGateway
- `RefundProcessor` — src/services/refund.ts:21; calls OrderService.getOrderWithItems() (:88)
## Dependency Chain
RefundProcessor → OrderService → OrderRepository → PostgreSQL
RefundProcessor → PaymentGateway → Stripe API
## Critical Findings
- Nothing retries when the Stripe call fails inside RefundProcessor (src/services/refund.ts:104)
- OrderRepository keys its cache on orderId and never invalidates on a status change
- Coverage is lopsided: OrderService 87%, RefundProcessor 12%
## Open Questions
- Who else calls RefundProcessor.process besides the refunds endpoint? (search pending)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.
Buried, not evicted — that's why a bigger window won't help, step 1: OrderRepository — src/repos/order.ts, implements Repository<T>
Write it, then read it back
The technique has two halves, and both do work. The agent writes the specifics after each discovery, not once at the end of a phase, because findings blur well before a phase ends. And it reads the file back before the next step or the next question, because that is what returns the specifics to the context the model reasons over. A scratchpad that is written but never read back is a log, not a mitigation: the entries are accurate and nothing consults them.
What goes in it matters as much: exact class names, paths and file:line references, dependency chains, and an open-questions section so unfinished leads are not forgotten. A short paraphrase ("a repository class with caching") is the degraded description, written down on purpose.
An instruction that sets this up from the start reads like this:
Maintain .analysis/findings.md as you work. After each investigation step, append what
you established, with exact file:line references. Before answering any question about
code you explored earlier, re-read that file rather than relying on the conversation.Why it works
| Property | Why it matters |
|---|---|
| It survives compaction, crashes and new sessions | The file is on disk; re-reading it restores the facts exactly |
| It is more precise than recall | file:line references do not drift the way a paraphrase does |
| It transfers between agents | A subagent can be told to read it — but only if its prompt gives the path, since nothing is discovered automatically |
| It is auditable | You can see what the agent believes and correct it |
To tell whether it is working, measure the symptom it claims to prevent: after several modules, ask for every class found with its path and compare how specific the answer is with and without the scratchpad. A shorter transcript, fewer files opened or a faster run are proxies; none of them shows that the specifics survived.
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.
Isolation is the benefit — parallel or not, step 1: Three subagents, run in parallel
The coordinator holds the map; subagents do the reading
The guide's own examples of delegable questions, "find all test files" and "trace refund flow dependencies", share a shape: each is narrow, each can be answered in a paragraph, and each is expensive to do inline. That shape is the test for what to hand off.
| Delegate it when the question… | Keep it inline when it… |
|---|---|
| Can be answered with a short summary | Needs the accumulated conversation to answer |
| Means reading many files | Touches one or two files you already know |
| Produces intermediate output with no later value | Needs the details verbatim afterwards |
| Is independent of the other questions (so it can also run in parallel) | Depends on a decision still being made |
What crosses back matters as much as what goes out. Each subagent should return a structured summary naming the classes, paths and dependency chains it found, and leave the file contents it read in its own context. And because a subagent inherits none of the coordinator's conversation (task statement 1.3), the question it is given must be self-contained: the scope, what is already known, and where any scratchpad lives.
The Explore subagent
Claude Code ships this pattern ready-made. The built-in Explore subagent is a read-only agent for searching and analysing a codebase: it does the searches and file reads in its own context and hands back a summary. It runs on the parent conversation's model, so what it buys is isolation, not a stronger analyst. Unlike most subagents it starts without your CLAUDE.md files, so a convention it must respect has to be stated in the task it is given.
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 errorsA fresh context inherits only the prompt string, step 1: Phase 2 subagent spawns with a bare task
The summary prevents two distinct failures. One is waste: phase two rediscovering what phase one established. The other is incoherence: phase two subagents reaching decisions that contradict phase one's conclusions, because they never saw them. Each prompt needs three things written into it: the architecture, the dependency chains established, and that subagent's own phase two objective. The pattern repeats down the run — phase one's summary feeds every phase two prompt, phase two's summary feeds phase three — and since subagents inherit nothing, the summary has to be in the prompt itself.
The /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. The guide's wording is the stem signal to recognise: "extended exploration sessions when context fills with verbose discovery output".
Scratchpad first, then compact
Compaction replaces the history with a summary, and a summary is lossy by design: it keeps the gist and drops detail, which is precisely the file:line-level detail degradation threatens. So the order is examinable. Write the findings to the scratchpad first, then compact, optionally with focus instructions naming what the summary must keep. Compact first and the specifics you meant to keep survive only if the summary happened to retain them.
During the session, not at the limit
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 by then the session has been reasoning over buried specifics for a long while. Its real value is protecting the quality of what remains: once the findings are safely on disk, compacting clears the noise while the session is still serving you.
What survives compaction
After /compact | What happens |
|---|---|
| Project-root CLAUDE.md | Re-read from disk and re-injected |
Nested CLAUDE.md files and paths: rules | Load again the next time Claude works with a file they cover |
| Instructions given only in conversation | Survive only as far as the summary keeps them |
| Specifics compressed out of the summary | Gone, unless they were written to a file first |
| The scratchpad on disk | Untouched; a re-read restores it exactly |
So a standing instruction such as "maintain the scratchpad and re-read it before answering" is safer in the project CLAUDE.md than in a chat message.
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.
When to write it
After every significant step, not once per phase. A manifest's value is measured by what a crash costs: written after each step, a crash loses the step in flight; written at phase boundaries, it loses everything since the last one. Writing on graceful shutdown protects only the case that needed no protection, since a crashing process gets no chance to write. And tying the write to the context filling up misses the point too: crashes and dropped connections do not wait for the window to fill. The trigger is progress made.
The coordinator's manifest
In a multi-agent run the coordinator keeps its own manifest over the agents' exports: per-phase status, what each phase produced, and for the phase in flight which items are complete, which are pending and what failed last.
{
"run_id": "billing-test-audit-01",
"phases": {
"structure_map": {"status": "complete", "output": "state/structure.json"},
"risk_ranking": {"status": "complete", "output": "state/risk.json"},
"test_writing": {"status": "in_progress",
"completed": ["billing/invoice.py", "billing/proration.py"],
"pending": ["billing/dunning.py", "billing/tax.py"],
"last_error": {"type": "timeout", "module": "billing/tax.py"}}
},
"findings_scratchpad": ".analysis/findings.md"
}On resume the coordinator reads it, skips the completed phases, re-delegates only the pending items, and injects the phase outputs and the scratchpad path into each new agent's prompt. In this sketch phases is the manifest's per-phase map and pending the list of items not yet done:
def plan_resume(manifest: dict) -> dict:
skip, redelegate = [], []
for name, phase in manifest["phases"].items():
if phase["status"] == "complete":
skip.append(name) # output already on disk
else:
redelegate += phase.get("pending", []) # completed items are not redone
inject = [manifest["findings_scratchpad"]] + [
p["output"] for p in manifest["phases"].values() if "output" in p]
return {"skip": skip, "redelegate": redelegate, "inject": inject}For the manifest above it skips structure_map and risk_ranking, re-delegates billing/dunning.py and billing/tax.py (the module that timed out is still pending, so it is retried), and injects the scratchpad and the two phase outputs. The invariant: no completed work is repeated, and no new agent starts without the established findings.
A manifest is not session resumption
--resume (task statement 1.7) and a manifest both continue earlier work, but they restore different things.
--resume | A manifest | |
|---|---|---|
| Restores | One conversation, including its old tool results | Structured state across many agents |
| After a crash mid-run | Covers only that one session | Covers the run: it is on disk, written as the run progresses |
| Staleness risk | High: old tool results read as if current | Low: the state is explicit and can be re-checked |
| Multi-agent | No | Yes |
Resuming means loading the manifest, not restarting, step 1: Progress builds — three files explored
Choosing the Technique
The techniques are not interchangeable; each answers one symptom.
| Symptom in the stem | Technique |
|---|---|
| Verbose discovery is filling the main context | Subagent delegation (in Claude Code, the Explore subagent) |
| Answers drift towards "typical patterns" | A scratchpad, re-read before answering |
| The notes are accurate but answers are still generic | Add the missing read-back; nothing else needs rebuilding |
| Context is already well filled mid-session | Write the scratchpad, then /compact |
| Phase two agents redo or contradict phase one | Phase summaries injected into their prompts |
| A long run died partway through | Manifest-based crash recovery |
| One pass judges many files inconsistently | Not this task statement: attention dilution, fixed by focused passes (4.6) |
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".
Sourcescode.claude.com › sessionscode.claude.com › best-practicesfetched 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, and its coverage of shell commands is partial: "/rewind undoes changes that Bash commands make to that file afterward. A file that only Bash commands changed isn't tracked." So once Claude's file editing tools have touched a file, later Bash changes to it are rewound too, but a file that was only ever moved, deleted or rewritten by commands such as mv or rm has nothing to restore. 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-11-19
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. (Claude Code's built-in Explore subagent, described above, is an exception on the CLAUDE.md point.) 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, and answers become inconsistent; not a token-limit problem |
| Degradation vs attention dilution | A long session losing early specifics vs one pass over too many items (fixed by focused passes, 4.6) |
| Scratchpad files = | Structured note-taking / "agentic memory" (Anthropic's official term) |
| Scratchpad discipline | Write specifics (file:line) after each discovery; read back before the next step |
| 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 |
| Explore subagent | Built-in, read-only codebase search that returns a summary; runs on the parent's model; starts without CLAUDE.md |
/clear | Empty context, previous conversation saved and resumable via /resume |
/compact [instructions] | Replace history with a (optionally focused) summary |
Order with /compact | Write findings to the scratchpad first, then compact |
After /compact | Root CLAUDE.md re-injected from disk; nested CLAUDE.md and paths: rules reload when a matching file is next touched |
| Checkpoints | Auto-created per prompt; /rewind restores code/conversation/both — "local undo," not git |
| Checkpoint blind spot | A file that only Bash commands changed isn't tracked; Bash changes to a file already edited by Claude's tools are rewound |
| 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 |
| Manifest write timing | After every significant step, not at phase end or on shutdown |
| Resuming from a manifest | Skip complete phases, re-delegate only pending items, inject phase outputs and scratchpad path |
Exam Traps
More wrong answers, and why each fails
| Tempting answer | Why it fails | Choose instead |
|---|---|---|
| Tell the agent to be more careful or to pay closer attention | The cause is where the findings sit, not effort; an instruction does not unbury them | A scratchpad, re-read before answering |
| Read every file, or load the full directory listing and import graph, up front | It spends the context before the work begins and captures the repository's shape, not the findings that later degrade | Delegate specific questions as they arise |
| Do the verbose discovery in the main conversation | The coordinator should hold the map; every file it reads crowds its own reasoning | Subagents for the reading |
| Have subagents return their full transcript or the raw files, for auditability | It puts the verbose exploration straight back into the context delegation was protecting | A structured summary naming classes, paths and chains |
| Have subagents return a confidence score and re-read the files yourself when it is low | It routes the coordinator back into the raw files on exactly the investigations that needed most reading | A structured summary of findings |
| Keep the scratchpad short by writing condensed paraphrase | Paraphrase is the degraded description; drift returns without file:line | Exact names, paths and file:line references |
| Give phase two only its objective, or a pointer to the stored phase one conversation | Without the conclusions it rediscovers them; a stored conversation is mostly discovery noise, read only if it chooses to | A compact phase summary injected into each prompt |
| Build a vector store over the repository or a bespoke memory service | Heavy machinery aimed at a problem a file plus a read-back already fixes | A scratchpad file and a read-back instruction |
How This Is Tested
| Stem signal | Answer | Wrong-answer pattern beside it |
|---|---|---|
| Ninety minutes in, it references "typical patterns" instead of the classes it found | Scratchpad with a read-back; delegate the verbose work | A larger context window; restart the session; "be more careful" |
| How to keep the main agent's context clean while exploring | Subagents for specific questions, each returning a summary | Parallelisation as the reason; subagents returning transcripts |
| A notes file holds the right specifics but answers are still generic | Read the file back before answering | A larger window; paste the whole file every turn; re-explore |
| Context is filling with discovery output mid-task | Write the scratchpad, then /compact (with focus instructions) | Compact first; wait for the hard limit |
| A long multi-agent run crashed partway through | Manifests written as the run progresses; skip complete, re-delegate pending | --resume the coordinator's session; start over |
| Phase two agents redo or contradict phase one | Phase summaries injected into their prompts | Assuming they inherit context; raw phase one output |
| One pass over 14 files gives uneven, contradictory feedback | Not this task statement: focused per-file passes plus an integration pass | Scratchpad or /compact; a bigger window |
Practice Scenario
Your Claude Code session has explored an unfamiliar payments repository for two hours, appending every class name, path and dependency chain it finds to exploration-notes.md after each step. It now answers with "the usual service-layer pattern" rather than naming RefundProcessor at src/services/refund.ts, which that file records correctly. What's the most effective first step?
Practice Questions
Exam simulator
Question 1 of 13
Scenario · Code Generation with Claude Code
Three hours into exploring a payments monolith, you ask which class writes ledger entries. Claude names LedgerService, although an hour earlier it traced those writes to JournalWriter in src/accounting/journal.ts, and it now describes the flow as "the usual service pattern". You still have several questions to ask. What change would most effectively keep the answers accurate?
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
- Claude Code — Best Practices — Anthropic
- Create custom subagents — Anthropic