Manage Context Effectively in Large Codebase Exploration
This module is about keeping Claude grounded in discovered codebase facts during long exploration sessions.
The exam’s core idea:
Large codebase exploration should not live only in conversation history.
Persist key findings to scratchpad files, delegate noisy exploration to subagents, compact strategically, and export structured state for recovery.
Claude Code’s own docs emphasize that the context window is the primary constraint: it fills with messages, file reads, and command outputs, and performance can degrade as it fills; Claude may start forgetting earlier instructions or making more mistakes when context gets crowded. (Claude)
1. Core mental model
Use this model:
Main agent = coordinator
Subagents = focused explorers
Scratchpads = durable memory
Manifests = restart/resume state
/compact = context pressure relief
Exam shortcut:
A good exploration architecture looks like this:
1. Main agent defines the exploration question.
2. Subagents investigate narrow questions.
3. Each agent writes findings to scratchpad/state files.
4. Coordinator summarizes phase results.
5. Next phase agents receive the phase summary.
6. /compact is used when context fills with verbose discovery output.
7. If the session crashes, coordinator reloads manifest and resumes.
2. Context degradation in extended sessions
The exam statement describes a common failure:
After a long exploration, Claude starts answering from generic “typical patterns” instead of the specific classes, files, and flows it discovered earlier.
Example bad answer late in a session:
But earlier exploration found:
Refunds actually enter through RefundController, call PaymentAdjustmentCommand, then emit RefundRequestedEvent, which is consumed by LedgerRefundWorker.
The issue is not that Claude cannot understand the system. The issue is that long sessions accumulate too much context, and ==earlier discoveries become less available or get summarized vaguely==.
Claude Code docs explicitly warn that debugging or codebase exploration can consume tens of thousands of tokens, and that old context can reduce performance or distract Claude. (Claude)
3. Scratchpad files
A scratchpad file is a durable file where agents record discovered facts.
It prevents this problem:
Claude discovered the answer earlier, but the conversation became too long and the fact was lost, compacted, or ignored.
Use scratchpads for:
entry points, key classes, file paths, dependency chains, test files, open questions, ruled-out paths, assumptions, phase summaries, subagent outputs
Example scratchpad path
or:
Scratchpad template
# Refund Flow Exploration Scratchpad
## Objective
Trace how refunds are requested, validated, approved, and recorded.
## Current phase
Phase 2: Trace dependencies from API entry point to ledger update.
## Confirmed entry points
- `src/refunds/RefundController.ts`
- Handles POST `/refunds`
- Calls `PaymentAdjustmentCommand`
## Key classes and files
- `src/refunds/RefundController.ts`
- `src/payments/PaymentAdjustmentCommand.ts`
- `src/events/RefundRequestedEvent.ts`
- `src/ledger/LedgerRefundWorker.ts`
## Flow summary
1. API request enters `RefundController.createRefund`.
2. Controller validates order ownership.
3. Controller creates `PaymentAdjustmentCommand`.
4. Command emits `RefundRequestedEvent`.
5. `LedgerRefundWorker` consumes event and records ledger transaction.
## Test files found
- `tests/refunds/RefundController.test.ts`
- `tests/payments/PaymentAdjustmentCommand.test.ts`
- `tests/ledger/LedgerRefundWorker.test.ts`
??? question "Open questions"
- Does `LedgerRefundWorker` handle duplicate refund events idempotently?
- Are partial refunds tested separately from full refunds?
## Files ruled out
- `src/legacy/RefundService.ts`
- Legacy path; not used by current API.
Exam point:
Scratchpads preserve specific discovered facts across context boundaries.
4. Subagent delegation for verbose exploration
Claude Code docs say subagents are useful when a side task would flood the main conversation with search results, logs, or file contents; the subagent works in its own context and returns only a summary. (Claude)
Use subagents for tasks like:
Find all test files for refund flow.
Trace all dependencies of RefundController.
Map all consumers of RefundRequestedEvent.
Find migration files related to refunds.
Identify all feature flags affecting refund behavior.
Review ledger worker idempotency.
Good main-agent prompt
Use subagents to investigate these questions independently:
1. Find all test files related to refunds.
2. Trace dependencies from RefundController to ledger update.
3. Find all consumers of RefundRequestedEvent.
4. Check whether refund processing is idempotent.
Each subagent must write a scratchpad section with:
- files inspected
- confirmed findings
- uncertain findings
- source locations
- open questions
- recommended next investigation
Why this works
The main conversation stays focused on coordination.
Verbose Grep/Glob/Read output stays inside subagent contexts.
The main agent receives compact, structured findings.
Claude Code’s context-window docs describe exactly this pattern: a subagent can handle research in its own separate context window so large reads stay out of the main session, with only a summary and small metadata trailer returning. (Claude)
5. Main conversation vs subagent
Use the main conversation when:
The task needs frequent interaction.
Multiple phases share significant context.
You are making a quick targeted change.
Latency matters.
Use subagents when:
The task is self-contained.
The output would be verbose.
You need separate exploration contexts.
You want parallel investigation.
You want tool restrictions or specialist behavior.
Claude Code docs make the same distinction: use the main conversation for frequent back-and-forth and quick targeted changes; use subagents when the work is self-contained, produces verbose output, or should return only a summary. (Claude)
6. Phase summaries before next-phase subagents
A strong large-codebase workflow is phase-based.
Bad:
This causes duplicate searches, inconsistent assumptions, and missed dependencies.
Better:
Before each new phase, summarize confirmed findings and inject that summary into each [subagent](<../D1 - Agentic Architecture & Orchestration/D1.3 - Subagent Invocation, Context Passing & Spawning.md>)’s initial prompt.
Phase 1 summary
<phase_1_summary>
Goal: Identify refund flow entry points.
Confirmed:
- Main API entry point: `src/refunds/RefundController.ts`
- Current flow does not use `src/legacy/RefundService.ts`
- Refund requests emit `RefundRequestedEvent`
Open questions:
- Which workers consume `RefundRequestedEvent`?
- Which tests cover duplicate refund events?
</phase_1_summary>
Phase 2 subagent prompt
Using the Phase 1 summary below, investigate only event consumers for `RefundRequestedEvent`.
Do not repeat the entry-point search unless necessary.
Update `.claude/exploration/refund-flow-scratchpad.md` with:
- consumers found
- file paths
- event handling behavior
- idempotency indicators
- tests found
- open questions
Exam point:
Summarize before fan-out. Inject the summary into new agents so they continue from discovered facts rather than restarting from generic assumptions.
7. /compact for extended exploration
/compact reduces conversation history by summarizing older messages while preserving important context. The command can also take focus instructions. (Claude)
Use /compact when:
The session has accumulated many file reads.
Claude starts repeating itself.
Claude references generic patterns instead of discovered files.
The context window is near full.
You are about to start a new exploration phase.
Verbose discovery output is crowding out important findings.
Bad compaction
This may preserve general narrative but lose exact file paths or decisions.
Better compaction
/compact focus on refund-flow exploration. Preserve:
- confirmed entry points
- key files and classes
- dependency chain
- test files found
- files ruled out
- unresolved questions
- scratchpad file path
- next planned subagent tasks
Claude Code docs recommend using /compact <instructions> for control, such as focusing on API changes, and note that compaction can be customized to preserve things like modified files and test commands. (Claude)
8. /context, /clear, and /compact
Know the distinction:
| Command | Use |
|---|---|
/context |
Inspect where context is going |
/compact |
Summarize current conversation to free space |
/clear |
Reset context for unrelated work |
/rewind |
Restore or summarize from a checkpoint |
/btw |
Ask a side question without adding it to history |
Claude Code’s command docs say /context visualizes context usage and optimization suggestions, /compact frees context by summarizing the conversation, and /clear starts a new conversation with empty context while preserving the old conversation for resume. (Claude)
Exam shortcut:
Same investigation getting long → /compact with focus.
Unrelated new task → /clear.
Need to inspect bloat → /context.
9. Crash recovery with structured state exports
For long codebase exploration, assume something may interrupt the session:
terminal closed
agent killed
context compacted badly
subagent stopped
Claude session resumed later
machine restarted
Do not rely only on conversation state.
Use:
Claude Code does persist sessions locally and supports resuming prior conversations with claude --continue or claude --resume; it also stores subagent transcripts separately inside the session. (Claude)
But the exam wants a stronger architecture:
Each agent exports structured state to a known location.
The D1.2 - Multi-Agent Orchestration - coordinator loads a manifest on resume.
The manifest is injected into new prompts.
10. Agent state export
Each subagent should write a state file.
Example path
Agent state schema
{
"agent_id": "refund-dependency-tracer",
"task": "Trace dependencies from RefundController to ledger update",
"status": "complete",
"last_updated": "2026-06-29T18:30:00+05:30",
"files_inspected": [
"src/refunds/RefundController.ts",
"src/payments/PaymentAdjustmentCommand.ts",
"src/events/RefundRequestedEvent.ts",
"src/ledger/LedgerRefundWorker.ts"
],
"confirmed_findings": [
{
"finding": "RefundController creates PaymentAdjustmentCommand.",
"source": "src/refunds/RefundController.ts",
"lines": "42-67"
},
{
"finding": "LedgerRefundWorker consumes RefundRequestedEvent.",
"source": "src/ledger/LedgerRefundWorker.ts",
"lines": "18-44"
}
],
"open_questions": [
"Does LedgerRefundWorker de-duplicate event IDs?"
],
"next_recommended_tasks": [
"Run idempotency-focused test search.",
"Inspect event persistence layer."
],
"scratchpad_updated": ".claude/exploration/refund-flow/refund-flow-scratchpad.md"
}
This allows recovery without reading the whole transcript.
11. Coordinator manifest
The coordinator manifest is the top-level index.
Example path
Manifest schema
{
"run_id": "refund-flow-exploration-2026-06-29",
"objective": "Understand refund request flow, dependencies, tests, and idempotency risks.",
"current_phase": "phase_3_idempotency_review",
"scratchpad": ".claude/exploration/refund-flow/refund-flow-scratchpad.md",
"phase_summaries": [
{
"phase": "phase_1_entry_points",
"summary_file": ".claude/exploration/refund-flow/phase_1_summary.md",
"status": "complete"
},
{
"phase": "phase_2_dependency_trace",
"summary_file": ".claude/exploration/refund-flow/phase_2_summary.md",
"status": "complete"
}
],
"agents": [
{
"agent_id": "refund-entrypoint-finder",
"state_file": ".claude/exploration/refund-flow/agents/refund-entrypoint-finder.json",
"status": "complete"
},
{
"agent_id": "refund-dependency-tracer",
"state_file": ".claude/exploration/refund-flow/agents/refund-dependency-tracer.json",
"status": "complete"
},
{
"agent_id": "refund-idempotency-reviewer",
"state_file": ".claude/exploration/refund-flow/agents/refund-idempotency-reviewer.json",
"status": "in_progress"
}
],
"open_questions": [
"Is refund event handling idempotent?",
"Are partial refunds covered by tests?"
],
"resume_instructions": [
"Load the scratchpad first.",
"Load completed agent state files.",
"Do not repeat Phase 1 or Phase 2 searches unless a contradiction appears.",
"Continue Phase 3 idempotency review."
]
}
Exam point:
A manifest is not just documentation. It is a structured restart contract.
12. Resume prompt
When restarting after a crash or compaction, prompt the coordinator like this:
Resume the refund-flow exploration.
First read:
- `.claude/exploration/refund-flow/manifest.json`
- the scratchpad listed in the manifest
- all completed agent state files listed in the manifest
Use the manifest as the source of truth for:
- current phase
- completed work
- open questions
- next recommended tasks
Do not repeat completed searches unless you find a contradiction.
Continue with Phase 3 idempotency review.
This is much stronger than:
13. Large codebase scoping
Context management also starts before exploration.
In large codebases, start Claude from the right directory and scope file access. Claude Code’s large-codebase docs explain that where you launch Claude determines file access and which CLAUDE.md files load; launching from a subdirectory keeps the session focused on that subtree until more access is granted. (Claude)
For exploration:
Task spans packages → start from repo root or grant additional dirs.
Task is within one subsystem → start from subsystem directory.
Task reads generated/vendor code → block or avoid those paths.
Task needs symbol navigation → use code intelligence where available.
Exam connection:
14. Practical exploration architecture
Scenario
You need to understand the refund flow in a large monorepo.
Bad workflow
Ask main agent: "Explore refunds."
Main agent greps hundreds of files.
Reads many unrelated files.
Conversation grows huge.
Later it says: "Typically refunds use RefundService."
It forgets discovered event-worker path.
Good workflow
1. Coordinator creates `.claude/exploration/refund-flow/`.
2. Coordinator writes manifest and scratchpad.
3. Subagent A finds entry points.
4. Subagent B finds tests.
5. Subagent C traces event consumers.
6. Coordinator summarizes Phase 1.
7. Coordinator injects Phase 1 summary into Phase 2 subagents.
8. Agents export state files.
9. Coordinator compacts with explicit preservation instructions.
10. On resume, coordinator reloads manifest and scratchpads.
15. Subagent prompt examples
Find all test files
Use a subagent to find all tests related to refunds.
Scope:
- Search only `packages/api` and `packages/shared`.
- Find files with refund-related test names, mocks, fixtures, or event assertions.
Return:
- test file path
- tested unit/flow
- relevant test names
- uncovered branches noticed
- confidence
- files searched
- files ruled out
Write results to:
`.claude/exploration/refund-flow/agents/refund-test-finder.json`
and update:
`.claude/exploration/refund-flow/refund-flow-scratchpad.md`
Trace dependencies
Use a subagent to trace dependencies from `RefundController.createRefund` to ledger update.
Use the existing scratchpad as starting context.
Do not repeat entry-point discovery.
Return:
- dependency chain
- exact files/classes/functions
- event producers and consumers
- external systems touched
- open questions
- source locations
Export state to:
`.claude/exploration/refund-flow/agents/refund-dependency-tracer.json`
Idempotency review
Use a subagent to review refund idempotency.
Starting facts:
- RefundController emits RefundRequestedEvent.
- LedgerRefundWorker consumes RefundRequestedEvent.
- Open question: duplicate event handling is unknown.
Investigate:
- idempotency keys
- duplicate event handling
- retry behavior
- tests for duplicate refund events
Return structured findings and update the manifest.
16. What to preserve in scratchpads
Preserve:
exact file paths
class/function names
dependency edges
confirmed entry points
ruled-out files
test file mappings
open questions
assumptions
source locations
phase summaries
next tasks
Do not preserve:
every grep result
full file contents
long reasoning chains
unfiltered logs
duplicate intermediate notes
speculation without source
This mirrors D5.1: preserve durable facts, not raw context.
17. What to include before /compact
Before running /compact, first ensure facts are written to files.
Checklist:
1. Scratchpad updated.
2. Manifest updated.
3. Subagent state files exported.
4. Phase summary written.
5. Open questions listed.
6. Next tasks listed.
7. Compaction instruction says what to preserve.
Then run:
/compact focus on refund-flow exploration. Preserve manifest path, scratchpad path, current phase, confirmed files/classes, dependency chain, open questions, and next subagent tasks.
Exam point:
/compactis useful, but it is not a substitute for structured persistence.
18. Common exam traps
Trap 1: Main conversation does all exploration
Wrong:
Right:
Trap 2: No scratchpad
Wrong:
Right:
Trap 3: Spawn next subagents without phase summary
Wrong:
Right:
Trap 4: Crash recovery relies on memory
Wrong:
Right:
Trap 5: /compact without preservation instructions
Wrong:
Better:
/compact focus on auth migration; preserve modified files, test commands, unresolved errors, and next steps.
Trap 6: Scratchpad stores raw logs
Wrong:
Right:
19. Scenario-based practice questions
Question 1
During a long codebase exploration, Claude starts saying things like:
But earlier it had found the specific classes involved.
What is the best response?
A) Continue asking in the same bloated session.
B) Refer to scratchpad files containing discovered classes and flows, compact with focus, and re-anchor Claude on confirmed findings.
C) Ask Claude to guess harder.
D) Read the entire codebase again in the main conversation.
Answer
B. The problem is context degradation. Persisted scratchpads and focused compaction re-anchor the session on exact discovered facts.
Question 2
A task requires finding all tests related to refunds across a large monorepo.
What is the best architecture?
A) Main agent reads every file.
B) Spawn a focused subagent to search tests and return a structured summary.
C) Ask the model to infer test names from conventions.
D) Skip test discovery.
Answer
B. Focused subagents isolate verbose search output and keep the main context clean.
Question 3
Before spawning Phase 2 subagents, what should the coordinator do?
A) Send no context so they start fresh.
B) Summarize Phase 1 findings and inject them into the Phase 2 prompts.
C) Delete the scratchpad.
D) Ask each subagent to rediscover everything.
Answer
B. Phase summaries prevent repeated exploration and preserve continuity across agent phases.
Question 4
A long exploration session crashes. What should the coordinator load on resume?
A) Only the latest user message.
B) Manifest, scratchpad, and structured agent state exports.
C) Random source files.
D) All raw logs from the terminal.
Answer
B. Structured state files allow recovery without relying on fragile conversation memory.
Question 5
What is the role of a scratchpad file?
A) Store every token Claude generated.
B) Persist key discovered facts, source locations, open questions, and phase summaries across context boundaries.
C) Replace tests.
D) Hide findings from the coordinator.
Answer
B. Scratchpads preserve durable exploration state.
Question 6
A subagent investigating dependencies returns 20 pages of raw file contents to the main conversation.
What is wrong?
A) Nothing; more context is always better.
B) It defeats the purpose of subagent isolation; the subagent should return a compact structured summary.
C) It should return no output.
D) It should edit files immediately.
Answer
B. Subagents should keep verbose exploration in their own context and return only useful summaries.
Question 7
The context window is filling with verbose exploration output, and the next task is still part of the same investigation.
What should you use?
A) /clear
B) /compact with focus instructions
C) Delete all scratchpads
D) Start over with no summary
Answer
B. /compact is appropriate when continuing the same investigation but needing to reduce context.
Question 8
The user is switching from refund-flow exploration to a completely unrelated UI styling task.
What is the better command?
A) /clear
B) /compact focus on refunds
C) Spawn more refund subagents
D) Keep all old context
Answer
A. For unrelated work, clear the context rather than carrying old investigation state.
Question 9
Which is the best manifest entry?
A)
B)
{
"current_phase": "phase_3_idempotency_review",
"scratchpad": ".claude/exploration/refund-flow/refund-flow-scratchpad.md",
"agents": [
{
"agent_id": "refund-dependency-tracer",
"state_file": ".claude/exploration/refund-flow/agents/refund-dependency-tracer.json",
"status": "complete"
}
],
"open_questions": [
"Does LedgerRefundWorker deduplicate duplicate events?"
],
"resume_instructions": [
"Load scratchpad and completed state files before continuing."
]
}
C)
D)
Answer
B. A manifest should be structured enough for the coordinator to resume accurately.
Question 10
When should exploration findings be written to scratchpad?
A) Only at the very end.
B) After each meaningful phase or subagent task.
C) Never.
D) Only after code is committed.
Answer
B. Frequent scratchpad updates reduce loss from compaction, context degradation, or session interruption.
20. Final D5.4 checklist
Memorize this:
1. Large-codebase exploration can degrade as context fills.
2. Degradation shows up as generic answers instead of discovered facts.
3. Persist key findings in scratchpad files.
4. Scratchpads should store exact files, symbols, flows, findings, and open questions.
5. Do not store raw logs or full file dumps in scratchpads.
6. Use subagents for verbose, self-contained exploration.
7. Main agent should coordinate high-level understanding.
8. Subagents should return structured summaries, not massive raw outputs.
9. Summarize each exploration phase before spawning the next phase.
10. Inject phase summaries into subagent prompts.
11. Use /compact when the same investigation gets long.
12. Use /compact with focus instructions.
13. Use /clear between unrelated tasks.
14. Export agent state to known files for crash recovery.
15. Maintain a coordinator manifest that can be loaded on resume.
D5.4 mental model
Main agent coordinates.
Subagents explore.
Scratchpads remember.
Manifests recover.
Phase summaries bridge.
Compact preserves.
Clear resets.
The exam’s favorite distinction is:
Do not solve large-codebase context problems by reading more files into the main conversation. Use subagents, scratchpads, phase summaries, compaction, and structured recovery state.