AI patch failed? Use git apply checks before another retry
TL;DR: Run git apply --check against the intended base before asking an AI tool to regenerate a failed patch. Test application in a disposable worktree, inspect the resulting diff, and run the real acceptance command. A patch that applies cleanly has passed a text integration check, not a correctness review.
What you’ll be able to do:
- Identify a stale patch without spending another model request.
- Choose a working-tree or index check deliberately.
- Preserve a failed integration attempt while deciding whether a retry is justified.
Honest take: A one-line Git error often tells you more than another full-codebase prompt.
Why should a patch failure pause the AI retry loop?
A failed patch can reflect the wrong starting revision rather than a weak model. Repeating the same request against the same stale context can produce another unusable patch while consuming more time or provider allowance.
Start by recording the base revision, the patch file, and the intended target. Keep the patch outside the repository under test so it does not become an accidental untracked deliverable. If the patch came from an agent branch, record that branch’s commit too. A screenshot of a chat diff does not identify the repository state it was generated against.
The official git-apply manual, checked November 8, 2026, distinguishes checking, applying to files, and applying to the index. Those choices are useful for AI-generated diffs regardless of which editor or model produced them.
| Check or action | Changes files? | Changes index? | Establishes correctness? |
|---|---|---|---|
git apply --check | No | No | No |
git apply | Yes | No | No |
git apply --index | Yes | Yes | No |
git apply --cached | No | Yes | No |
| Run the project’s acceptance tests | May create test artifacts | Normally no | Only what those tests assert |
These are different evidence gates. Successful application means the patch could be integrated under the selected rules. It says nothing about whether an authentication check still works or a calculation now returns the right result.
What do you check before running git apply?
Run from the repository root and inspect the current state first. Git documents that running apply from a subdirectory can ignore paths outside that directory, which is an especially confusing failure mode when a coding agent changes several packages.
git rev-parse --show-toplevel
git rev-parse HEAD
git status --short
git apply --stat /absolute/path/candidate.patch
git apply --summary /absolute/path/candidate.patch
git apply --check /absolute/path/candidate.patch
The stat and summary commands inspect the patch without applying it. Read their output before execution: an unexpected deletion, executable-bit change, or file outside the task scope deserves review even when the text would apply cleanly.
Use the file-scope guard workflow when the task has an explicit path allowlist. Git’s ability to apply a patch is not authorization to modify every path named in it.
A nonzero check result is useful evidence, not an invitation to force application. Save stderr verbatim. A wrong relative path, already-applied change, missing file, and stale hunk can require different next steps. Do not collapse them all into “the AI failed.”
Can you reproduce a stale-patch failure without an AI call?
Yes. This local fixture creates its own temporary repository, commits a base, and builds a patch from a chosen change. It does not touch your project. Run it with Python 3 and Git installed:
from pathlib import Path
import subprocess
import tempfile
def git(root, *args, check=True):
return subprocess.run(
["git", "-C", str(root), *args],
check=check, capture_output=True, text=True,
)
with tempfile.TemporaryDirectory(prefix="patch-preflight-") as folder:
root = Path(folder)
git(root, "init", "-q")
git(root, "config", "user.name", "Local Fixture")
git(root, "config", "user.email", "fixture@example.invalid")
target = root / "config.txt"
base = "mode=old\nlimit=10\nowner=demo\n"
target.write_text(base, encoding="utf-8")
git(root, "add", "config.txt")
git(root, "commit", "-qm", "fixture base")
target.write_text(base.replace("limit=10", "limit=20"), encoding="utf-8")
patch_text = git(root, "diff", "--binary", "--full-index").stdout
patch = root / "candidate.patch"
patch.write_text(patch_text, encoding="utf-8")
target.write_text(base, encoding="utf-8")
clean = git(root, "apply", "--check", str(patch), check=False)
assert clean.returncode == 0, clean.stderr
assert target.read_text() == base
target.write_text("completely different content\n", encoding="utf-8")
stale = git(root, "apply", "--check", str(patch), check=False)
assert stale.returncode != 0
assert target.read_text() == "completely different content\n"
print("clean_check=PASS; stale_check=REJECTED; files_unchanged=PASS")
Expected output from the fixture:
clean_check=PASS; stale_check=REJECTED; files_unchanged=PASS
We ran this on November 8, 2026 with Git 2.47.3 and Python 3.13.5. The stale variant produced patch failed: config.txt:1 and patch does not apply. That is a real local Git result for intentionally constructed data. It is not a benchmark of any coding model’s patch quality.
The fix for this fixture is to check against the correct base content. In a real project, preserve the target’s current work and regenerate the patch from the intended revision, or review a deliberate integration. Replacing the live file with the old base merely to silence Git would discard legitimate edits.
When does —index reject a patch that looks applicable?
An index check also requires the relevant staged and working copies to agree. This stricter condition helps catch a developer or agent changing the same file after staging it.
For a deliberate index-aware preflight, use:
git apply --check --index /absolute/path/candidate.patch
If the working copy differs from the index, the failure may be about that mismatch rather than the patch’s text. Inspect both views with the official git-diff commands:
git diff -- path/to/file
git diff --cached -- path/to/file
Do not automatically stage everything to make the check pass. Staging changes the review boundary. A previously unreviewed edit could then become part of the proposed commit. The staged and untracked review guide explains that boundary in detail.
Plain --check can be appropriate when you intend to apply only to files in an isolated worktree. --check --index is useful when your workflow explicitly wants matching staged and working copies. Choose the mode based on the next action, rather than treating the stricter command as a universal repair.
Where should you apply a patch after the check passes?
Apply it in a separate worktree based on an explicit commit. The official worktree documentation describes separate working directories and indexes with shared repository data. This preserves your current directory’s edits while you investigate integration.
The following names are examples. Choose an unused branch and directory, and inspect existing worktrees first:
git worktree list
git rev-parse HEAD
# Replace BASE_COMMIT with the recorded commit you intend to test.
git worktree add -b patch-trial ../patch-trial BASE_COMMIT
git -C ../patch-trial apply --check /absolute/path/candidate.patch
git -C ../patch-trial apply /absolute/path/candidate.patch
git -C ../patch-trial diff --check
git -C ../patch-trial diff --stat
git -C ../patch-trial status --short
A worktree is directory isolation, not a security sandbox. Tests and install scripts still run with your user permissions and can reach shared resources. Use the project’s normal execution restrictions for code you have not trusted.
Inspect new files as well as tracked diffs. Plain git diff does not show the contents of untracked files. The status manual documents the categories; use it to identify additions that need separate reading before staging explicit paths.
Keep a failed worktree until the failure is understood. Do not remove it with a force option just to make the next attempt look clean. The failure contains information about the patch, base, dependencies, and tests that another model request cannot recover from a vague summary.
Should you try a three-way application or reject files?
Use three-way application only as a deliberate integration experiment. Git requires blob identity information in the patch and the corresponding objects locally. It can leave conflicts, and it implies index behavior unless used with --cached. A text snippet copied from a chat may not carry enough information.
The official apply documentation also explains that --reject changes the failure behavior: applicable hunks may be written while rejected hunks are left for inspection. That is materially different from the default atomic failure behavior. Do not add --reject to an unattended loop and assume the resulting tree represents the complete requested change.
For the first diagnostic, prefer the default check and a complete failure. If you intentionally attempt three-way integration, use the trial worktree, record the command, and stop when conflicts appear. Resolving a conflict requires deciding how both sides should behave; automatically choosing one side hides that decision.
Do not combine a growing collection of whitespace and context overrides until the error disappears. Each override changes what Git accepts. Read the actual mismatch, and use a narrow option only when you understand why the patch and target differ.
How much retry budget should a patch receive?
Give the agent a concrete failure packet before allowing another attempt: base SHA, target SHA, the relevant Git stderr, a small diff of the conflicting area, and the acceptance command. Avoid resending the entire repository when the problem is a stale three-line hunk.
A useful policy is one integration diagnosis followed by one regeneration attempt. That is an editorial workflow recommendation, not a provider usage limit. When a second patch fails for the same reason, pause and fix the handoff instead of increasing model output length.
For hypothetical accounting, three generation attempts at a chosen allowance of 2,000 output tokens each reserve 6,000 output tokens. One attempt reserves 2,000, a difference of 4,000. This is arithmetic on invented planning inputs, not measured savings or current API pricing. Count actual usage and accepted changes with the local cost ledger before claiming financial improvement.
Honest take
Use Git to reject stale integration cheaply, then spend model effort on the smallest unresolved problem. These checks need an ordinary Git checkout and Python for the fixture; no GPU, subscription upgrade, or paid API is required. They cannot prove that a clean patch is safe, complete, or correct. Your acceptance tests and code review still decide whether it should ship.
Sources
Official references checked November 8, 2026:
- Git apply: checking, index modes, and conflict behavior
- Git diff: working tree and index comparisons
- Git worktree: separate working directories
- Git status: tracked and untracked changes
- Git add: explicit staging
- Git rev-parse: repository and revision inspection
Last updated November 8, 2026. Git behavior and AI tool billing can change; verify your installed version and current provider terms before purchasing services.
Was this article helpful?
Thanks for the feedback — it helps improve future articles.
Need hands-on help?
I offer 1-on-1 technical consulting for local AI setup, GPU selection, and AI coding tool configuration — same topics covered on this site.
Book a session — $49 / hour →Know which coding tool is worth paying for
Hands-on comparisons of AI coding assistants and what each one costs to run — including the local-model path. Sent only when something changes. Unsubscribe anytime.