Sub topic 8
Using recent edits as context
This chapter assumes you have read the chapter on building the request from prefix, suffix and related context. It also assumes you can read a unified diff and write basic Python.
Why the cursor is not enough
A plain completion request contains the text before the cursor, the text after it, and some related snippets. That is a snapshot. It shows what the file looks like now, but not how it got there.
Recent edits show intent. Suppose you rename w to width in a function signature. The snapshot shows a function whose body still uses w. The edit trail shows that you are in the middle of a rename. A model that sees only the snapshot might treat the old name as correct. A model that sees the trail can predict that the next change is w to width in the body, and later at the call sites.
Edit history is the main extra input that next edit suggestions need. It is also useful for ordinary completions, which can use it to match the style and direction of what you are doing.
What counts as a recent edit
An edit is a change to a document, with a before state and an after state. The editor reports edits as events, usually one per keystroke or paste. A history is an ordered list of these changes. It is limited by age, count and size.
| Property | What the assistant records | Why it matters |
|---|---|---|
| Location | File path and line range | Lets the model relate the edit to the cursor position |
| Content | Removed and inserted text | Shows what changed |
| Order | Sequence number or timestamp | Newer edits usually matter more |
| Origin | Typed, pasted, undo, formatter, accepted suggestion | Lets you filter noise (see below) |
Origin is the property that is easiest to forget. Without it, the history cannot tell your edits from edits made by tools.
From keystrokes to meaningful edits
If you record each keystroke separately, typing width produces five events. Sending them all would fill the prompt with fragments that carry no more meaning than one event. So assistants coalesce edits: they merge consecutive changes that belong together.
Common merge rules:
- The edits are in the same file.
- The second edit starts where the first one ended, or on the same lines.
- They happened within a short time window, often one or two seconds.
After merging, the history holds one entry per logical change, such as "renamed w to width in the signature". Merging also gives you a natural place to drop no-ops. If the merged edit has the same before and after text, for example after a typed character was deleted again, nothing changed and the entry can be discarded.
A small implementation
The following program records edits, merges them, and renders the history as diffs that fit a character budget. It uses only the standard library. A real assistant counts tokens instead of characters, but the structure is the same.
import difflib
from dataclasses import dataclass
@dataclass
class Edit:
path: str
before: str
after: str
timestamp: float
def to_diff(edit: Edit) -> str:
lines = difflib.unified_diff(
edit.before.splitlines(),
edit.after.splitlines(),
fromfile=f"a/{edit.path}",
tofile=f"b/{edit.path}",
n=1,
lineterm="",
)
return "\n".join(lines)
class EditHistory:
def __init__(self, merge_window: float = 2.0, max_chars: int = 2000):
self.merge_window = merge_window
self.max_chars = max_chars
self.edits: list[Edit] = []
def record(self, path: str, before: str, after: str, now: float) -> None:
last = self.edits[-1] if self.edits else None
if (
last is not None
and last.path == path
and last.after == before
and now - last.timestamp <= self.merge_window
):
# Same logical change: keep the original "before", take the new "after".
last.after = after
last.timestamp = now
if last.before == last.after:
self.edits.pop() # the edit undid itself
else:
self.edits.append(Edit(path, before, after, now))
def render(self) -> str:
chosen: list[str] = []
used = 0
for edit in reversed(self.edits): # newest first
diff = to_diff(edit)
if not diff:
continue
if used + len(diff) > self.max_chars:
break
chosen.append(diff)
used += len(diff)
return "\n\n".join(reversed(chosen)) # oldest first in the prompt
history = EditHistory()
v0 = "def area(w, h):\n return w * h\n"
v1 = "def area(width, h):\n return w * h\n"
v2 = "def area(width, height):\n return w * h\n"
history.record("geometry.py", v0, v1, now=0.0)
history.record("geometry.py", v1, v2, now=0.5) # merged with the previous edit
history.record("app.py", "x = 1\n", "x = 2\n", now=10.0)
print(history.render())Running it prints two diffs. The two keystroke-level edits in geometry.py have become one:
--- a/geometry.py
+++ b/geometry.py
@@ -1,2 +1,2 @@
-def area(w, h):
+def area(width, height):
return w * h
--- a/app.py
+++ b/app.py
@@ -1 +1 @@
-x = 1
+x = 2Three design choices in this code are worth noting:
- Merging keeps the first
before. The merged entry describes the whole change from the original state to the latest state. - Selection goes newest first, rendering goes oldest first. The budget protects the most recent edits, but the model reads the story in chronological order.
- The cut is at whole edits. Truncating a diff in the middle could produce a confusing fragment.
How the history is used in the prompt
The history goes into the prompt as its own section, usually before the current file content. Three formats are common.
| Format | Example | Strength | Weakness |
|---|---|---|---|
| Unified diff | `-def area(w, h):` and `+def area(width, height):` | Compact, models have seen many diffs | Loses context beyond a few lines |
| Before and after blocks | Old snippet, then new snippet | Easy to read, clear for small edits | Costs more tokens for large blocks |
| Annotated current file | Current file with markers on changed regions | Shows edits in place | The markers must be learned by the model |
For edit prediction, models are generally trained on the same format used at inference time. That means the prompt format is part of the model's contract. If you change the format without retraining or re-prompting, quality drops.
For an inline completion, a few recent diffs are usually enough, and they come after the higher-priority prefix and suffix in the budget. For next edit suggestions, the history is central, so it gets a larger share. The details of that prediction are covered in the next chapters.
Choosing what to keep
A history can grow without limit, and the prompt cannot. Assistants typically apply these limits together:
- Count. Keep only the last N merged edits, for example the last 5 to 20.
- Age. Drop edits older than a few minutes, or edits from before a long pause.
- Size. Skip any single edit that is larger than a threshold, such as a pasted file.
- Distance. Prefer edits in the current file or in files that are open nearby.
Recency is only a proxy for relevance. An edit you made ten minutes ago in the file you are working on may matter more than one from ten seconds ago in an unrelated file. Some systems score edits by a mix of age and proximity instead of using age alone.
Edge cases
Most problems with edit history come from edits that do not reflect your intent.
- Pastes. A pasted block is often large and tells the model little about what you will do next. Many assistants cap its size or summarize it.
- Formatter runs and refactoring tools. A "format on save" can change hundreds of lines. If these enter the history as normal edits, they crowd out your real work. Tag them by origin and exclude them.
- Accepted suggestions. After you accept a completion, the inserted text becomes an edit. Counting it as your own edit can create a feedback loop where the model keeps extending its earlier output. Keep it tagged, and treat it carefully.
- Undo and redo. Undoing an edit reverses it. A history that contains both the edit and its reversal wastes space and may mislead the model. The self-cancelling check in the code above handles the simple case.
- Stale edits. After you switch branches, run
git checkout, or reload a file from disk, earlier edits no longer match the file. Clear or invalidate the history when the document changes outside the editor's event stream. - Line shifts. Line numbers in an old diff are wrong once lines above them change. Diffs for the prompt should use content and short context, not absolute positions, or be recomputed from current text.
Cost and latency
Every extra token in the prompt adds processing time, and completions are latency-sensitive. Edit history also changes between requests, which hurts caching. Many serving systems reuse the computed state of a prompt's unchanged beginning. A history placed early in the prompt that changes on every keystroke invalidates that reuse. Placing stable content first and the changing history near the end keeps more of the prompt cacheable. This is a trade-off against putting the history where the model attends to it best, and teams tune it by measurement.
Exercise
A user types the word total one character at a time in 1.5 seconds, then pastes a 3,000-line file, then runs the formatter. Using the merge rules and filters from this chapter, which of these should end up in the prompt's edit history, and why?
Show answer
The typed total should be one merged edit, because the characters are in the same place, contiguous, and inside the merge window. The 3,000-line paste should be capped or dropped, because it exceeds the size limit and says little about what comes next. The formatter changes should be excluded by origin, because they are not the user's intent and would crowd out the real edit.
Exercise
In the Python example, why does render loop over reversed(self.edits) but join the result with reversed(chosen)?
Show answer
The first loop walks from newest to oldest so the size budget is spent on the most recent edits. chosen is therefore in newest-first order, so reversing it puts the diffs in chronological order, which is how the model should read the story of the edits.