Manage context effectively in large codebase exploration
Learning objectives
Explore a large repository through bounded questions, preserve source-linked findings across context boundaries, and resume from verified artifacts after interruption. Use compaction without confusing a summary with the current codebase.
Notice loss of grounding
An extended session may begin referring to “typical service patterns” instead of the classes and functions actually found earlier. Inconsistent names, forgotten constraints, and repeated searches are signs to inspect the active context and saved evidence. They do not prove that every inconsistency came from context size; a wrong checkout or stale note can produce similar symptoms.
Monitor context usage with the interface's supported inspection tools. In the supplied Claude Code workflow, /context helps inspect active context and /memory helps inspect persistent instruction sources. Cache reuse can reduce processing cost under eligible conditions, but it does not restore forgotten evidence or make stale files current.
Ask a bounded repository question
Begin with the task: for example, “trace refund requests from the API handler to the transaction commit, including rejection paths.” Locate likely entry points, then follow imports, calls, aliases, and relevant tests. Read the code needed to establish the flow rather than loading every file.
Another bounded task might be to locate relevant test files. Specify the directories and naming conventions searched, exclusions, and any truncation. Finding every filename is different from reading every test or establishing behavioral coverage. Preserve that distinction in the result.
Stop exploration when the question has enough evidence for the next decision, or when a specific unresolved dependency needs another source. A broad search followed by targeted reads is useful; endlessly broadening the search without a hypothesis is not.
Keep a source-linked scratchpad
Use a task note such as NOTES.md or a structured artifact for findings, decisions, exact locations, inspected revision, changed files, observed checks, open questions, and next steps. Keep transient discoveries separate from long-lived project conventions in CLAUDE.md.
Update the note at meaningful phase boundaries. A note saying “refund code understood” is insufficient; name the handler, validator, service, and persistence transition actually examined. Mark assumptions and unchecked paths. On a follow-up question, read the note and reopen the relevant current code if the decision depends on it.
The note persists only if it is saved in accessible storage, and it influences a later request only when it is loaded. Setting a working directory does not prove that every arbitrary note was automatically read. A high-level summary helps navigation, but more precise primary evidence can override an incorrect summary.
Delegate exploration with a clear return contract
A specialized worker can isolate verbose file reads and return a compact dependency map. Give it the scope, current findings, revision, tools and permissions, and required return fields. Ask for evidence, limitations, and artifact references rather than a long private reasoning narrative.
Independent questions can be investigated concurrently. A later question that depends on the refund-flow map should receive that verified map before its worker starts. A new worker does not automatically know the parent's discoveries. Inspect whether the runtime starts fresh or forks context, and supply the needed task packet explicitly.
The parent remains responsible for integration. A concise worker report can be incomplete or wrong. Reopen decisive code when checking a conflict or acting on a high-impact finding. Context isolation reduces the parent's intermediate transcript; it does not eliminate the worker's cost or provide filesystem isolation.
Export state through a recovery manifest
For a long investigation, maintain a manifest that points to each worker's saved output, its scope, input revision, completion status, and validation status. Give workers separate write domains and let a coordinator publish the accepted combined state. Concurrent edits to one shared JSON file can overwrite each other.
Use atomic publication or another appropriate storage consistency mechanism. Single-writer ownership reduces one class of race but does not guarantee crash-safe writes, correct content, or isolation from every external writer. Verify saved artifacts before treating the manifest as a checkpoint.
This illustrative manifest describes a partially completed exploration:
{
"task_id": "refund-flow-R7",
"repository_revision": "R7",
"phases": [
{"name":"entry_points","status":"complete","validation":"source_compared","artifact":"work/refund/entry-points.md"},
{"name":"transaction_path","status":"partial","validation":"pending","artifact":"work/refund/transaction-path.md"}
],
"open_questions": ["Does the caller roll back when the commit operation fails?"],
"next_action": "Read the transaction caller and its failure-path tests before declaring the flow reviewed."
}
It preserves a known-good first phase without mislabeling the second. The relative artifact paths are references under the teaching project's root; the coordinator must resolve and read them, not assume they exist because a JSON string names them.
Resume against current state
After interruption, load the manifest, verify the repository and revision, confirm artifacts exist and have the expected content, and inspect any operations whose completion is uncertain. Reload only the relevant state into each resumed worker.
If the checkout is now R8 and the transaction caller changed, retain still-valid entry-point evidence where justified, but recheck the affected path. A session ID or initialization event identifies a session; it does not prove that all earlier state was restored correctly or remains applicable. Cross-machine recovery needs both the transcript or exported state and the referenced files, dependencies, intended workspace/account and credential identity or an approved secret reference, and actual access permissions. Do not copy secret keys, tokens or passwords into the transcript, manifest or handoff; knowing a secret reference does not grant access.
A repository checkpoint can help recover versioned files. It does not capture every ignored artifact, database action, or external service change. Do not claim that resuming a conversation rolls those effects back.
Compact with a preservation target
The supplied workflow allows focused compaction, for example /compact focus on the refund flow, inspected revision, open transaction question, and observed test results. First save decisive details in the task note. After compaction, verify that the remaining state still supports the next action.
Compaction instructions guide summarization; they do not guarantee exact preservation. Keep amounts, dates, identifiers, signatures, and observed failures in structured facts or referenced evidence when precision matters. Clearing the conversation removes immediate context; it is suitable only when the necessary continuation evidence is safely recoverable.
If one huge read repeatedly refills the context, repeating compaction alone can thrash. Narrow the read to a function or range, filter irrelevant output at the source, or isolate the investigation. A file path returned instead of content is not proof that its full body was reviewed.
Complete a bounded exploration handoff
Consider this fictional repository: src/refund/handler.ts:8 calls validateRefund at validator.ts:4, then refundService at service.ts:12, which calls commitRefund at repository.ts:30. These are teaching inputs, not findings from a real checkout. A scratchpad can state task refund-trace, revision R7, objective “trace rejection and commit,” examined locations above, finding “validation precedes commit,” unchecked question “does commit failure roll back?,” observed checks none, and next step “read caller error handling and its tests.” Save that record, then actually load it and reopen the relevant current code for a later rollback question. An R8 change to the caller leaves that path pending recheck; an unread/missing note cannot reconstruct it.
A separate fictional test-discovery task searches only src/refund/ and tests/refund/ at R7 for *.test.ts and *.spec.ts, excluding generated/vendor directories. Suppose the supplied tree contains exactly src/refund/handler.test.ts and tests/refund/rollback.spec.ts. Return that complete expected filename set with searched roots/patterns and “contents/behavior not yet reviewed.” A refund-flow worker returns the location-linked map above plus the unresolved rollback edge, without executing a refund.
Before a dependent test-analysis phase, persist the checked phase-A map and give phase B an explicit initial packet: “Revision R7; trace handler8→validator4→service12→repository30; rollback handling unverified; evidence in saved trace; inspect rollback.spec.ts and the current caller to determine the failure contract. Return exact locations, expected versus actual checks and gaps.” If phase A is incomplete, sources changed or references unavailable, phase B remains pending until its prerequisites are established. A summary delivered only to the parent is not automatic input to a fresh worker.
Qualify loading, workers and resource claims
CLAUDE.md guidance, configured auto memory, imported content, path-triggered rules and deliberately read NOTES.md have different loading roles. Imports still consume context; conditional rules are not globally loaded merely because they exist. The source's target below 200 lines per instruction file is advice, not a critical correctness boundary or guaranteed adherence below it. Check the actually loaded state. Project guidance is not hard factual-source or permission enforcement. In that supplied snapshot, configured auto memory consists of notes generated from user corrections and preferences. Its startup timeline places configured CLAUDE.md, auto memory, MCP tool names and skill descriptions in the initial context before the first user input; later file reads and tool outputs accumulate separately. As the described context limit approaches, older tool outputs are cleared before conversation summarization if needed. Preserve decisive evidence in accessible records and inspect the actual retained state; those source-client descriptions do not prove every custom note auto-loads or every early detail survives.
Source-standard workers start fresh with their own supplied task/project context; forks inherit conversation history under the supported runtime. Both still need adequate current evidence and authority. The source describes a default three-layer nesting limit and CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTH override; a fork retaining an Agent tool at the boundary does not bypass the same spawn restriction. Task/Agent/AgentDefinition option names, deferred MCP schemas and tool access are host-specific. Reduced definitions can lower some overhead but do not establish invocation, readonly effects or zero total cost.
The source's malformed agent frontmatter is conceptual rather than a working configuration. A supported host-specific configuration needs valid delimiters and name/description/tools fields; e.g., a conceptual worker named refund-tracer, described as “trace the scoped refund path,” with only the actual permitted read tools. Validate the real host schema before invocation. A definition is not evidence a worker ran. Nesting/resource/permission errors stay explicit pending/failure outcomes.
For idealized independent workers taking three and five minutes, the worker phase is five minutes. Add actual dispatch, queueing, verification and synthesis to full elapsed time; resource consumption includes both workers and retries. Typical 1,000–2,000-token summaries are not hard caps or proof that decisive conditions survived. Runtime exploration and indexed retrieval each depend on source revision, freshness and configuration; neither is always faster or current.
Make recovery identity and effects explicit
At the authorized teaching-root location teaching/recovery.json, this complete expected manifest contains the exact UTF-8 teaching artifact texts (including their final LF) and fingerprints, not real-repository observations: {"schema_version":"teaching-state-1","task_id":"refund-flow-R7","run_id":"teaching-run-1","session_id":"teaching-session-1","coordinator":"C1","checkpoint_id":"cp2","inputs":{"repository_revision":"R7","status":"stipulated fictional repository"},"agents":[{"agent_id":"A1","write_domain":"teaching/A1","status":"complete","validation":"expected_source_compared","artifact":"teaching/A1/entry-points.md","sha256":"1f032240a52613161f5d4e5655c742c073be32580619d9eb5a23460e5b9fdedc","content":"R7: handler.ts:8 -> validator.ts:4 -> service.ts:12 -> repository.ts:30. Validation precedes commit. No tests executed.\n"},{"agent_id":"B1","write_domain":"teaching/B1","status":"partial","validation":"pending","artifact":"teaching/B1/transaction-path.md","sha256":"d5716f1c363b8f396833d3876d4c9042af01693ac1894ca9362712fa5cda1136","content":"R7: rollback behavior remains unchecked; inspect caller error handling and rollback.spec.ts.\n"}],"external_effects":[],"effects_status":"none performed","open_questions":["Does commit failure roll back?"],"next_action":"Read the current caller and rollback test before declaring transaction path complete"}. Resolve the artifact paths under that root, read and compare actual bytes and identities, distinguish completed A1 from pending B1, check current authority and effect state, then inject only supported findings into a resumed prompt. The hashes identify these declared teaching strings; they do not verify the fictional repository or indicate any API/Git execution.
Select the actual intended session/task/workspace through the supported resume mechanism. Known matching state can continue; changed R8 input requires affected-path revalidation; a missing transcript/artifact or partial mirror stays incomplete rather than being refreshed to look current. A local transcript save, shared SessionStore mirror, container-volume mount and custom manifest are different persistence layers. Verify actual storage/mirror completion and authorized new-host access; the source's /data/adapter examples do not establish universal directories, supported SDK calls or successful cross-host restoration. An init event or tool list supplies no new authority and does not prove earlier analysis loaded.
Git checkpoints version only selected owned files. Link the selected revision to the manifest and inspect the authorized intended file set before any actual staging/commit/revert. The source's git add . sketch is not a manifest implementation or permission to stage unrelated files/secrets. Transcripts, ignored artifacts, database writes and external actions require their own real state records; restoring Git cannot reverse them. No repository mutation is performed by this example.
Inspect compaction and diagnostics by their actual scope
Manual focus and automatic summarization share lossy tradeoffs; neither guarantees exact retained bytes. The source v2.1.198 thinking-inheritance description concerns summary production only, not a permanent change to later session settings. Save changed-file lists, test commands/results, precise findings and pending constraints and inspect the resulting retained state.
The described rewind menu's “Summarize from here” condenses later messages while retaining earlier context; “Summarize up to here” condenses earlier messages while retaining recent ones. These are context choices, not universal file rollback. /autocompact 500k is a source example requiring actual model capacity/interface support, not a universal default. Clear/reset only after necessary state is recoverable or no longer needed; reset is not completion.
Oversized output that immediately refills the window can cause thrashing, while Not enough messages to compact can occur with few turns despite one huge paste filling the window. Distinguish those observations. The expected adjustment is a relevant smaller range or source-side filter and retained pending scope, followed by actual inspection of the result; another identical failed compaction is not a verified repair. None of these commands is run here.
Context-token reduction, cache eligibility, elapsed latency, CPU/memory and total cost are different measures. A cache miss after a break does not prove lost facts or require unnecessary keepalive requests. The source's /heapdump and Desktop output suggestion is diagnostic advice requiring actual useful evidence, supported interface and authorized artifact location; it is not a project action or proof that compaction reduces process memory. Measure resource claims before reporting improvement. The supplied knowledge is a local compiled snapshot. Its original citation-anchor attachments were not provided or independently inspected here, and current product availability and behavior have not been externally verified. Source interface/version descriptions retain that evidence boundary.
Preserve concrete configuration and focus examples
The source's financial-agent fragment has malformed -- delimiters and a list-style name line, with tools: [Bash, Read, Write]. Those tools are not a read-only contract. A complete conceptual alternative for the bounded read task is shown below. Its valid frontmatter shape illustrates the intended fields; check the actual host's accepted fields, tool identifiers and permissions before registration or invocation. The body is the worker instruction, not evidence that a worker ran.
---
name: refund-tracer
description: Trace the declared refund call path and report unresolved dependencies.
tools: [Read, Glob, Grep]
---
Read only the authorized roots at the supplied revision. Locate the refund
entry point, follow relevant calls and prerequisite checks, and return exact
file locations, inspected scope and unresolved error paths. Do not execute
refunds, change files or claim that uninspected tests passed.
The source's focused compaction commands also express different selection goals:
| Source example | Intended priority | Required limit on interpretation |
|---|---|---|
/compact focus on the auth bug fix |
Authentication investigation | Verify actual findings, unresolved constraints and test results survived |
/compact Focus on the API changes |
API-related changes | Other decisive evidence may still need a saved reference and later read |
/compact keep only the plan and the diff |
Plan and diff over verbose output | This can omit necessary original facts; save required evidence before using it |
These are local interface examples, not executed commands or instructions to drop required evidence. The persistent instruction to preserve all modified files and test commands can guide either manual or automatic compaction; verify the resulting summary rather than assume a focused command or short instruction file enforces exact retention.
Summary
Explore through specific questions, save concrete findings and unresolved dependencies, and carry verified phase summaries into later work. Recover from a manifest tied to real artifacts and the current revision. Use compaction to manage context while keeping precise evidence retrievable.
