Direct answer
Reduce monorepo search burn by narrowing the repository before searching, mapping package ownership, retrieving candidate files and only then reading focused sections. Repeated broad grep loops often mean the task lacks a symbol map, a package boundary or a stopping rule.
Use root and subdirectory context files, ignore generated directories, send read-only subagents to scout named packages and keep a search budget. Do not assume semantic retrieval guarantees a fixed token saving. The frozen evidence contains no controlled Claude Code token-reduction percentage. Measure search calls, duplicate reads, fresh-input tokens and verified results in your own repository.
Why grep loops happen
A broad search returns matches, not understanding. In a monorepo, the same symbol can appear in source, tests, generated clients, fixtures, documentation and vendored code. An agent can keep widening the query because each result suggests another name to inspect. The context fills with fragments before the relevant interface is resolved.
The problem is not that grep is wrong. Exact search is often the fastest way to locate a literal. The failure appears when search becomes the only navigation strategy. A package graph, symbol index or ownership map can answer “where should I look?” before a text query answers “where does this string appear?”
Official: The Anthropic large-codebase guidance recommends a root CLAUDE.md for big-picture pointers, subdirectory files for local conventions, agentic grep search, optional LSP symbol search, ignore files, read-only exploration subagents, per-subdirectory commands and codebase maps.
That guidance does not authorize a universal savings claim. Unknown: The supplied sources contain no controlled percentage for token reduction from scoped search or semantic retrieval. Treat retrieval changes as hypotheses to measure, not promises to print in a benchmark graphic.
Start with repository scope
A task should name the package or capability before it names a symbol. “Fix invoice rounding” is still broad in a repository with billing, checkout, ledger and reporting packages. “Trace the invoice subtotal calculation in the billing package, then check its checkout caller” gives search a boundary.
Write the scope into the task brief. Include the likely package, the entry point and the directories that are out of scope. If the scope is wrong, the agent should report that after a bounded search rather than silently scanning the whole repository.
A root context file should point to the package map, build commands and ownership conventions. Subdirectory files should hold local rules. The legacy-code tribal knowledge guide explains why undocumented ownership and business rules need a durable home outside an agent’s temporary context.
| Scope level | Useful pointer | Search effect |
|---|---|---|
| Repository | Package map and build entry points | Prevents blind root scans |
| Domain | Service or feature boundary | Narrows candidate packages |
| Package | Public exports and local commands | Focuses symbol lookup |
| Module | File ownership and tests | Directs exact grep or LSP queries |
| Symbol | Definition and call sites | Supports focused reads |
Ignore files matter because generated code can dominate search results. Exclude build output, dependency directories and generated clients when they are not the task. Document an exception for tasks that intentionally modify generated artifacts. The goal is not to hide relevant code but to stop irrelevant code from consuming the context budget.
Map package boundaries before semantic search
A package graph records which packages depend on which others. It can be derived from workspace manifests, import rules or an existing build system. The map does not need to be elaborate. A table of package names, public entry points, owners and dependency edges is often enough for navigation.
Semantic retrieval means finding code by meaning rather than only literal text. It can help when the task uses a business term that differs from the symbol name. It can also return plausible but irrelevant files if the index is stale or the query is vague. Use it to propose candidates, then verify them with exact search and focused reads.
This retrieval strategy is not a claim that every repository needs a vector database. Start with the package map and existing search tools. Add semantic retrieval only when a measured navigation problem justifies it.
| Retrieval stage | Question | Tool or artifact | Stop condition |
|---|---|---|---|
| Scope | Which capability owns the change? | Root context and package map | Package identified |
| Locate | Which symbol or file implements it? | LSP or exact grep | Definition found |
| Expand | Who calls or depends on it? | Import graph or call-site search | Relevant callers listed |
| Verify | Does the candidate match the requirement? | Focused reads and tests | Behavior confirmed |
| Change | What is the smallest safe edit? | Worktree and diff | Reviewed patch ready |
A stale index is a data-quality problem. Note the commit used to build the map or index. If the task changes package structure, refresh the map before trusting it. The Claude Code migration context-portability guide provides a useful pattern for keeping navigation evidence attached to a repository change.
Use subagents as scouts, not a shared memory shortcut
Official: Custom subagents start with fresh, isolated context. Initial context includes the system prompt, task message, CLAUDE.md files, git status and preloaded skills. They do not automatically see the parent’s full history. The subagent documentation also says combined custom descriptions above 15,000 tokens trigger a startup warning, and the default concurrent subagent limit is 20.
That isolation can reduce duplicated reading in the parent, but it does not eliminate duplicated discovery among scouts. If four agents each search the same repository without a handoff packet, they can all read the same package map and repeat the same exact searches. The subagent duplicate-work analysis explains how to share a task brief without assuming hidden shared memory.
Give each scout a named package, a question and a return format. Ask for candidate files, relevant symbols, tests and unresolved questions. Do not ask for a full repository summary. A compact report gives the parent enough evidence to decide the next read.
| Scout brief | Scope | Return |
|---|---|---|
| Package explorer | One package | Entry points and public symbols |
| Call-site scout | One symbol | Direct callers and dependent packages |
| Test locator | One behavior | Relevant tests and fixtures |
| Legacy reader | One module | Undocumented rules and confidence |
Parallel scouts also need separate file state if they will edit. The parallel-agent worktree isolation guide explains how worktrees reduce shared-file collisions. Read-only scouting does not need a worktree for every agent, but it still needs non-overlapping questions and a merge step for the reports.
Set a search budget before the loop starts
A search budget is a local workflow rule, not a documented hard cap. It can limit broad searches, candidate files or repeated reads. The purpose is to force a decision: refine the query, consult the package map, ask a human or change the task scope.
For example, a team might allow three broad repository searches before requiring a package map. That number is a policy choice, not a vendor limit. A narrow search inside an identified package can continue under a different budget because its expected result is more specific.
Derived: If a task permits three broad searches and each returns twenty candidate files, the raw candidate count is 3 × 20 = 60 file references before deduplication. That arithmetic does not measure tokens or usefulness. It shows why a candidate cap and deduplication step belong in the workflow.
| Budget | Unit | Reset condition | Escalation |
|---|---|---|---|
| Broad searches | Query count | Package identified | Build or repair package map |
| Candidate files | Unique paths | Candidate set reviewed | Narrow query or ask owner |
| Duplicate reads | Repeated file reads | Read cache or handoff updated | Return a compact scout report |
| Focused reads | Sections per candidate | Candidate verified | Stop and summarize uncertainty |
| Context checkpoints | Summary or task reset | Scope changes | Compact or start a focused session |
The Claude Code compaction context-retention test explains that compaction replaces older turns with a server-written summary while recent turns remain word for word. Compaction can make room, but it does not repair a bad retrieval strategy. Preserve the package map and candidate list in files so a summary does not have to carry every detail.
Distinguish exact search from semantic retrieval
Exact search is best for literals: a symbol name, error string, configuration key or migration identifier. Semantic retrieval is best for concepts: “where do we enforce invoice eligibility?” when the code uses a different term. LSP symbol search can help with definitions and references when the repository supports it.
A good sequence often starts exact. Search the named package for the literal, inspect the definition, then follow direct callers. If the literal is absent or the terminology is unclear, use semantic retrieval to propose candidates. Verify each candidate with an exact path or symbol before reading broadly.
Do not treat semantic similarity as evidence of ownership. A retrieved file can discuss the same business term while belonging to another domain. Explain why each candidate is relevant. If the reason is only “the embedding looked close,” the candidate needs another check.
| Query need | First choice | Verification |
|---|---|---|
| Known symbol | LSP or exact grep | Open definition and exports |
| Error string | Exact grep | Find emitter and handler |
| Business concept | Package map, then semantic retrieval | Confirm domain owner |
| Call site | Import graph or reference search | Check direct versus transitive callers |
| Generated artifact | Documented generator path | Verify source of truth |
| Legacy behavior | Tests and module notes | Characterize before changing |
The Claude Code MCP output truncation guide is relevant when search results arrive through tools. A compact candidate list with paths and reasons survives truncation better than pages of raw matches. Preserve the decisive failure or symbol, not every matching line.
Focused reads beat broad file dumps
Finding a file is not the same as reading it. Start with the definition, exports and directly relevant function. Then read the caller or test that constrains behavior. Broad file dumps can consume context with unrelated imports, comments and branches.
A useful read note records the path, symbol, reason and unresolved question. If the note says only “looks relevant,” the candidate has not earned a broad read. If it says “exports the subtotal calculator used by checkout,” the next read has a clear target.
The Claude Code long-context prefill latency test provides a measurement framework for long prompts. Separate prompt processing, first token, decode, tool execution and retries. A search-heavy task may spend time in tools rather than model decode, so do not summarize the whole delay as model speed.
| Read level | Include | Exclude initially |
|---|---|---|
| Definition | Signature, exports, core branch | Unrelated helpers |
| Caller | Invocation and data transformation | Distant transitive callers |
| Test | Relevant case and fixture | Entire test suite |
| Configuration | Active value and owner | Generated or default examples |
| History | Commit that introduced the behavior | Full repository log |
Search evidence should be reproducible. Save the query, path scope and candidate list in the change record. The Claude Code proof-of-work packet can hold those artifacts beside the final diff and test result.
A measurement scorecard
Measure retrieval as a system. Count broad searches, narrow searches, unique candidate files, repeated reads, focused sections, tool failures and verified findings. Add token or cost data only from a surface that actually reports it. Do not estimate tokens from character counts unless the method is stated and validated.
Hold the task and repository commit constant when comparing strategies. Run the old broad-search workflow, record the evidence, then run the scoped workflow on the same starting state. Pair model, version, permissions and prompt details with the result. A different model or a warmed cache can change the comparison.
The usage tracking and cost API guide explains the available telemetry boundaries. The historical Usage and Cost API is not real-time, and its cost data has documented granularity and exclusions. A local search experiment should not imply fleet-wide precision from a single session.
| Metric | How to count | Why it matters | Caveat |
|---|---|---|---|
| Broad searches | Repository-wide query count | Detects scope failure | Query count is not token count |
| Narrow searches | Package-scoped query count | Shows focused navigation | May rise while total work falls |
| Unique candidates | Deduplicated paths | Measures retrieval breadth | Relevance still needs review |
| Duplicate reads | Repeated path and section | Finds wasted context | Some rereads are intentional |
| Verified findings | Candidates confirmed useful | Measures retrieval quality | Depends on task definition |
| Fresh-input tokens | Reported usage field | Measures context pressure | Cache and billing surfaces differ |
| Verified change | Tests plus human review | Measures useful outcome | Not a retrieval-only metric |
Derived: If two runs examine the same ten candidate files but one reads each twice and the other reads each once, the repeat-read counts are twenty and ten. The difference is ten avoided repeat reads, not a claimed token saving. Token impact depends on file size, prompt structure, cache state and what the agent actually retained.
Worked example: locate a subtotal rule
Suppose the task is to change a discount threshold in a monorepo with checkout, billing, ledger and reporting packages. The requirement says the rule belongs to billing. These are illustrative inputs, not a benchmark.
The scoped workflow starts with the package map. It identifies the billing package’s public entry point and local test command. An exact search inside billing locates the subtotal calculator. A reference search then identifies checkout as the direct caller. Reporting imports a derived total but does not own the rule.
| Step | Scope | Evidence | Decision |
|---|---|---|---|
| Package map | Billing | Owner and public entry point | Search billing first |
| Exact search | src/billing |
Subtotal definition | Read core function |
| Reference search | Calculator symbol | Checkout caller | Inspect caller contract |
| Test search | Billing tests | Boundary fixture | Extend acceptance case |
| Dependency check | Reporting import | Derived total only | No edit unless contract changes |
The win is a small candidate set with an ownership reason for each file. The loss is that the map can be stale and an indirect runtime caller can be missed. Verify the final diff and integration tests rather than treating the graph as complete.
The cost per verified change framework keeps the comparison focused on useful delivery. A lower search count is not a win if the agent edits the wrong package. A slightly higher narrow-search count can be worthwhile when it prevents a broad wrong turn.
Document the stopping decision as carefully as the successful search. A note that says “no candidate found in the owning package” is more useful than a silent repository-wide fallback. It tells the reviewer whether the package map, the symbol name or the requirement needs another look.
Keep the map maintainable
A package map that takes longer to update than the repository is not a reliable control. Generate the dependency edges from workspace metadata when possible, then add human-owned notes for public entry points and business ownership. Separate generated facts from editorial notes so a reviewer knows which parts can drift mechanically.
Put the map near the root context file and link to it from package-level instructions. A short entry can name the package purpose, public exports, local test command and owning team. Avoid copying the entire dependency graph into every CLAUDE.md file. Repeated static text consumes context and creates multiple places to update.
When a package is renamed or split, update the map in the same change. Add a lightweight check that verifies mapped package paths still exist. This is an engineering control, not a documented Claude Code feature. The repository-hook security review explains the trust questions if the check runs as a hook.
A search index also needs a refresh policy. Note the source commit and the tool used to build it. If the index is older than the current task’s structural changes, prefer exact search until it is rebuilt. A stale semantic result should be labeled as a candidate, never as proof that a symbol moved or disappeared.
Do not place credentials in the map or its generation scripts. The settings-file secret exposure guide describes how configuration files can become an accidental secret store. Package ownership and dependency edges rarely need sensitive values.
Preserve a search handoff
Long investigations should leave a compact handoff. Capture the task scope, package map commit, queries already tried, candidate files, confirmed findings and open questions. The next session can then resume with focused reads instead of repeating the same broad searches.
This matters when a scout is cancelled. Official: Stopped subagents do not auto-resume when messaged, while completed subagents can be resumed with conversation history. The subagent stop and resume semantics explain the lifecycle. A written handoff is more reliable than assuming a stopped task will continue where it left off.
Store the handoff outside the conversation. A short Markdown table in the repository or a change ticket can be versioned with the work. Include only the evidence needed for the next decision. The context-portable migration guide provides a useful model for preserving findings across tools.
Review the handoff before accepting it. A list of twenty files with no reasons is not a retrieval result. Each confirmed candidate should say why it matters and what was read. Each rejected candidate should say why it was rejected when that reason could prevent the same search later.
Use the LLM cost calculator only when the input prices and token counts are known. It cannot reconstruct missing usage from a chat transcript, and it does not make a subscription quota equivalent to API pricing. The measurement scorecard should stay attached to its original data source.
Honest loss and data gap
Unknown: The frozen sources do not provide a fixed token-reduction percentage for semantic retrieval, scoped grep, LSP search or subagent scouting. They also do not establish that grep loops occur at a measurable rate across repositories. This article cannot turn a workflow recommendation into a universal benchmark.
Scoped retrieval can miss code when package ownership is wrong, generated source is authoritative or an indirect dependency matters. Semantic retrieval can surface irrelevant candidates. Subagents can duplicate discovery despite isolated context. A strict search budget can also stop a useful investigation too early.
The practical win is a visible navigation path and fewer unbounded reads. The honest loss is setup work for the package map and possible false negatives from aggressive scoping. Revisit the map when the repository structure changes, and keep a documented escape hatch for tasks that genuinely require a broader search.
A practical retrieval checklist
- Name the capability, package and out-of-scope directories.
- Read the root context and package map before a broad search.
- Use exact search for known literals and LSP for symbols when available.
- Use semantic retrieval to propose candidates, then verify ownership.
- Give read-only scouts non-overlapping questions and a return format.
- Cap broad searches and candidate files with a local workflow rule.
- Read definitions and direct callers before broad file dumps.
- Save the query, candidate list and reason for each relevant file.
- Measure duplicate reads and verified findings, not only query count.
- Store the package map and search evidence outside temporary chat context.
The Claude Code subagent hang controls matter when a scout stops producing events. A missing heartbeat is a reason to cancel or bound the tool, not to launch more broad searches. The background subagent running-count diagnosis explains why the UI count should not be the only completion signal.
When a session reaches its context boundary, read the stop reason instead of retrying blindly. Official: The stop-reason documentation distinguishes max_tokens, model_context_window_exceeded, tool_use, pause_turn, refusal, end_turn and stop_sequence. A context-limit stop calls for a narrower task or preserved handoff, not an unlimited regeneration loop.
Practical OpenAI-format alternative with One AI API Key
If you want to compare retrieval behavior across coding agents, the 46 live free model IDs run through OpenAI-format agents. The free lane shares 100 requests and 5,000,000 tokens per day per account, resets at 05:30 IST or 00:00 UTC, and allows one request in flight per key. Accounts can have up to three keys.
Use the quickstart for the base URL and first request. The pricing page explains prepaid billing, the sign-up page starts an account, and the privacy policy covers logging defaults and upstream-provider terms.
The documented Claude Code route is unavailable because all four Claude IDs were marked unavailable on November 27, 2026. Free IDs are OpenAI-format only. Never claim they work inside Claude Code. A different provider does not replace a package map, a search budget or focused verification.
New accounts receive $10 credit with no card, and billing is prepaid with no subscription or seat fee. The published controls include prompt logging off by default, per-key spend caps, expiry dates, allowed-model lists and request-level usage records. Upstream providers receive requests under their own terms. Use the per-key controls reference for a narrow test credential. The free daily allowance is shared across the free IDs, and guaranteed automatic fallback should not be promised because the supplied routing descriptions conflict.
For a retrieval comparison, configure an OpenAI-format agent with https://api.oneaiapikey.com/v1, one key and a selected free ID against a synthetic monorepo fixture. Hold the package map and task constant, then record broad searches, narrow searches, duplicate reads and verified findings. Pair the model ID and usage data with the scorecard. Note the fixture commit as well, because a changed package graph can alter the search path. Do not send a private production repository merely to compare search behavior, and do not convert the result into a universal token-saving claim.
FAQ
Is grep bad for monorepos?
No. Exact search is useful for known literals. The problem is repeated broad search without package scope, candidate review or a stopping rule.
Does semantic retrieval guarantee fewer tokens?
No. The supplied evidence contains no controlled Claude Code token-reduction percentage. Measure it on a fixed task and repository, including duplicate reads and verified findings.
Can subagents share a hidden memory?
No. Custom subagents start with isolated context. Share a written task brief, package scope and return format instead of assuming they saw the parent conversation.
When should I compact a search session?
Compact or restart when the task has wandered or context pressure is high, but preserve the package map, candidate list and unresolved questions in files. Compaction is not a substitute for focused retrieval.
What is the best sign that retrieval worked?
The agent identifies the owning package, reads the relevant definition and direct callers, and produces a verified change. Fewer searches alone do not prove success.
More Claude Code troubleshooting
- Claude Code WSL IDE environment-variable diagnosis
- Claude Code WSL2 memory-warning breakdown
- Claude Code Windows subagent MCP memory leaks
- Claude Code VS Code WebSocket regression test
- Claude Code desktop browser-pane crash recovery
- Claude Code compaction cost worksheet
- Claude Code prompt-caching break-even math
- Claude Code idle-session cache-miss analysis
- Claude Code task budgets versus hard stops
- Claude Code 429 error decision tree
- Claude Code billing-dispute evidence packet
- Claude Code refund and support policy guide
- Claude Code hallucinated-package supply-chain controls
- Claude Code GitHub Actions secret boundaries
- Claude Code extension-trojan remediation steps
- Claude Code CVE-2026-55607 sandbox boundary
- Claude Code auto-mode classifier limitations
- Claude Code destructive git guardrails
- Claude Code generated-test oracle bias
Sources
- Anthropic large-codebase search and context guidance
- Claude Code subagent context isolation
- Claude Code worktree isolation
- Claude Code troubleshooting guidance
- Claude Code compaction behavior
- Claude Code stop-reason handling