Last updated 13 October 2026
Fix Claude Code hunk failed error
The mechanics of patch application and failure
The hunk failure error in Claude Code typically signals a disconnect between the agent's internal model of a file and the actual content of that file on your disk. When the agent decides to modify your code, it does not simply overwrite the file. Instead, it uses the Edit tool to generate a patch based on what it remembers from its last Read tool execution. If the file has changed even slightly since that read operation, the patching algorithm will fail because it cannot find the exact context lines it needs to anchor the change. This is a common occurrence in fast-paced development environments where a developer might be jumping between their IDE and the terminal while the agent is still processing.
Manual edits are the most frequent cause of these mismatches. If you have an auto-save feature enabled in your editor or if you manually tweak a variable while Claude Code is still thinking about its next step, the agent's plan becomes invalid. The Edit tool is designed to be safe and precise, so it will refuse to apply a patch if the surrounding code does not match its expectations. This safety mechanism prevents the agent from accidentally corrupting your source code by applying changes to the wrong location, but it can be frustrating when you are trying to work alongside the agent in real time. To stop an agent that is stuck in a loop trying to apply a failed patch, you can use the Escape key to interrupt the current process.
Line endings and whitespace as a source of conflict
Whitespace and line ending configurations often hide at the root of hunk failures. Claude Code is sensitive to the difference between LF and CRLF line endings. If your project is configured with git's core.autocrlf set to true, your files might look like they have one type of ending in your editor while the agent sees another in the terminal environment. When the agent attempts to apply a patch, the Edit tool looks for an exact bit-for-bit match of the context lines. If the agent expects a newline but finds a carriage return and a newline, the hunk will fail to apply. This is a technical limitation of how diffs are calculated and applied across different operating systems.
You should also consider your editor's formatting settings. Many modern IDEs are configured to automatically remove trailing whitespace or add a trailing newline at the end of a file upon saving. If Claude Code reads a file with three empty lines at the end and your editor suddenly collapses them into one, any subsequent Edit tool call that relies on those lines will fail. To resolve this, you can try to align your project settings in .claude/settings.json or provide specific instructions in your root CLAUDE.md file about how line endings and formatting should be handled. Consistency across your toolchain is the best defense against these invisible character conflicts. If the agent continues to struggle with formatting, you can suggest it use the Write tool to replace the file entirely instead of trying to patch it.
Context drift and history management
Context drift occurs as a conversation session grows longer and more complex. Claude Code maintains a context window that includes the history of the current session, the files it has read, and the tools it has used. If you have been working in a single session for a long time, the agent might begin to hallucinate line numbers or lose track of the most recent version of a file. This is especially common when a file has undergone multiple rounds of edits in a short period. The agent might still be referencing a version of a function from several messages ago rather than the one it just modified. This mismatch leads to the agent trying to edit lines that no longer exist in the specified format.
The /compact command is the primary tool for managing this kind of context bloat. When you run /compact, Claude Code summarizes the key points of the conversation so far and clears out the redundant details. This helps the agent refocus on the current state of the repository. If a hunk failure happens repeatedly in a long session, compacting the history often provides the agent with the clarity it needs to realize its previous assumptions about the file structure were wrong. In some cases, the drift is so significant that the only solution is to use the /clear command. This restarts the session in the same directory, clearing all history and forcing the agent to use the Read tool to get a fresh, accurate snapshot of the codebase before any further edits are attempted.
Permission levels and tool constraints
Permissions and execution modes play a significant role in how tools like Edit and Write function within your project. Claude Code operates in different modes that dictate how much autonomy it has over your files. If you are in the default mode, you might be prompted to approve every change. If you deny a change or interrupt the process with the Escape key, the agent might not correctly update its internal state to reflect that the file remains unchanged. This discrepancy leads to future hunk failures because the agent proceeds as if the edit had succeeded, creating a divergence between the disk and the agent's memory.
You can cycle through permission modes by pressing Shift+Tab within a session. Moving to a mode like acceptEdits allows the agent to apply changes more fluidly, which can sometimes bypass the friction that leads to patching errors during complex refactors. You should also verify your settings in the .claude/settings.json file or the global ~/.claude/settings.json file. These files control the specific permissions for each tool. If the Edit tool has been restricted or if the environment lacks the necessary write permissions for the directory, the agent will report failures. Commands like /status and /config provide a clear view of your current permission landscape and help you identify if a restrictive setting is causing the agent to fail when it tries to write to your files.
Visual tracking of multiple project sessions
Managing multiple concurrent development tasks increases the risk of environment conflicts. When you have several Claude Code instances running in different terminal tabs, it becomes difficult to track which agent is modifying which file. A developer might accidentally trigger a build process or a git command in one tab that affects the files an agent is trying to patch in another tab. This lack of visibility is a major contributor to the state mismatches that cause hunk failures. Using adhdTerminal provides a solution to this coordination problem by organizing your work into a single visual wall of tiles on your macOS or Windows desktop.
Each tile in adhdTerminal represents a specific Claude Code session, complete with a name, color, and number. You can see at a glance whether a session is working, waiting for your input, or has finished its task. This visual feedback prevents you from interfering with an active session by making it obvious which projects are currently under the agent's control. If a session encounters a hunk failure, you can see it immediately on your wall without having to dig through multiple terminal windows. The persistent nature of these tiles means they reopen in the same place after a restart, ensuring your workflow remains intact. This level of organization ensures that your manual work and the agent's automated edits do not collide, reducing the likelihood of patch errors.
Manual recovery through terminal or agent tools
When the Edit tool continues to fail despite your best efforts to clean up the context, you can resort to manual intervention through the agent itself. Claude Code has access to the Bash tool, which allows it to run shell commands directly in your environment. You can instruct the agent to use Bash to perform a git checkout on the problematic file to reset it to a known good state. Alternatively, you can ask the agent to use the Write tool to overwrite the entire file with the correct code. The Write tool is less efficient than the Edit tool for large files because it sends the whole content, but it is much more reliable when patches are failing because it does not rely on complex diffing logic.
If you find yourself in a loop where the agent is repeatedly failing to apply a patch and then trying the same failing patch again, you must take control of the session. Use the Escape key once to stop the agent's current thought process. Pressing Escape twice will open a history view where you can navigate back to a point before the errors started. This allows you to re-frame your request or give the agent specific instructions on how to handle the file. Running the claude doctor command is also a good step to ensure there are no underlying issues with your installation or your access to the necessary services that might be causing unexpected behavior during tool execution. Sometimes a simple update using the claude update command can also resolve internal bugs in the patching logic.
Questions people ask
How do I force Claude Code to re-read a file that had a hunk failure?
You can explicitly tell the agent to use the Read tool on the specific file again to update its internal buffer. Alternatively, use the /clear command to wipe the session history, which forces the agent to perform a fresh Read of any file it needs to modify for the next task.
Can I change the default tool Claude Code uses for file modifications?
You cannot change the default tool in the settings, but you can influence it through your prompt or instructions in your CLAUDE.md file. If the Edit tool fails often due to complex file structures, you can instruct the agent to prefer the Write tool for small files or use the Bash tool to manage changes via standard shell commands.
What should I do if the agent gets stuck in a loop of failed edits?
Interrupt the agent by pressing the Escape key to stop the current loop. Press Escape a second time to access the message history and revert the conversation to a state before the patching errors began, then provide a more specific instruction to help the agent avoid the conflict.
Read next
- Access git submodules in Claude CodeFix issues where Claude Code cannot see or modify code located inside nested git submodules within your main repository.
- Allow Claude Code to run shell scriptsResolve tool execution errors by adjusting permission settings to let Claude Code execute local bash or powershell scripts in your terminal.
- Break a linter error loop in ClaudeWhat to do when Claude Code fixes one linting error only to create another, leading to a circular set of edits.
- Change the Node version for Claude CodeResolve compatibility issues by switching the Node.js version used by Claude Code without breaking your other local development tools.