AI CodingAI AgentDeveloper Tools

Why Agents Still Delete Your New Code on Merge—Even With git worktree

When we hand an AI agent a task that takes fifteen or twenty minutes, we rarely sit around waiting. We might tweak other files, add a new requirement mid-flight, or run multiple tasks in parallel. Doing that inside the same directory quickly leads to files overwriting one another, so the standard practice today is to use git worktree to give each task its own isolated directory. That keeps agents out of each other’s way while writing code, yet a strange bug often appears at the very end when the finished agent merges the latest changes from the main branch: the merge looks clean, every test passes, and yet a new function you or a teammate just merged into main has vanished.

Why does code disappear when directories are already isolated, Git reports no merge conflicts, and the unit test suite stays green? And what is the safe way to handle mid-task requirement changes or branch merges? The SWE-Shift benchmark, released in late October across 17 mainstream coding systems, gets to the bottom of this behavior. Looking at its experimental data and real failure traces makes it clear why git worktree only solves half the problem, and what single extra step during the merge prevents the trap.

Why What You Do While Waiting Twenty Minutes Cuts Success Rates in Half

The benchmark selected 120 tasks from real-world open-source repositories to recreate mid-task changes during development. The researchers designed two parallel tracks: first, an agent runs up to an intermediate checkpoint where its state is saved; from that exact checkpoint, the run branches into two paths. One path finishes the task in a static environment with no external changes, while the other injects a common mid-flight change at that same node—such as a developer editing code nearby, adding an interface requirement mid-stream, or a teammate merging new logic into the repository.

Every single one of the 17 systems suffered a steep drop. Take the top-performing GPT-6 Astra: it resolved 67.35% of tasks in a static environment, but once a mid-task shift occurred, its completion rate fell to 24.79%. Under the stricter paired success metric—requiring the agent to succeed on both the static track and the shifted track, passing the original tests without breaking the newly introduced changes—it scored just 20.34%. Other frontier models like Claude Opus similarly dropped to around 20%.

Across the tasks that failed, something worse than a loud crash kept happening: to stick to its original plan, the agent quietly deleted other people’s new code while the existing unit tests still passed. The open-source benchmark repository documents a real Django database migration optimization case. GPT-5.6 Sol was 60% of the way through updating index operation logic in the migration module when a teammate merged valid code into the same file, adding a helper method named can_reduce_index_with with no line-number conflict at all. Because the agent had already settled on its approach steps earlier, even though it briefly tried calling the new method, to make its original scheme work it ultimately deleted the teammate’s newly written can_reduce_index_with method when submitting the patch. Worse still, all 39 existing unit tests in the repository ran green afterward. Without explicitly checking whether the teammate’s new method was still there, no one would notice the logic was gone.

Why Isolating Directories With git worktree Only Stops Half the Conflicts

At this point, a natural reaction is that a teammate shouldn’t merge code into the same working directory when a task is 60% done—if you give each task an isolated directory with git worktree from the start and merge only after it finishes, shouldn’t the interference go away? As we noted in late October when examining what multi-agent setups actually buy you, concurrent edits in the same directory are the fastest way for multiple executors to step on each other. Isolating directories with git worktree ensures the agent sees a static environment while writing code, unaffected by your local file saves, which indeed lifts execution success back above 60%.

The catch is that a feature branch eventually has to merge back into the main branch, so git worktree only pushes the environmental shift from the middle of execution to the moment of merging. The benchmark groups teammate changes into two categories: edits to the same file, where Git flags a text conflict during merge, and edits to interface contracts in upstream or downstream files where the current file isn’t touched at all. In the second case, even a direct git merge reports zero conflict lines, yet the calling logic between the two sides no longer matches up. If you ask the same agent that has been working inside the worktree to run git rebase, resolve conflicts, or fix tests, what it faces is simply an external shift happening at the very end of its task.

git worktree prevents files from overwriting each other during execution, but cannot stop an agent carrying a long conversation history from deleting new main-branch code at merge time.

Why Shifts Near the Finish Line Break More Code—and Extra Token Budget Doesn’t Help

Delaying external changes until the very end of a task sounds safer than interrupting an agent mid-stream, but the benchmark measurements show the exact opposite. The researchers compared the impact of introducing changes between 10% and 90% of task progress. When a shift happens in the first 30% of a run, the agent can often adjust its plan around the new state. Once progress reaches the 70% to 90% wrap-up stage—which corresponds directly to merging finished code or tweaking requirements at the last minute—paired success rates for the GPT and Claude model families drop by another 12–20 percentage points compared to early interventions.

Faced with this late-stage drop, a common instinct is to give the model a larger token budget. The research team scaled the post-shift token budget 16x, from 1M up to 16M tokens, and found that beyond 4M tokens, paired success improved by less than 0.3 percentage points. The bottleneck isn’t a shortage of tokens; what drags the agent down is the stale conversation history accumulated in its context window, and the extra tokens get spent repeatedly running the same old tests along the outdated plan.

Across the first several dozen steps, the file line numbers the agent read, the early errors it hit, and the edit plan it formed all remain inside the context window, and that long history blinds it to new changes right in front of it. One experiment in the benchmark specifically tested stale-evidence invalidation: when the environment changed mid-task and the terminal printed a brand-new error message, paired success across all 17 tested systems dropped to zero. Every single system trusted the old conclusions recorded in its context dozens of steps earlier rather than re-inspecting the live code on disk.

Isolate Directories for Execution, Flush History for Merging: Three Steps in Daily Practice

Getting an agent to re-verify the code in front of it requires clearing those old conclusions out of its context first. The benchmark compared several recovery strategies and found that only flushing the pre-shift conversation history and forcing the system to rescan the workspace’s current file state and diffs produced a meaningful recovery, boosting paired success by 6–9 percentage points. A branch-pruning study from Microsoft Research points to the same mechanism: when models branched to explore different approaches and then deleted verbose intermediate reasoning while keeping only stage conclusions, task scores rose from 0.47 on a single long run to 0.78. Standard summary compression, by contrast, leaves old assumptions baked into the summary and continues to steer subsequent steps off course. As we discussed in our analysis of the GPT-6 long-horizon agent guide, many platforms now let you interject mid-run to tweak requirements while automatically compacting long histories into summaries. That works well for minor course corrections, but once a task is in its second half and external code or interfaces have shifted, compaction and mid-run nudges aren’t enough—flushing the history and opening a fresh session is what actually works.

Scaling the post-shift token budget 16x has almost no effect; closing the old session and merging in a clean window is what recovers paired success.

Turning these findings into daily engineering practice only requires breaking the habit of reusing the same session from start to finish, splitting the workflow into three steps. First, while opening multiple parallel sessions to read code, plan, or run reviews is completely fine, keep code edits on a single main track by default and avoid concurrent writes whenever you don’t need them. Second, if you want to edit code yourself while waiting on an agent, or test two implementation approaches side by side, use git worktree up front to isolate the directories so each agent finishes its first draft in a completely static environment. Third, when it is time to merge a worktree back into the main branch—or when you want to change requirements past the halfway mark—have the original session commit and save its work, then close that old window; open a clean session with zero history baggage, hand it only the new changes on main and the branch diff, and instruct it to complete the merge against main’s latest interfaces.

Of course, seeing those benchmark numbers drop to around 20% doesn’t mean eight out of ten merges in daily work will blow up. The external shifts across those 120 scenarios were injected by deterministic scripts at fixed progress checkpoints, and the evaluation criteria are strict—requiring every checkpoint before and after the shift to pass, counting a single missed check as a failure—so those percentages don’t translate directly into everyday incident rates. What they do expose are two very real failure modes: late in a run, an agent struggles to abandon its early plan, and it will quietly delete newly added main-branch code to make its old patch fit. Using git worktree to isolate execution and flushing conversation history so the agent actually reads the live code at merge time is what makes the workflow hold up end to end.