AI patch safety: check target paths before git apply
TL;DR: Inspect every file path in an AI-generated patch before modifying your working tree or index. Combine git apply --numstat -z with a check of rename from and copy from headers so a patch cannot touch files outside your intended directory scope, and only then run git apply --check.
What you’ll be able to do:
- Extract NUL-terminated target paths from a patch using
git apply --numstat -zwithout applying changes. - Catch both outbound edits and inbound renames that pull files from outside an allowed directory prefix.
- Gate
git apply --checkbehind a strict path-scope check using only Git and Python’s standard library.
Honest take:
git apply --checkonly tells you whether hunks fit cleanly; it will happily approve a patch that modifies deployment scripts or configuration outside the folder you asked the AI agent to edit.
Why is git apply --check not enough for AI-generated patches?
When you ask an AI coding assistant to fix a bug in one module—for example, src/api/—the returned unified diff can include changes you never authorized. Coding agents frequently “fix” a failing test or type check by editing shared configuration files, changing CI scripts under infra/, or renaming files across package boundaries.
Running git apply --check verifies that the patch applies cleanly to the target files, as documented in the official git-apply manual checked November 14, 2026. However, clean applicability says nothing about which paths the patch touches. If infra/deploy.sh matches the patch context, git apply --check exits with status 0.
Enforcing a path boundary before applicability checking solves that problem locally. Using Git 2.47.3 and Python’s standard library requires no paid review API, no extra model prompt, and no GPU. It does not prove that the code inside the allowed directory is bug-free, and it does not measure token or billing savings.
How do Git’s patch-inspection flags compare?
git apply includes several options that turn off actual file modification and report what a patch would touch. Each flag exposes different details about the patch.
| Inspection method | Modifies files or index? | Handles unusual characters without quoting? | Shows rename/copy source paths? | Primary role in preflight |
|---|---|---|---|---|
git apply --numstat -z | No (--numstat turns off apply) | Yes (NUL-terminated paths) | No (lists destination path only) | Machine-readable list of destination paths |
git apply --summary | No (--summary turns off apply) | No (human-formatted text) | Yes (prints rename old => new) | Human review of creations, deletions, modes, and renames |
rename from / copy from header scan | No | Raw header bytes | Yes (explicit extended diff headers) | Captures source paths that --numstat -z omits |
git apply --check | No (--check turns off apply) | N/A | N/A | Confirms hunks apply cleanly after scope passes |
Notice the subtle behavior of git apply --numstat -z on rename patches. In our local verification with Git 2.47.3, a Git diff that renames infra/deploy.sh to src/api/deploy.sh with 100% similarity produces this --numstat -z output:
0 0 src/api/deploy.sh\0
Because git apply --numstat -z emits only the destination path (src/api/deploy.sh), a wrapper that checks --numstat -z alone would conclude that every path lies inside src/api/—even though applying the patch deletes infra/deploy.sh from outside the allowed directory! Pairing --numstat -z with a scan for rename from and copy from headers closes that gap.
What about git apply --include or running from a subdirectory?
The git-apply manual documents two built-in scoping mechanisms that look tempting at first glance but behave dangerously in automated AI workflows:
- Running from a subdirectory: The manual notes that when running
git applyfrom a subdirectory inside a repository, patched paths outside that directory are ignored. Silent partial application is dangerous: if an AI patch changes bothsrc/api/handler.pyand a shared schema outsidesrc/api/, ignoring half the patch leaves your working tree in an inconsistent state without raising an error. - Using
--include=<path-pattern>: Passing--include=src/api/*tells Git to apply changes matching the pattern and ignore non-matching paths. Again, silently dropping out-of-scope hunks hides the fact that the agent attempted to modify unauthorized files.
For an automated preflight gate, you want all-or-nothing rejection: if any path in the patch falls outside the authorized prefix, reject the entire patch before touching a single file.
How do you build a path-scope and applicability gate in Python?
The script below runs git apply --numstat -z to parse destination paths without quoting issues, inspects the patch for rename from and copy from headers, verifies every path against an allowed POSIX directory prefix using Python’s pathlib.PurePosixPath, and runs git apply --check only when every path is in scope.
Save this as check_patch_scope.py:
import json
from pathlib import Path, PurePosixPath
import subprocess
import sys
def parse_numstat_z(raw_bytes):
tokens = raw_bytes.split(b"\0")
if tokens and tokens[-1] == b"":
tokens.pop()
paths = []
for raw in tokens:
entry = raw.decode("utf-8", errors="surrogateescape")
parts = entry.split("\t", 2)
if len(parts) != 3 or not parts[2]:
raise ValueError("unexpected numstat record: " + entry)
paths.append(parts[2])
return paths
def parse_header_sources(patch_path):
sources = []
with Path(patch_path).open("rb") as handle:
for raw_line in handle:
for prefix in (b"rename from ", b"copy from "):
if raw_line.startswith(prefix):
value = raw_line[len(prefix):].rstrip(b"\r\n")
sources.append(value.decode("utf-8", errors="surrogateescape"))
return sources
def within_prefix(rel_path, allowed_prefix):
candidate = PurePosixPath(rel_path)
prefix = PurePosixPath(allowed_prefix)
if not rel_path or candidate.is_absolute() or ".." in candidate.parts:
return False
return candidate == prefix or prefix in candidate.parents
def check_patch_scope(repo, patch_file, allowed_prefix):
stat_proc = subprocess.run(
["git", "-C", str(repo), "apply", "--numstat", "-z", "--", str(patch_file)],
stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=False,
)
if stat_proc.returncode != 0:
raise RuntimeError(
"git apply --numstat failed: "
+ stat_proc.stderr.decode("utf-8", errors="replace").strip()
)
paths = parse_numstat_z(stat_proc.stdout)
for src in parse_header_sources(patch_file):
if src not in paths:
paths.append(src)
if not paths:
return {"status": "EMPTY_PATCH", "paths": [], "outside": []}
outside = [p for p in paths if not within_prefix(p, allowed_prefix)]
if outside:
return {"status": "OUT_OF_SCOPE_PATHS", "paths": paths, "outside": outside}
check_proc = subprocess.run(
["git", "-C", str(repo), "apply", "--check", "--", str(patch_file)],
stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=False,
)
if check_proc.returncode != 0:
return {
"status": "APPLY_CHECK_FAILED",
"paths": paths,
"outside": [],
"error": check_proc.stderr.decode("utf-8", errors="replace").strip(),
}
return {"status": "SCOPE_AND_CHECK_OK", "paths": paths, "outside": []}
if __name__ == "__main__":
print(json.dumps(check_patch_scope(sys.argv[1], sys.argv[2], sys.argv[3])))
Run the script from your terminal by passing the repository root, the candidate patch file, and the allowed relative directory prefix:
python3 check_patch_scope.py /path/to/repo /private/review/candidate.patch src/api
Key safeguards built into this helper:
- No silent partial apply: Neither
--numstatnor--checkmodifies the working tree or index. Ifoutsideis non-empty, the script returnsOUT_OF_SCOPE_PATHSimmediately and never invokes--checkor applies changes. - Traversal and absolute-path rejection:
within_prefix()usesPurePosixPathto reject empty strings, absolute paths, and any path containing..segments before checking whetherallowed_prefixis equal to or a parent of the candidate path. - Explicit option termination: Both Git invocations pass
--before the patch path so a patch filename starting with-cannot be interpreted as an extragit applyflag. For capturing diffs and handling subprocess exit codes earlier in the pipeline, see our Git diff exit-code pipeline guide.
What did the Git 2.47.3 fixture tests prove?
We tested check_patch_scope.py on November 14, 2026 against a disposable Git 2.47.3 repository containing two tracked files: src/api/handler.py (inside the allowed src/api prefix) and infra/deploy.sh (outside the allowed prefix).
For the valid in-scope fixture (patch-in-scope.patch), where only src/api/handler.py changed from return 200 to return 201, the helper returned:
{"status": "SCOPE_AND_CHECK_OK", "paths": ["src/api/handler.py"], "outside": []}
We then executed three failure fixtures against the same repository to verify each rejection gate:
| Local fixture | Patch contents | Observed status | outside array |
|---|---|---|---|
| Clean in-scope edit | Modifies src/api/handler.py only | SCOPE_AND_CHECK_OK | [] |
| Multi-file out-of-scope edit | Modifies src/api/handler.py and infra/deploy.sh | OUT_OF_SCOPE_PATHS | ["infra/deploy.sh"] |
| Inbound rename from outside scope | git mv infra/deploy.sh src/api/deploy.sh (diff --cached -M) | OUT_OF_SCOPE_PATHS | ["infra/deploy.sh"] |
| Stale in-scope patch after base commit changes | Modifies src/api/handler.py against a diverged commit | APPLY_CHECK_FAILED | [] (includes Git stderr) |
The inbound rename test highlights why header inspection matters: git apply --numstat -z reported only src/api/deploy.sh, while parse_header_sources() extracted infra/deploy.sh from the rename from infra/deploy.sh extended header and blocked the patch.
How does path scoping fit into a complete patch workflow?
Treat path scoping as one layer in a sequence of deterministic local checks before running tests or asking a model for a retry:
- Verify repository state first: Check
git status --shortandgit rev-parse HEADso you know the exact base commit. If a diff or patch includes unexpected CRLF or whitespace noise rather than wrong files, use the CRLF and line-ending diff budget guide. - Run
check_patch_scope.py: Confirm that the patch touches only the paths you authorized for the task and passesgit apply --check. - Inspect binary and submodule side effects: Remember that
git apply --numstatreports- -for binary changes. Pair this gate with the binary files and submodule diff inventory guide and the pre-retrygit applycheck guide. - Apply in a disposable worktree and run real tests: Once scope and applicability pass, apply the patch in an isolated worktree and run your project’s test suite.
When an agent works across multiple tasks at the same time, combine this path-scope check with isolated worktrees so one task’s staged or unstaged edits cannot pollute another task’s patch check; see the Git worktrees two-task budget guide.
If you run local coding models via Ollama to generate or review these patches, verify how loaded models report active VRAM versus disk footprint with the Ollama /api/ps memory reporting guide on RunAIHome, and validate local checkpoint headers before loading weights with the Safetensors header check on AIFoss.
Honest take: what are the limits of this scope check?
Path-prefix validation protects directory boundaries, not semantic security inside the allowed folder. If src/api/ itself contains authentication middleware or security-critical configuration, an in-scope patch can still introduce a vulnerability while passing SCOPE_AND_CHECK_OK.
Additionally, this helper checks unified diffs processed by git apply inside an existing repository. It does not sandbox arbitrary shell commands executed by an autonomous agent, and it does not resolve symlinks that already exist inside the allowed directory tree. If your repository tracks symlinks inside src/api/ that point elsewhere, inspect git ls-files -s (mode 120000) separately before applying untrusted patches.
Use this script to enforce a crisp contract: when you ask an AI tool to edit one directory, verify that its patch stays inside that directory before touching your codebase.
Sources
git-applymanual (--numstat,-z,--summary,--check,--include) — Gitgit-diffextended header format (rename from,copy from) — Gitgit-statusmanual — Gitpathlib.PurePosixPathreference — Python 3 Documentationsubprocess.runreference — Python 3 Documentation
Last updated November 14, 2026. Official Git and Python documentation and local Git 2.47.3 fixtures were checked on this date. These checks validate patch path scoping and applicability only, not AI model quality or cost reductions.
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.