Skip to content

5.4 Codebase Exploration & Context Degradation

An agent’s context is the conversation it works from, including every tool output. Exploring a large codebase is one of the most context-intensive tasks that a Claude-based agent performs. This task covers exploring an unfamiliar repository, tracing dependency chains and understanding legacy systems. Long sessions cause context degradation. The model loses its grip on earlier findings as the context fills with verbose discovery output. Context degradation is not related to exhausting the available tokens.

This lesson uses one made-up example throughout: a joinery firm that wants to change how its job-costing system prices quotes. A developer first has a Claude-based agent explore the code for several hours.

The observable symptom is that the model starts referring to “typical patterns” instead of the specific classes, methods and dependency chains it found earlier. Early in the session, the joinery firm’s agent reports that the QuoteRepository class in src/repos/quote.ts implements Repository<T> and caches in findById. Several modules later, the agent says “this follows the typical repository pattern”.

This happens because:

  1. Each exploration step produces verbose output: file contents, search results, directory listings.
  2. That output accumulates in the conversation context.
  3. Earlier precise findings are further back in the context, while the newer verbose output dominates.
  4. The model’s attention shifts to the recent output, and it loses the specific references to earlier findings.

So a larger context window does not fix context degradation. The model no longer uses details that come before newer verbose output. It has not exhausted its space.

Scratchpad files are the primary way to limit context degradation. The agent writes important findings to a file and reads that file again for later questions. The file is outside the conversation context, so context degradation does not affect its contents. When the joinery firm’s agent needs the QuoteRepository details again, it reads the scratchpad, not its context. This example shows a scratchpad file.

# 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 Chain
RefundProcessor → OrderService → OrderRepository → PostgreSQL
RefundProcessor → 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%

Instruct agents to keep scratchpad files from the start of any extended exploration session. Scratchpad files are a deliberate strategy. They are not an emergency fix to use once answers become vague.

A subagent is a separate agent that the main agent, the coordinator, spawns for one task. Spawning subagents for specific investigation tasks is the second major way to limit context degradation. Without subagents, the coordinator does all the exploration itself. Every file that it reads and every search that it runs adds verbose output to its context. The joinery firm’s coordinator might delegate:

  • “Find all test files for the quoting service and report their coverage status”
  • “Trace the deposit payment flow from API endpoint to database and list all intermediate services”
  • “Identify all external API integrations and their error handling patterns”

Each subagent explores verbosely in its own isolated context, then returns a structured summary. The coordinator keeps only the main findings, so its context stays free of verbose output for high-level coordination. The obvious interpretation is that subagents are for parallelisation, but their main value is context isolation.

Exploration can run in phases: Phase 1 to understand the architecture, Phase 2 to investigate specific components. Before spawning Phase 2 subagents, summarise the main Phase 1 findings and inject them into the initial context of those subagents. Without this summary, the Phase 2 subagents duplicate Phase 1’s exploration, because nobody gave them the findings. This is the “cold start” problem. The summary also gives the subagents the architectural understanding to ask the right questions. The joinery firm’s Phase 2 subagent on pricing starts with knowledge of how the quoting layers connect. For example:

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 PaymentGateway

Claude Code provides a /compact command specifically for reducing context usage during extended sessions. When verbose discovery output fills the context, /compact summarises the conversation to free space. It keeps the important information. Use it proactively, not only when you reach context limits. It protects context quality, not only quantity. The joinery firm’s developer runs it partway through the session.

Crash Recovery via Structured State Manifests

Section titled “Crash Recovery via Structured State Manifests”

Extended sessions can fail because of session crashes, network interruptions or context exhaustion. Without a recovery mechanism, all exploration progress is lost. The fix is structured state persistence. Each agent exports its current state to a manifest at a known file location. The manifest includes:

  • What has been explored (files read, searches performed)
  • 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"
]
}

When the work resumes, the coordinator loads the manifest and injects it into agent prompts. The agent continues from the point where it stopped, without repeating earlier exploration. When a crash happens in the joinery firm’s Phase 2, the work restarts from the next steps in the manifest.

Exam questions usually describe the symptom: the agent refers to “typical patterns” instead of the classes it found earlier. The correct answer is scratchpad files. Wrong options enlarge the context window, but degradation is not a token problem. Or they restart without saving state, and then the findings are lost. Subagents are mainly for context isolation, not only parallelisation. /compact is for proactive use.

Five exam-style multiple-choice questions on Codebase Exploration & Context Degradation. Pick an answer, then open the explanation.

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.

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.

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.

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.

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.