Skip to content
Domain 5Task 5.4

Codebase Exploration & Context Degradation

Learn this interactively

What You Need to Know

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.

Context Degradation

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

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.

markdown
# 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.

Subagent Delegation

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.

Summary Injection Between Phases

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

The /compact Command

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

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
json
{
  "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.

In the exam

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.

Key Concept

Context degradation means the model stops using specific findings that it made earlier. It is not a token limit problem. Scratchpad files keep findings outside the context. Subagents isolate verbose exploration. Manifests prevent the loss of progress across sessions.

Current state

Exam guide v1.0 teaches crash recovery through state manifests "that the coordinator loads on resume and injects into agent prompts". Current state (checked 14 October 2026): the subagents docs say "You can resume a subagent after restarting Claude Code by resuming the same session", and a resumed subagent keeps its "full conversation history, including all previous tool calls, results, and reasoning." In Claude Code, a restart need not lose a subagent's work. On the exam, answer with the state manifest.

Exam Traps

Exam Trap

Increasing the context window to solve context degradation

Degradation comes from verbose output pushing earlier findings further back in the context, not from running out of tokens, so a larger window still fills with that output. Record key findings in a scratchpad file outside the context and refer back to it.

Exam Trap

Expecting next-phase subagents to inherit phase-one history, or handing each the full transcript

A subagent starts with its own isolated context. It does not see the parent's conversation history. A full transcript copied into each subagent can exceed its budget. Summarise the key findings and inject the summary into each subagent's initial context.

Exam Trap

Restarting a session to fix context degradation without saving state

Restarting loses all accumulated knowledge. Use scratchpad files and state manifests to persist findings before restarting, then inject them into the new session.

Exam Trap

Using /compact only when hitting context limits

/compact should be used proactively during extended sessions to maintain context quality, not just as a last resort when context is exhausted.

Practice Scenario

A Claude Code 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 Exercise

Build a Context-Resilient Codebase Explorer

Difficulty
60 minutes

What you'll learn

  • Recognise context degradation as an attention quality problem, not a token limit problem
  • Implement scratchpad files to persist key findings outside the conversation context
  • Use subagent delegation for context isolation, not just parallelisation
  • Design crash recovery via structured state manifests for session resilience
  • Apply summary injection between exploration phases to prevent cold start duplication
  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 free of verbose output 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 free of raw verbose output.

  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. So the attention shift does not affect that knowledge. That shift is what 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.

  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.

  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 the beginning.

    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 the point where it stopped.

  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.

Sources