Stop Token Drain: Fix Claude Code Agentic Loop Hangs with .claudecodeignore
You launched claude in your terminal, typed a simple refactor request, and walked away to grab coffee. Five minutes later you're back to find the token counter has jumped by 200,000 tokens and the agent is still stuck repeating "Searching for..." on a loop. If that sounds familiar, you're not alone — and it's not a bug in your prompt. It's almost always a missing .claudecodeignore file.
Claude Code, Anthropic's autonomous CLI agent, is genuinely impressive at navigating a codebase on its own. But "autonomous" also means it will happily crawl every file it can reach, including the ones you never intended it to read. That's how a five-minute refactor turns into a billing surprise.
Anatomy of an Agentic Loop Hang: Why Claude Code Runs Wild
Think of Claude Code's file-search tool like a delivery driver who's been told "just find the address yourself." Most of the time it works fine. But if the street signs keep changing every few seconds — which is exactly what happens with hot-reload logs or a live SQLite file — the driver never stops circling the block to "re-verify" the address. That's the Agentic Loop Hang in a nutshell.
By default, Claude Code respects your .gitignore. That sounds safe, but .gitignore was designed for a completely different job: deciding what Git should version, not what an LLM agent should read. Plenty of files you deliberately keep tracked in Git — like package-lock.json or a mock database — are exactly the kind of dead weight you don't want fed into an agent's context window.
Here's why each trigger causes real damage:
- The "Infinite Search" Trap — When Claude detects a directory that keeps changing (build output, active logs,
.cache/), it interprets the change as new state and re-runs its search tool to "confirm" the environment. Multiply that by every file-write event during a dev server session, and you get a recursive loop that never settles. - The Cost of Lockfiles — A
pnpm-lock.yamlorpackage-lock.jsoncan easily run 20,000+ lines of machine-generated metadata. None of it is semantically useful for coding, but Claude Code will tokenize every line if it's not blocked. It's the silent sponge soaking up your token budget. - The Visual/Binary Blindspot — Feed an LLM a
.pngor.sqlitebinary blob, and it can't parse the content meaningfully. Instead, it often triggers repeated error-handling retries, treating the unreadable file as a failed operation it needs to keep attempting.
Here's the loop visualized:
flowchart TD
A[Agent starts task] --> B[File search tool scans directory]
B --> C{Dynamic file detected?<br/>logs, cache, lockfile, binary}
C -- Yes --> D[Agent flags state change]
D --> E[Re-triggers search to verify]
E --> B
C -- No --> F[Reads relevant source file]
F --> G[Completes task normally]
Once you see the loop drawn out, the fix becomes obvious: cut off branch C entirely before the agent ever starts.
.gitignore vs. .claudecodeignore: They Solve Different Problems
| Feature | .gitignore |
.claudecodeignore |
|---|---|---|
| Purpose | Controls what Git tracks in version history | Controls what the Claude Code agent can read/index |
| Typical exclusions | Build artifacts, node_modules/, secrets |
Lockfiles, logs, binaries, cache — even if tracked in Git |
| Impact if misconfigured | Bloated repo history | Runaway token spend + infinite agentic loops |
| Who should use it | Every project | Every project running Claude Code CLI |
Notice the overlap column is small. Most teams already keep package-lock.json in Git on purpose — for reproducible builds — but that doesn't mean an LLM agent needs to see all 20,000 lines of it every time it opens a file in your src/ folder.
If you haven't set up Claude Code itself yet, it's worth running through the complete Claude Code CLI installation guide first — the ignore file config below assumes you already have the CLI running locally.
How to Configure .claudecodeignore (Step-by-Step)
Step 1 — Create the file at your project root.
Same directory level as your .gitignore and package.json.
touch .claudecodeignore
Step 2 — Define boundaries with standard glob patterns.
.claudecodeignore uses the same globbing syntax you already know from .gitignore — *.log, **/temp/*, trailing slashes for directories. No new syntax to learn.
Step 3 — Separate build artifacts from source.
Ask yourself: does Claude actually need to read dist/ or build/ to refactor your source code? Almost never. Compiled output is a derivative of the source — editing it directly would be pointless, and letting the agent index it just burns tokens for zero benefit.
Step 4 — Verify the boundary is actually working.
Run claude doctor to sanity-check your CLI configuration, then kick off a small test task and watch the terminal's tool-use log. If you still see Claude reading pnpm-lock.yaml or peeking into dist/, double-check for typos in your glob patterns — a missing trailing slash on a directory entry is the most common mistake.
The Ultimate Production-Ready .claudecodeignore Template
Copy this directly into your project root. It's organized by why each category causes problems, not just what it blocks.
# ====================================================================
# PRODUCTION-READY .claudecodeignore
# Prevent Claude Code Agentic Loop Hangs & Token Drain
# ====================================================================
# 1. Package Manager Lockfiles (massive text, zero semantic coding value)
package-lock.json
pnpm-lock.yaml
yarn.lock
Cargo.lock
Gemfile.lock
poetry.lock
mix.lock
# 2. Build & Compilation Outputs (keeps Claude off compiled JS/CSS)
dist/
build/
out/
.next/
.nuxt/
target/
bin/
obj/
# 3. Dynamic Cache & System Files (prevents recursive loop-scans mid-dev)
.cache/
.sass-cache/
.eslintcache
.parcel-cache
.turbo/
.vercel/
.npm/
# 4. Logs and Databases (live writes trigger infinite read loops)
*.log
*.sqlite
*.sqlite-journal
*.db
ghost-local.db
pnpm-debug.log*
yarn-debug.log*
yarn-error.log*
# 5. Media, Assets & Heavy Binaries (LLMs can't debug raw binary data)
*.png
*.jpg
*.jpeg
*.gif
*.svg
*.ico
*.mp4
*.pdf
*.zip
*.tar.gz
Save it, restart your Claude Code session, and the agent's visible file tree shrinks dramatically — which is exactly the point.
Which Model Should Handle Your Agentic Coding Tasks?
The .claudecodeignore fix matters even more once you realize how much raw throughput today's frontier models are capable of. According to the Vellum LLM Leaderboard's SWE-Bench Verified scores, the agentic coding gap between top models is razor thin — meaning wasted tokens on noise files hurt you regardless of which model you pick.
| Model | SWE-Bench Verified Score | Best Fit For |
|---|---|---|
GPT-5.6 Sol |
96.2% | Long multi-file refactors requiring deep planning |
Claude Mythos 5 |
95.5% | Autonomous agentic loops with tool-heavy CLI workflows (Claude Code's native model) |
Claude Fable 5 |
95.0% | Lightweight, fast iterative debugging sessions |
Since Claude Code is built natively around Anthropic's own model family, Claude Mythos 5 is the default and most tightly integrated choice for CLI-based agentic runs — but the token-drain problem exists regardless of which model powers the agent. A perfectly tuned model still wastes money re-reading a 20,000-line lockfile every single turn.
Pro-Tips for Optimizing Claude Code Token Budgets
💡 Key Efficiency Rules
- Explicit Target Task Boundaries. Don't prompt with
claude "Refactor my project". Instead, scope it tightly:claude "Refactor types in /src/components". A narrow prompt combined with.claudecodeignoremeans the agent's search space shrinks from "everything" to "exactly what matters." - The Clean-Before-Run Rule. Run
npm run clean(or your equivalent) before launching any agent session. Even with a solid ignore config, an emptydist/folder guarantees zero leakage — belt and suspenders.
If you're curious about the bigger financial picture beyond just this one config file, our LLM API cost optimization guide breaks down how uncontrolled context windows inflate API bills across providers, not just Claude Code specifically.
A single .claudecodeignore file at your project root is the difference between a five-minute agentic refactor and a runaway loop draining your token quota before you've had your coffee. The fix costs you two minutes of setup and pays for itself on the very first run.
Run the test yourself: check your token usage before and after adding this config on your next refactoring task. If this stopped a loop hang or cut your bill noticeably, drop a comment with your before/after numbers — it helps other developers gauge how much this actually saves in practice.
Specializing in autonomous AI CLI workflows, LLM context window optimization, and cost containment strategies for developer teams.
댓글
댓글 쓰기