Codex Patch Conflicts With Existing Code

Codex fails with "Invalid Context" or "No such file or directory" when applying a patch. Tell the two apart, then refresh state or restart the session.

Codex tries to edit a file and the apply_patch step fails. You see one of two very different errors, and the fix depends on which:

  • apply_patch verification failed: Invalid Context (often printed as Error: Invalid Context: followed by an @@ line) — the patch’s surrounding context lines no longer match the file. This is genuine state drift.
  • Failed to apply patch ... No such file or directory / execution error: Io(Os { code: 2, kind: NotFound }) — the file is fine; the Codex CLI runtime lost its path to the apply_patch helper. This is a known CLI bug (0.117–0.120, as of June 2026), not a conflict at all.

Fastest fix (Invalid Context): stop, re-read the current file, regenerate the patch. Fastest fix (No such file or directory): restart the Codex session — do not touch your code.

The rest of this page tells you which bucket you’re in and how to keep it from recurring.

How Codex patches differ from git apply

This matters because the usual “line numbers are off” intuition is wrong here. Codex CLI does not emit unified diffs with line numbers — it uses OpenAI’s V4A format through the apply_patch tool. A V4A hunk is context-anchored: it locates the edit by matching three lines of surrounding code (and optional @@ class/function headers), not by line number. Format looks like:

*** Begin Patch
*** Update File: src/utils.ts
@@ export function parse(input) {
   const trimmed = input.trim();
-  return JSON.parse(trimmed);
+  return JSON.parse(trimmed || "{}");
 }
*** End Patch

Because anchoring is by context, off-by-a-few line numbers don’t break it — but any change to those 3 context lines does. That’s why a reformat or a stray edit is so destructive: it rewrites the very lines Codex was matching against. The CLI then reports Invalid Context and refuses to guess. (Spec: openai/codex apply_patch instructions.)

First: which error are you seeing?

Error stringBucketFastest fix
Invalid Context / Error: Invalid Context: / Failed to find context '...' in <file>Context drift (file changed)Re-read file, regenerate patch
No such file or directory / Io(Os { code: 2, kind: NotFound }) after the patch was approvedCLI runtime path bugRestart the Codex session
Update hunk does not contain any lines / parse errorMalformed patch from the modelRe-ask for a full hunk
<<<<<<< markers left in the fileA git merge ran, not CodexResolve the git merge, then re-run Codex

If you’re in the runtime path bug row, skip straight to The “No such file or directory” runtime bug — none of the state-drift steps apply.

Common causes (context-drift bucket)

Ordered by hit rate, highest first. These all produce Invalid Context.

1. File changed between Codex’s read and the patch apply

Codex read utils.ts 30 seconds ago. You then formatted the file in your editor (Prettier on save). The context lines in the patch no longer match.

How to spot it: git status shows the file modified more recently than you expected, or git diff src/utils.ts reveals changes you didn’t intend.

2. Auto-formatter ran after Codex read, before the patch apply

VS Code’s “format on save” is the silent culprit. You glanced at the file (which triggered nothing), but Prettier reformatted on a focus-change save. Codex’s context anchors now differ by whitespace or wrapping.

How to spot it: Disable format-on-save ("editor.formatOnSave": false), have Codex re-read + regenerate. If it now applies, format-on-save was it.

3. Whitespace / line-ending mismatch (CRLF vs LF)

Repo cloned on Windows with core.autocrlf=true produces CRLF locally; Codex’s context lines are LF. Every line differs by an invisible carriage return, so the context never matches.

How to spot it: git config core.autocrlf shows true. Or file src/utils.ts reports CRLF line terminators.

4. Codex’s read was from a different commit than the apply target

You started the session on feature/billing, switched to main while Codex was thinking, then asked it to apply. The patch’s context belongs to the old branch; the new branch doesn’t have those lines.

How to spot it: git log --oneline -5 on both branches. If they diverge before the file Codex read, the patch targets a different past.

5. Two agents (or agent + you) edited the file in parallel

Claude Code and Codex were both told to update utils.ts. One finished first; the other’s patch is anchored to the pre-edit state and now conflicts.

How to spot it: git log src/utils.ts --oneline shows recent commits you didn’t make, or git status shows uncommitted surprises. Coordination failure.

6. Codex generated a fuzzy / abbreviated patch

The model occasionally emits hunks with // ... placeholders or only one line of context instead of three. The V4A parser then can’t uniquely locate the edit (Update hunk does not contain any lines, or a silently wrong match).

How to spot it: The patch text contains literal // ... or ... (unchanged) markers, or each hunk has under three context lines. Ask for full hunks.

Shortest path to fix (context-drift bucket)

Ordered by ROI. Step 1 alone fixes most Invalid Context failures.

Step 1: Stop, check current state, regenerate

When you see Invalid Context:

# 1. See actual state
git status
git diff src/utils.ts

# 2. If the working tree is dirty with surprises, find the source
git log --oneline -5 src/utils.ts

Then prompt Codex:

The patch failed with "Invalid Context". Re-read src/utils.ts from disk
right now, then regenerate the patch against the current contents.

Do not force-apply a stale patch. Codex re-reading the file is the official recovery path — the apply_patch tooling is designed to surface a clear failure precisely so the model can re-read and retry.

Step 2: Disable auto-format during agent sessions

VS Code settings:

{
  "editor.formatOnSave": false,
  "editor.formatOnPaste": false,
  "editor.codeActionsOnSave": {}
}

Or per-workspace .vscode/settings.json. Re-enable after the agent finishes (and run your formatter once to normalize).

Step 3: Normalize line endings repo-wide

In .gitattributes:

* text=auto eol=lf
*.bat text eol=crlf
*.png binary
*.jpg binary

Then renormalize the existing checkout:

git add --renormalize .
git commit -m "Normalize line endings to LF"

Now everyone’s working tree is LF and Codex’s context lines match. For Windows devs, set git config --global core.autocrlf input (not true).

Step 4: Commit before agent runs, agent commits before next runs

Single-agent discipline:

1. git status clean before starting the agent.
2. Agent edits + tests.
3. git add -A && git commit -m "agent: <task>" before starting the next session.

For multi-agent workflows, treat shared files as exclusive — only one agent touches each file at a time, coordinated via the task tracker or a CODEOWNERS-style claim.

Step 5: Force full-hunk patches, not elided ones

In the prompt:

Return the full patch text — every changed line plus 3 lines of real
context above and below each hunk. Do NOT use `// ...` placeholders,
`// (unchanged)` markers, or fewer than 3 context lines.

Three context lines is the V4A default; demanding it back prevents the under-anchored patches that match the wrong spot or fail to parse.

Step 6: For persistent conflicts, split the patch

If a single large patch keeps failing, split into smaller atomic patches:

Don't generate one big patch. Instead:
1. Add the new validate() method — return that patch.
2. After I apply, update the call sites — return that patch.
3. After I apply, update the tests — return that patch.

Each patch should touch at most 3 files.

Smaller patches have a smaller blast radius and recover faster when something drifts under them.

The “No such file or directory” runtime bug

If the patch was already approved and then failed with No such file or directory, execution error: Io(Os { code: 2, kind: NotFound }), or bwrap: Can't mkdir ...: No such file or directory, this is not a code conflict. It’s a known Codex CLI runtime regression (reported across 0.117–0.120, as of June 2026): the CLI caches a stale path to its apply_patch helper (under ~/.codex/tmp/arg0) and loses it mid-session, so a patch that applied a minute ago now hits ENOENT.

How to recover, in order:

  1. Restart the Codex session. Quit and relaunch codex; the helper path is re-resolved and the same patch applies. This clears it for most people.
  2. Update the CLI: npm install -g @openai/codex@latest (or brew upgrade codex). Fixes have shipped in newer releases, so don’t fight a bug that’s already patched.
  3. On Windows, large patches can also fail because the patch body is passed via argv and overruns the command-line length limit. Split the change into smaller hunks (Step 6 above), or run Codex inside WSL2.

Track the live status on the issue tracker: openai/codex issues.

How to confirm it’s fixed

After re-running, verify the edit actually landed:

git diff src/utils.ts          # the change you asked for is present
git status                     # no stray <<<<<<< markers, no surprise files
npm test                       # or your project's test command

If git diff shows the intended change and tests pass, the patch applied cleanly. If you still see <<<<<<< markers, that’s a leftover git merge conflict — resolve it manually, commit, then re-run Codex against the clean state.

FAQ

Why does Codex say the diff is correct but git says the file is different? Both are right. Codex’s V4A patch is anchored to the file as it read it; the file on disk changed afterward (a formatter, a branch switch, or another agent). The patch isn’t wrong — it’s stale. Re-read and regenerate.

Is Invalid Context the same as a git merge conflict? No. Invalid Context comes from Codex’s apply_patch failing to find its anchor lines and is fixed by regenerating the patch. <<<<<<< markers come from git merge/git rebase and must be resolved in the file by hand.

Patches keep failing right after they were approved — is my repo corrupted? Almost certainly not. If the error is No such file or directory after approval, it’s the CLI’s stale-path runtime bug. Restart the Codex session and/or update to the latest version; your code is untouched.

Does turning off format-on-save really matter? Yes, more than for git apply. Because V4A matches three lines of context exactly, a reformat that re-wraps or re-indents those lines breaks the anchor even though the code is logically identical. Disable it during agent sessions and format once at the end.

How do I stop two agents from clobbering each other’s patches? Treat each file as exclusively owned for the duration of a task: one agent edits it, commits, then the next agent reads. Coordinate ownership through commits or a CODEOWNERS-style claim — parallel edits to the same file are the surest way to produce Invalid Context.

Prevention

  • Normalize line endings via .gitattributes (* text=auto eol=lf) once and forget it.
  • Disable editor.formatOnSave during agent sessions; format once at the end as a deliberate step.
  • Treat shared files as exclusive — one agent at a time, coordinated through commits.
  • Always demand full-hunk patches with three real context lines; under-anchored patches cause more conflicts than they save tokens.
  • Commit before every agent run and after; clean state in, clean state out.
  • Keep the Codex CLI updated so you’re not hitting an already-fixed runtime bug.
  • For large refactors, split into a chain of small patches rather than one mega-patch.

Tags: #Codex #Coding agent #Troubleshooting #Debug #Patch conflicts