A loop happens when Claude repeats the same failed approach: it retries the same command, rewrites the same file, or apologizes and then makes the identical mistake again. Recognizing a loop early saves tokens (the units of text the model processes) and avoids compounding errors.
The fastest recovery is a scope change: instead of asking Claude to fix the broken whole, isolate the smallest piece that must work first. Give Claude a single file, a single function, or a single error message rather than the full context. Smaller scope means fewer variables and a shorter path to a correct answer.
When narrowing scope is not enough, change the approach entirely. Tell Claude explicitly what strategy to drop and what to try instead. Phrases like /clear in Claude Code (which resets the conversation context) or starting a new session prevent earlier failed attempts from biasing the next ones.
Use /clear to wipe the conversation and start fresh without losing your files.
Paste only the relevant error or code block, not the whole project.
State the constraint explicitly: Do not touch file X. Focus only on function Y.
Ask Claude to explain its plan before it acts: Describe your approach in one paragraph, then wait.
Key points
Detect a loop by counting repeated identical attempts
Use /clear to reset context without losing files
Narrow scope to one file or one function
Explicitly forbid failed strategies before retrying
Recovering from a bad edit
Claude Code edits files directly on disk. If a change breaks something, you need to act fast before the context grows and the original state is harder to trace. The two main recovery paths are git-based revert (when your project uses git, a version control system that tracks every file change) and manual undo (when it does not).
When git is available, these commands cover most situations:
See what changed:/git diff inside Claude Code, or run git diff in a terminal. This shows every line added or removed since the last saved checkpoint (called a commit).
Discard all uncommitted changes:git checkout -- . (a dot meaning "all files") resets every tracked file to the last commit. Untracked new files are left alone.
Revert one file only:git checkout -- path/to/file.js restores just that file.
Undo the last commit but keep the edits staged:git reset --soft HEAD~1. Use this when the commit happened but the code is still wrong.
Undo the last commit and discard the edits entirely:git reset --hard HEAD~1. This is destructive: the changes are gone.
If there is no git history, your options are narrower. Claude Code keeps a session transcript, so you can ask it to reprint the original content of a file it edited, then paste it back. For critical files, the safest habit is to run cp important.js important.js.bak before starting a long editing session.
You can also ask Claude Code directly: "Undo the last edit to config.js" or "Revert all your changes in this session." Claude Code will use git under the hood when available, or attempt to reconstruct the prior content from its context window (the active memory of the conversation).
Key points
git checkout -- file to restore it to the last commit
git reset --hard HEAD~1 to wipe the last commit entirely
Ask Claude Code in plain English to undo or revert
Back up critical files manually before a big session
Context got polluted
Every conversation with Claude runs inside a context window (the block of text the model can see at once). When a long session accumulates failed attempts, contradictory instructions, or noisy tool output, the model starts to weight that bad history and gives worse answers. This is called context pollution.
Claude Code gives you three levels of intervention, from least to most disruptive:
Compact (/compact): summarises the conversation so far into a short digest, keeps the summary in context, and frees up space. Use this when the session is still productive but getting long.
Clear (/clear): wipes the entire conversation history but keeps your working files and the Claude Code session open. Use this when the context is actively misleading Claude but you want to stay in the same project.
Fresh start (close and reopen Claude Code, or start a new chat): removes all session state. Use this when even a cleared context drags in bad assumptions from the open files or tool state.
A good rule of thumb: if you find yourself re-explaining something you already said three messages ago, compact first. If Claude contradicts itself or ignores a constraint you set, clear. If the model seems to be hallucinating file contents or tool results, start fresh and re-read the relevant files explicitly.
Key points
Context window fills up and degrades answer quality
Hallucinated file contents require a full fresh start
A wrong or outdated API
Claude is trained on a fixed snapshot of the world. When you ask it to call an API (an Application Programming Interface, the contract that defines how two programs talk to each other), it may generate code that matches an older version of that API. This is called a hallucinated or stale call: the code looks plausible but will fail at runtime because the endpoint, parameter name, or required header no longer exists.
The failure pattern is usually one of these:
A 404 (not found) or 410 (gone) HTTP status, meaning the URL path was retired.
A 422 or 400 (unprocessable / bad request), meaning a required field changed name or a deprecated field was rejected.
An authentication error (401/403) because the token format or header key changed (for example, some APIs moved from Authorization: Token ... to Authorization: Bearer ...).
A silent wrong result when an old optional field is now ignored and a new required field was never sent.
The fix is always the same: ground Claude in the real, current spec before asking it to write or debug the call. You can paste the relevant section of the official docs directly into your prompt, or point Claude Code at the live OpenAPI (machine-readable API description) file with /fetch. Never trust Claude to know a third-party API without a source.
In Claude Code (the command-line and IDE coding agent), the workflow is: reproduce the error, collect the raw HTTP response, fetch the current docs, then ask Claude to diff its generated code against the real spec and patch only what changed. Keep the fix surgical to avoid introducing new bugs.
Key points
Stale API call: code generated from an outdated spec
Ground Claude in the current official docs before writing calls
Use raw HTTP status codes to diagnose the failure category
Fetch the live OpenAPI spec with /fetch, then ask for a targeted patch
You hit a 429
A 429 error means "Too Many Requests." The API (Application Programming Interface, the gateway Claude Code uses to reach Claude) has a rate limit: a ceiling on how many tokens (pieces of text) you can send or receive in a given time window. Hit that ceiling and every request bounces back with a 429 until the window resets.
Claude Code reports 429s as a red error message in the terminal. The message usually includes a Retry-After header value, telling you exactly how many seconds to wait. If you are on a free or Tier-1 plan, the window is typically one minute; on higher tiers the limits are per-hour and per-day as well.
Common causes of 429s in a Claude Code session:
Running a multi-agent or parallel workflow that fans out many simultaneous calls
Using extended thinking (high budget_tokens) on repeated prompts, which burns tokens fast
Looping scripts (such as /loop or custom automation) with no delay between iterations
A large codebase context read in full on every turn instead of incrementally
To avoid 429s: read files incrementally with offset and limit, use prompt caching (prefix the stable parts of your context so they are not re-billed each turn), lower max_tokens when you do not need long answers, and add a short pause between automated calls. For heavy batch work, switch to the Batch API, which has a separate, much larger rate limit and a 50 percent cost discount.
Key points
429 = rate limit hit, wait for the window to reset
Retry-After header tells you the exact wait time
Prompt caching and incremental reads reduce token spend
Batch API has a separate limit and costs 50% less
A command hung
A hung process is one that has stopped making progress but has not exited. In Claude Code, this typically happens when a shell command waits forever for input, a network request times out silently, or a background task fills a buffer. Recognising the difference between "slow" and "truly stuck" saves you from killing work that just needs more time.
The fastest escape is Ctrl+C, which sends an interrupt signal to the foreground process. If the terminal itself is frozen, press Ctrl+C twice quickly. Claude Code will cancel the current tool call and return control to you without losing the conversation context.
For commands you know may run long, pass them as background jobs by including run_in_background: true in the tool parameters, or suffix the shell command with &. You will receive a notification when the job finishes instead of waiting inline.
Ctrl+C: interrupt and cancel the active tool call.
timeout prefix: wrap risky commands with timeout 30 <command> to auto-kill after N seconds.
background flag: use run_in_background for long builds, servers, or test suites.
/stop: the Claude Code slash command (slash commands start with /) that halts an ongoing agent loop without closing the session.
Key points
Ctrl+C cancels the active tool call and returns control
Wrap risky shell commands with the timeout prefix
Use run_in_background for long or blocking processes
/stop halts an agent loop without ending the session
Undoing changes safely
Git gives you several layers of undo, each suited to a different situation. The key is knowing which layer to reach for so you recover what you need without losing anything else.
git restore discards uncommitted edits in your working directory. Run git restore path/to/file.js to throw away unsaved changes in that file and bring it back to the last committed state. Add the --staged flag to un-stage a file without touching the edits on disk: git restore --staged path/to/file.js.
git checkout (older syntax, still widely used) can do the same thing for a single file: git checkout -- path/to/file.js. It also lets you jump to a specific commit or branch, which is useful when you want to inspect an earlier state without erasing your current work.
When you think a commit is lost, git reflog is your safety net. The reflog (short for "reference log") records every position HEAD has ever pointed to, including commits that were "deleted" by a reset or rebase. Common recovery workflow:
Run git reflog to list recent HEAD positions with short hashes.
Find the hash just before things went wrong.
Create a new branch from it: git checkout -b recovery abc1234.
Merge or cherry-pick what you need back into your main branch.
git reflog lists every HEAD position, including lost commits
always branch from a reflog hash instead of resetting hard
When to start fresh
A Claude Code session accumulates context (the full history of messages, tool calls, and file reads held in memory). When that context grows stale, contradictory, or simply too large, continuing the session costs more tokens and produces worse results than opening a new one.
Watch for these signals that salvaging is the wrong move:
Repetitive loops: Claude keeps suggesting the same broken fix after you have already rejected it.
Context confusion: Claude references an old file path, a deleted variable, or a plan you explicitly cancelled.
Token pressure: responses become terse, skip steps, or warn you that the context window is nearly full.
Cascading tool failures: three or more consecutive tool calls fail for unrelated reasons, signalling the session state is corrupted rather than the code itself.
Starting fresh does not mean losing your work. Compact summaries let you carry the essential decisions into the new session without the noise. Use /compact before you quit to compress the conversation, then copy the summary into your next session opener.
The rule of thumb: if you have spent more time arguing with the session than writing code, reset. A clean session with a well-written handoff prompt (a short paragraph describing what was done and what comes next) is faster than nursing a broken one.
Key points
Repetitive loops signal context rot, not a code problem.
Use /compact to compress history before quitting.
A handoff prompt carries decisions without noise.
Three cascading tool failures is a reset trigger.
Work with me
Master Claude, Claude Code and LLMs, from your first prompt to multi-agent orchestration.
Like this course? I built it end to end. Need a web app, mobile app, AI automation or SEO/GEO? Let us talk.