Reducing AI Code Editing Granularity: From Whole-File Rewrites to Line-Level Patches

    Whole-file rewrites are a common pain point when using AI coding assistants: a one-line change forces the model to regenerate thousands of lines, risking truncation, higher cost, and unintended edits. This article explains why coarse-grained edit interfaces cause this behavior, and how to fix it with a locate-read-patch pipeline using line-range reads, line-number block replacements, visible failure handling, and structured diff validation. It also covers engineering details such as stale line numbers, concurrent edits, encoding preservation, and practical workarounds when you cannot change the underlying tooling.

    In everyday development, many people run into an exhausting interaction pattern: you just want to rename an identifier from ctx to session, yet the AI coding assistant regenerates the entire multi-thousand-line source file. The output is slow and expensive, may be truncated midway, and worse, the model may “helpfully” change a few unrelated spots, leaving the developer to manually audit the entire file. It is tempting to blame the model’s intelligence, but from an engineering perspective the more common root cause is that the editing interface is too coarse: the tool layer only offers two hammers—read the whole file, overwrite the whole file. When facing a local change, the model has no choice but to rewrite everything.

    The core fix is not to immediately switch to a larger model, but to reduce editing granularity from “file” to “lines or blocks,” paired with precise context injection and verifiable change results. Below we walk through problem diagnosis, capability breakdown, implementation constraints, and temporary workarounds when you cannot change the tooling.

    Why Whole-File Rewrites Become the Default Path

    A failed interaction can be broken down into three mutually reinforcing root causes.

    First, tool granularity. If the assistant can only “write the whole file,” then even a one-line change requires, at the protocol level, the complete new file. Output tokens are typically one to two times the input, and long files are more likely to be truncated mid-generation, lose lines, or pick up damaged styles, comments, and unrelated logic. The developer then has to find the three intended changes and the accidental ones within thousands of lines—the cost shifts from the model side to the human side.

    Second, context granularity. If reading also means stuffing the whole file into the prompt, examining a twenty-line function body drags in three thousand lines of surrounding code. The truly relevant symbol definitions, call sites, and type constraints get diluted, attention is scattered, the probability of wrong edits rises, and you pay for irrelevant text. A local change should be a high-signal-to-noise task; whole-file context turns it into a low-signal one.

    Third, validation granularity. Without a structured description of the diff, “it’s done” is just a natural-language claim. Humans cannot quickly confirm the scope with a standard diff; they can only scan by eye. This step often takes longer than waiting for the model to generate, and silent errors slip through more easily.

    Combined, the interaction pattern is locked in: read a lot, write a lot, verify slowly. To break the cycle, the model must be given hands that can “read only a segment, change only a segment, and say failure when it fails.”

    Break a Change into Locate, Read by Lines, Patch by Lines

    A more sensible tool semantics can be abstracted into a three-step pipeline rather than a single “overwrite file” operation.

    The locate phase needs only a file path, symbol name, approximate line number, or function name. There is no need to send the full text to the model. Many language servers, indexes, or simple text searches can produce candidate line ranges. The goal is to circle “the few dozen possibly relevant lines,” not to use the whole repository as context.

    The read phase should slice by line numbers. The interface can take a start line and end line (inclusive on both ends, 1-indexed), or a range notation like “246:330.” Encoding should be auto-detected for common character sets to avoid a split multi-byte character shifting all subsequent line numbers. For large files, pull only the function body or a local block—this is where the first chunk of irrelevant context is saved. What the model sees is a dense fragment: the signature, local variables, and a few neighboring call sites, which is enough for a rename or a small refactor.

    The write phase should perform block replacement rather than whole-file rewriting. One model-friendly form is the “line-number block”: given a start line, an end line, and new text. The semantics can be made very explicit: start line N with an empty end line means replace only line N; an end line M greater than or equal to N means replace the closed interval N to M; an end line smaller than the start line means insert before line N. Insert, replace, and single-line rewrite cover the vast majority of everyday local edits. The model only needs to output the few lines that actually change, instead of three thousand lines of original text plus three lines of change.

    There is also a “byte block” form: offset, old length, new content. It suits machine-precise positioning or applying multiple concurrent patches to the same file, but it is not suitable for asking a model to count bytes by hand—neither human brains nor language models are good at counting offsets in variable-length UTF-8 encoding. Byte interfaces should stay inside the toolchain; line-number interfaces are what should be exposed to the conversational side.

    Failures Must Be Visible; Out-of-Range Must Not Be Silent

    If fine-grained editing “guesses” at boundaries, the harm is more insidious than whole-file rewrites. When a line number exceeds the current file length, the tool should report an error and state “the file currently has X lines,” rather than clamping to the last line or modifying a different location. When a patch fails to apply, it should not append something like “index synchronized” that implies success. Explicit failure is far safer than fake success: the model can re-read the real line numbers and retry, and a human can intervene immediately.

    After applying a patch, the tool layer should return a standard diff, or at minimum the “old snippet / new snippet / line range.” This aligns validation granularity with editing granularity: a human confirms in seconds with a diff view instead of scanning the full file. If a language server is available, run diagnostics after the patch and feed unresolved symbols and type errors into the next round, forming an “edit a small step, verify a small step” loop.

    Tightening the Interaction Immediately Without Changing the Underlying Tool

    Even if your current environment only supports whole-file reads and writes, conventions can reduce the damage.

    First, explicitly forbid outputting unchanged lines in the prompt. Require only “file path + line range + replacement text,” and apply it with an editor macro or script. Even if the assistant cannot call a fine-grained interface directly, shaping the output in fine-grained form reduces truncation and unrelated rewrites.

    Second, trim the context manually: paste only the target function, the relevant type definitions, and two or three call sites, and state “do not fabricate the rest of the file.” This is a manual version of “read by lines.”

    Third, restrict each task to one class of mechanical change—e.g., only rename, without formatting or refactoring neighboring functions along the way. The narrower the constraint, the fewer accidental diffs appear in whole-file output.

    Fourth, commit a clean working tree with version control first, then immediately inspect the diff after applying the model’s result. Validation still happens on the human side, but at least with tooling assistance, so “a line changed far away” cannot be missed.

    These practices cannot fundamentally eliminate excess tokens, but they turn the worst case from “silent corruption” into “visible and rollback-able.”

    Engineering Details When Designing Fine-Grained Editing

    Line numbers must match the current on-disk version. If the file is formatted or edited by someone between read and write, all line numbers shift. In practice, the patch should carry an old-text fingerprint or the old line content, compare first at apply time, and then replace—avoiding applying the patch to the wrong location.

    When multiple edits target the same file concurrently, line-number blocks may interfere with each other. In that case it is better for the tool internally to convert multiple line-level patches into one ordered application, or fall back to byte-level replacement anchored on old content. The model still sees only line-level semantics, with the runtime doing the merge.

    For large insertions, do not make the model retype subsequent unchanged lines. The insert semantics (end line smaller than start line) exist precisely for this case. When replacing a large block, output only the new block and let the tool stitch the file head and tail.

    Encoding and line endings must be preserved exactly. Automatically converting CRLF to LF, or expanding tabs into spaces, creates noisy “everything changed formally, nothing changed semantically” diffs that disrupt code review and may trigger unrelated CI failures. One of the values of fine-grained patches is keeping untouched bytes untouched.

    Summary

    “Change one variable, get the whole file back” is usually the result of tooling that ties the model’s hands into two hammers. By narrowing reads to line ranges, narrowing writes to line-number blocks or anchored local replacements, turning failures into explicit errors with diff validation, the model finally has room to do only the few lines that actually need doing. This does not depend on any specific product; it is a general capability that AI coding tools and editor integrations should have: locate, slice-read, chunk-write, visible failure. Once granularity comes down, tokens, truncation, wrong edits, and manual verification costs fall together. Then, and only then, debating how smart the model is addresses the genuinely remaining part of the intelligence problem.