Skip to content

Agent falls back to write_file after str_replace failure, causing code corruption #20799

@Stanley-blik

Description

@Stanley-blik

What happened?

When the agent attempts to use the str_replace tool to edit a file, and the target string appears more than once in the file, the tool correctly throws an error. However, instead of stopping or asking for clarification, the agent silently falls back to using write_file to rewrite the entire file — often with incorrect or incomplete content, breaking the codebase.

What did you expect to happen?

When str_replace fails due to multiple occurrences of the target string, the agent should:

Surface the error and ask the user to provide more context or a more unique target string
Not attempt a full file rewrite as a fallback

Client information

Client Information

Run gemini to enter the interactive CLI, then run the /about command.

> /about


╭──────────────────────────────────────────────────────────────────────────╮
│                                                                          │
│ About Gemini CLI                                                         │
│                                                                          │
│ CLI Version              0.31.0                                          │
│ Git Commit               72c653354                                       │
│ Model                    Auto (Gemini 3)                                 │
│ Sandbox                  no sandbox                                      │
│ OS                       win32                                           │
│ Auth Method             Logged in with Google                            │
│                         (stanleyisaac134@gmail.com)                      │
│ Tier                     Gemini Code Assist in Google One AI Pro         │
│                                                                          │
╰──────────────────────────────────────────────────────────────────────────╯


Login information

I authenticated using my Google Account.

Anything else we need to know?

Steps to Reproduce

  • Have a file where a particular string (e.g. a function name, a variable, or a block of code) appears more than once
  • Ask the agent to make a targeted edit that involves one of those repeated strings
  • Agent calls str_replace → fails with a "multiple occurrences" error
  • Agent proceeds to call write_file with a full rewrite of the file
    -File is now broken or missing logic

Metadata

Metadata

Assignees

No one assigned

    Labels

    Stalearea/agentIssues related to Core Agent, Tools, Memory, Sub-Agents, Hooks, Agent Qualitystatus/need-triageIssues that need to be triaged by the triage automation.

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions