5.4 Codebase Exploration & Context Degradation
What You Need to Know
Section titled “What You Need to Know”Large codebase exploration is one of the most context-intensive tasks a Claude-based agent performs. Whether an agent is exploring an unfamiliar repository, tracing dependency chains, or understanding legacy systems, extended sessions create a specific failure mode: context degradation. It has nothing to do with running out of tokens. The model simply loses its grip on earlier findings as the context fills with verbose discovery output.
Context Degradation
Section titled “Context Degradation”Context degradation manifests as a specific, observable behaviour: the model starts referencing “typical patterns” instead of the specific classes, methods, and dependency chains it discovered earlier in the session. After investigating several modules, the agent might say “this follows the typical repository pattern” instead of “the OrderRepository class at src/repos/order.ts implements the base Repository<T> interface with custom caching in the findById method.”
This happens because:
- Each exploration step generates verbose output (file contents, search results, directory listings).
- This output accumulates in the conversation context.
- Earlier, precise discoveries are pushed further into the context while more recent verbose output dominates.
- The model’s attention shifts to recent output and it loses specific references to earlier findings.
The critical insight: context degradation is not a token limit problem. Increasing the context window doesn’t fix it. The model isn’t running out of space. It’s losing track of specific details as they get buried under newer, more verbose output.
Scratchpad Files
Section titled “Scratchpad Files”The primary mitigation for context degradation is scratchpad files. The agent writes key findings to a file and references it for subsequent questions. This persists knowledge outside the conversation context, making it immune to context degradation.
# Exploration Scratchpad — Order Service
## Key Classes- `OrderRepository` (src/repos/order.ts) — implements Repository<T>, custom findById caching- `OrderService` (src/services/order.ts) — orchestrates OrderRepository + PaymentGateway- `RefundProcessor` (src/services/refund.ts) — depends on OrderService.getOrderWithItems()
## Dependency ChainRefundProcessor → OrderService → OrderRepository → PostgreSQLRefundProcessor → PaymentGateway → Stripe API
## Critical Findings- RefundProcessor has no retry logic for Stripe API failures- OrderRepository caches by orderId but cache invalidation on status change is missing- Test coverage: OrderService has 87% coverage, RefundProcessor has 12%When the agent needs to reference earlier discoveries, it reads the scratchpad file instead of relying on conversation context. Treat this as a deliberate strategy from the outset, not a rescue move once things degrade — agents should be instructed to maintain scratchpad files from the start of any extended exploration session.
Subagent Delegation
Section titled “Subagent Delegation”Spawning subagents for specific investigation tasks is the second major mitigation strategy. Instead of the main agent doing all exploration directly (filling its context with verbose output from every file read and search), delegate specific questions to subagents:
- “Find all test files for the order service and report their coverage status”
- “Trace the refund flow from API endpoint to database and list all intermediate services”
- “Identify all external API integrations and their error handling patterns”
Each subagent operates with its own isolated context. It can explore verbosely without polluting the main agent’s context. It returns a structured summary to the coordinator, which keeps only the key findings.
Parallelisation is the obvious read; the real value is context isolation. The main agent’s context stays clean for high-level coordination while subagents handle the verbose exploration.
Summary Injection Between Phases
Section titled “Summary Injection Between Phases”When exploration happens in phases (Phase 1: understand the architecture, Phase 2: investigate specific components), summarise key findings from Phase 1 before spawning Phase 2 subagents. Inject these summaries into the initial context of Phase 2 subagents.
This prevents the “cold start” problem where Phase 2 subagents duplicate Phase 1 exploration because they were not given the previous findings. It also ensures that Phase 2 agents have the architectural understanding needed to ask the right questions.
Phase 1 Summary (injected into Phase 2 subagent prompts):- The system follows a layered architecture: Controllers → Services → Repositories → Database- The refund flow passes through: RefundController → RefundProcessor → OrderService → PaymentGateway- Key concern: RefundProcessor has no retry logic for external API failures- Phase 2 objective: Investigate error handling in RefundProcessor and PaymentGatewayThe /compact Command
Section titled “The /compact Command”Claude Code provides a /compact command specifically for reducing context usage during extended sessions. When context fills with verbose discovery output — file contents, search results, directory listings — /compact summarises the conversation to free up space while preserving key information.
Use /compact proactively during extended exploration sessions, not just when you hit context limits. It’s there to protect context quality, not only quantity.
Crash Recovery via Structured State Manifests
Section titled “Crash Recovery via Structured State Manifests”Extended exploration sessions can fail due to session crashes, network interruptions, or context exhaustion. Without recovery mechanisms, all exploration progress is lost.
The fix is structured state persistence. Each agent exports its current state to a known file location (a manifest). This manifest includes:
- What has been explored (files read, searches performed)
- Key findings discovered so far
- Current phase and next steps
- Any pending questions or unresolved issues
{ "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" ]}On resume, the coordinator loads this manifest and injects it into agent prompts. The agent picks up where it left off without repeating earlier exploration.
Exam Traps
Section titled “Exam Traps”Practice Scenario
Section titled “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?
- A. Increase the model context window so that far more of the discovery output can be retained throughout the whole exploration
- B. Have the agent maintain scratchpad files recording key findings and reference them for subsequent questions
- C. Restart the session with a fresh context and ask the agent to explore the codebase more efficiently this time
- D. Pre-load the entire codebase structure into the initial context so exploration has less to rediscover
Answer & explanation
Correct: B
- A — Context degradation is not about running out of tokens — it is about the model losing grip on earlier findings as verbose output accumulates. A larger window does not fix this.
- B — Scratchpad files persist knowledge outside the conversation context, directly counteracting context degradation by keeping critical discoveries accessible regardless of context state.
- C — Restarting loses all accumulated knowledge without addressing the underlying context degradation problem. Without scratchpad files, the same degradation will recur.
- D — This would consume context budget before exploration starts and does not address degradation during the session. The problem is accumulated verbose output, not missing initial context.
Sources
Section titled “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
Exam Simulator
Section titled “Exam Simulator”Five exam-style multiple-choice questions on Codebase Exploration & Context Degradation. Pick an answer, then open the explanation.
Question 1
Section titled “Question 1”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?
- A. Have the agent keep scratchpad files recording key findings and re-read them later
- B. Increase the model’s context window to accommodate more discovery output
- C. Restart the session and ask the agent to explore more efficiently
- D. Pre-load the entire codebase structure into the initial context before exploration begins
Answer & explanation
Correct: A
- A is correct: Scratchpad files persist knowledge outside the conversation context, directly counteracting context degradation by keeping critical discoveries accessible regardless of context state.
- B is wrong: Context degradation is not about running out of tokens. It is about the model losing grip on earlier findings as verbose output accumulates. A larger window still fills with verbose output.
- C is wrong: Restarting loses all accumulated knowledge without addressing the underlying problem. Without scratchpad files, the same degradation will recur.
- D is wrong: Pre-loading consumes context budget before exploration starts and does not address degradation during the session.
Question 2
Section titled “Question 2”A codebase exploration agent delegates investigation to three subagents. The main agent’s context stays clean while subagents handle verbose file reading and search operations. What is the primary benefit of this delegation pattern?
- A. Parallelisation — the three subagents can investigate simultaneously, reducing wall-clock time
- B. Cost reduction — subagents use cheaper model tiers for routine file reading
- C. Context isolation — the main agent’s context is not filled with verbose exploration output
- D. Error handling — subagent failures do not crash the main agent
Answer & explanation
Correct: C
- A is wrong: While parallelisation is a secondary benefit, the primary value for codebase exploration is keeping the main agent’s context clean.
- B is wrong: Model tier selection is a separate concern. Delegation for context isolation applies regardless of which model each agent uses.
- C is correct: Subagent delegation for codebase exploration is primarily about context isolation. The main agent preserves high-level coordination context while subagents handle verbose output in their own isolated contexts.
- D is wrong: Error handling is a benefit of structured error propagation, not the primary purpose of delegation in this context.
Question 3
Section titled “Question 3”An agent completes Phase 1 of codebase exploration (architecture overview) and is about to spawn subagents for Phase 2 (detailed component investigation). What should happen between phases?
- A. The subagents should start fresh and re-discover the architecture to verify Phase 1 findings
- B. Phase 1 findings should be summarised and injected into Phase 2 subagent prompts
- C. Phase 1 verbose output should be passed directly to Phase 2 subagents for complete context
- D. Phase 2 subagents should read the Phase 1 conversation log from storage
Answer & explanation
Correct: B
- A is wrong: Re-discovering architecture duplicates work and wastes Phase 2 context budget on already-known information.
- B is correct: Summary injection provides Phase 2 agents with architectural context without the verbose output. This prevents the cold-start problem where Phase 2 agents duplicate Phase 1 exploration.
- C is wrong: Passing verbose output defeats the purpose of context isolation. Phase 2 agents would start with contexts already filled with Phase 1 exploration noise.
- D is wrong: Full conversation logs include verbose discovery output that would pollute Phase 2 context. Summaries are the correct transfer mechanism.
Question 4
Section titled “Question 4”During an extended codebase exploration, the agent’s context is filling with verbose file contents and search results. When should the /compact command be used?
- A. Only when the agent hits the context limit and can no longer process new input
- B. Only when the agent explicitly reports that it is losing track of earlier findings
- C. At the end of the session to create a clean summary for the next session
- D. Proactively during the session to maintain context quality before limits are reached
Answer & explanation
Correct: D
- A is wrong: Waiting until the limit is hit means the agent has already been degrading. /compact should be used before quality deteriorates.
- B is wrong: By the time the agent reports losing track, context degradation has been affecting outputs for some time. Proactive use prevents this.
- C is wrong: Using /compact only at the end misses the opportunity to maintain quality throughout the session. By the end, degradation has already occurred.
- D is correct: /compact is a tool for maintaining context quality proactively, not just context quantity. Use it during extended sessions before degradation sets in.
Question 5
Section titled “Question 5”A codebase exploration session crashes after 45 minutes of investigation. The agent had discovered critical dependency chains and test coverage gaps. Without any recovery mechanism, what happens?
- A. The model retains findings from the session and can continue in a new session
- B. All exploration progress is lost and must be repeated from scratch
- C. The findings are preserved in the model’s long-term memory for future sessions
- D. The conversation history is automatically saved and can be resumed
Answer & explanation
Correct: B
- A is wrong: The Claude API is stateless. There is no session memory that persists across separate API calls or sessions.
- B is correct: Without crash recovery (structured state manifests), all progress is lost. This is why agents should export state to manifest files at regular checkpoints.
- C is wrong: LLMs have no long-term memory across sessions. Each session starts fresh unless state is explicitly persisted.
- D is wrong: Conversation history is not automatically saved for API-based usage. Explicit state persistence (manifest files) is required.