Dashboard

Stop an AI Coding Agent From Reformatting Whole Files

An AI coding agent asked to fix one bug can return a diff that touches the whole file. Here is the scoping instruction, and a before/after diff, that keeps it to just the lines that changed.

Steve Jefferson
Steve Jefferson
Developer Advocate
13 September 20261 min read

Stop an AI Coding Agent From Reformatting Whole Files

You ask an AI coding agent to fix one bug. It comes back with a diff that touches 180 lines across a file that used to need eight. The quotes changed from single to double. The imports got re-sorted. Two functions got re-indented for no reason you can name. Somewhere in that noise is your actual fix, and you now have to review the whole file to find it. The fastest way to stop an AI coding agent from reformatting your whole file is to give it an explicit line-scope rule, separate from any file-level instruction, that treats every line it did not need to change as off limits.

Why the agent reformats code you never touched

This is not a bug in the model, it is a side effect of how these agents are trained and how they read a file. Most coding agents are optimized to produce code that looks internally consistent. When they open a file to fix one function, they see quote style, indentation, or import order that does not match their default preferences, and they "fix" it along the way because nothing in the prompt told them that consistency is not the goal this time. A few other things make it worse.

  • Some tools run a formatter automatically on every file they save, not just the lines they edited.

  • The model has no concept of "your" diff unless you give it one. Left alone, it optimizes for the file as a whole, not the change you asked for.

  • Vague instructions like "clean this up while you're in there" get interpreted as a license to touch anything nearby.

  • Long context windows mean the agent reads the entire file before writing, which makes it more likely to notice and act on unrelated style issues.

What an unscoped diff actually costs you

A 200-line diff for a one-line fix is not just annoying to read. It has real downstream costs on a team that reviews code before merging it.

  • Reviewers cannot tell what actually changed, so they either rubber-stamp it or spend twenty minutes finding the real edit inside the noise.

  • git blame stops being useful on that file, because every line now points at a reformat commit instead of the commit that actually introduced it.

  • Merge conflicts multiply, since anyone else with an open branch touching that file now collides with lines they never meant to touch.

  • Diff-based CI checks (coverage deltas, lint-on-changed-lines, size limits) trigger on lines that carry no real risk, which trains the team to ignore the warnings.

The scoping instruction that stops an AI coding agent from reformatting your whole file

General advice like "be careful" or "don't break anything" does not work, because it gives the agent no concrete boundary to check itself against. What works is a rule that defines scope at the line level, not just the file level, and tells the agent what to do with opinions it is not allowed to act on. Use this as a system instruction, a repo-level agent config file, or a prompt prefix you paste at the start of a task:

SCOPE RULES FOR THIS TASK
1. You may edit only the files listed below. Do not create, delete, rename, or modify
   any file not on this list, even if you believe it needs the same fix:
   - src/billing/invoice.py
2. Within an allowed file, change only the lines required to implement the described
   fix or feature. Do not reformat, reindent, reorder imports, rename variables, or
   change quote/string style on any line you are not otherwise editing for a functional
   reason.
3. Do not run a formatter, linter --fix, or "clean up" pass across the whole file.
   If the file has a formatter configured, apply it only to the lines you changed.
4. If you notice an unrelated issue (style, naming, a possible bug elsewhere), do not
   fix it. Describe it in your final response as a separate suggestion instead.
5. Before finishing, check your own diff. If a line appears in the diff and its meaning
   did not change, revert that line back to the original.

The two clauses doing most of the work are 3 and 5. Clause 3 stops the agent from invoking a formatter as a reflex. Clause 5 gives it a concrete self-check: read your own diff, and if a line's meaning is unchanged, put it back. Agents are reasonably good at following a mechanical check like that when it is spelled out; they are much worse at inferring it from a vague request to "keep the diff small."

Before and after: the same fix, two different diffs

Here is what an unscoped request produces. The task was: "the discount is being applied twice, fix it."

-def calculate_total(items, discount_pct):
-    subtotal = sum([i['price'] * i['qty'] for i in items])
-    discount = subtotal * discount_pct
-    total = subtotal - discount
-    total = total - discount  # applying it again by mistake
-    return total
+def calculate_total(items: list[dict], discount_pct: float) -> float:
+    """Calculate the order total after discount."""
+    subtotal = sum(item["price"] * item["qty"] for item in items)
+    discount = subtotal * discount_pct
+    return subtotal - discount

... plus 40 more re-flowed lines elsewhere in the same file where the agent
switched every single quote to a double quote and re-sorted the imports.

Here is the same fix under the scope rules above. Same bug, same file, same agent, different instructions:

 def calculate_total(items, discount_pct):
     subtotal = sum([i['price'] * i['qty'] for i in items])
     discount = subtotal * discount_pct
     total = subtotal - discount
-    total = total - discount  # applying it again by mistake
     return total

Five lines instead of forty-something, and every line in the diff is there because the fix required it. A reviewer can approve that in the time it takes to read one sentence. The type hints, the docstring, and the quote-style change the agent wanted to make are not wrong ideas, they are just a different task, and the rule above tells the agent to say so instead of doing it.

Where to put this instruction so it actually sticks

Where you put the rule matters more than how cleverly you word it. A one-off instruction typed into a single prompt gets forgotten two turns later in a long session; a rule saved at the project level survives the whole task. Most current coding agents read a persistent instructions file at the root of the repo, so that is the first place to put this. If you also need to keep the agent out of entire files, not just unrelated lines inside a file it is already touching, combine this with a file-level allowlist along the lines described in restricting an AI coding agent's file system access, which is the file-boundary version of the same problem.

  • Put the scope rule in your project's persistent agent instructions file, not just in the chat prompt, so it applies to every task in that repo.

  • For a specific high-risk task, repeat the file list and the "revert unchanged lines" check directly in the task prompt as a reminder.

  • If your team uses a shared config for multiple agents or tools, keep the wording tool-agnostic (avoid vendor-specific flags) so it holds up across whichever agent someone runs.

  • Test the instruction by asking for a trivial one-line fix and counting the lines in the resulting diff. If it is more than a handful, the scope rule is not being honored and needs to be stated more directly, closer to the top of the instructions.

When a full reformat is actually the right call

None of this means an agent should never reformat a file. Sometimes that is exactly the job: you are migrating a codebase to a new style guide, adopting a formatter for the first time, or cleaning up a file nobody has touched in two years before a bigger rewrite. The fix is not to ban reformatting, it is to make it its own explicit task with its own commit, separate from any functional change. Ask for the reformat by itself, review that diff on its own terms, merge it, and only then hand the agent the next task that touches actual logic. Mixing the two in one diff is what causes the problem, not reformatting itself.

A line-scope rule solves the within-file version of a broader pattern: agents default to doing more than you asked unless you draw the boundary yourself. The closest relative is the file-boundary problem covered in stopping an AI coding agent from editing unrelated files, which is worth pairing with the rule above so an agent is constrained on both axes, which files it can touch and which lines inside them. If you are handing an agent larger, multi-file work, getting an agent to write smaller, more reviewable pull requests extends the same idea from a single diff to an entire change set. And before you merge anything an agent produced, whether scoped or not, it is worth prompting a second AI pass to review the code before you ship it as a cheap second check on top of your own read.

If you are still choosing which coding tool to standardize on, how well each one respects a scoping instruction like this is worth testing directly rather than taking on faith. Our broader guide to picking the right AI coding tool covers the tradeoffs beyond just diff scope.

Frequently asked questions

Why does my AI coding agent reformat the whole file when I only asked for one fix?

Because nothing in your prompt told it not to. Most agents are trained to produce internally consistent code, so when they see a mismatch in style while reading the file, they treat fixing it as part of doing a good job unless you explicitly scope the task to the lines that matter.

Will telling an agent not to reformat cause it to miss real style violations?

No, it changes what happens when it notices one. Under a scope rule, the agent still sees the issue, it just reports it in its response instead of silently fixing it. You keep the visibility without the unreviewable diff.

Does this still work if my editor runs a formatter automatically on save?

It needs an extra line. Add an explicit instruction that any format-on-save behavior should apply only to the lines the agent changed, or disable format-on-save for agent sessions and run the formatter manually, scoped to the diff, before you commit.

What if the fix legitimately requires touching many lines?

Then the diff should be large, and that is fine, the rule targets lines that changed for no functional reason, not large diffs in general. A rename that touches forty call sites is a big diff with a clear, single reason for every line in it.

How do I catch a full-file reformat before it gets merged?

Read the diff stat before the diff itself. A change described as a one-line bug fix that shows a hundred lines changed is the signal to stop and ask why, before you spend time reviewing content instead of just the shape of the change.

How did this land?

About the author

Steve Jefferson
Steve Jefferson

Developer Advocate

Steve builds something with Swarmz every week and writes up what worked, what broke, and what he'd do differently. Tutorials and hands-on guides are his lane.

Share

Get the next post in your inbox

One email a month. Product updates, engineering posts, and the best of Built with Swarmz.

I agree to receive emails about AI building tips and Swarmz product news. Unsubscribe any time.