Stale context: when the assistant works from an outdated copy

APIClaudeKeyFree · Updated 2026-11-24 · 9 min read

Two copies of a document, one with handwritten corrections
The assistant often holds an older copy than the one you just edited.

A familiar sequence for anyone pairing with an AI coding tool: you ask for a change, accept it, tweak a few lines yourself, then ask for another change. The second answer quietly reverts your tweak, or applies its edit to code that no longer exists. Developers often describe it as a sync bug, and sometimes it is, but more often it is a predictable consequence of how these tools hold context.

This article explains where the outdated copy comes from, how different tools and workflows make it more or less likely, and the habits and tooling choices that keep your own edits safe. It applies to terminal agents, IDE extensions and home-made scripts that call a chat API, including scripts built on the keyless endpoint on this site.

Frequently asked questions

What is stale context in an AI coding tool?

It is any version of a file that the model saw earlier in the conversation and still treats as current. If the file changed on disk after the model read it, the model is reasoning about an outdated copy unless the tool reads the file again.

Is this a bug in the model or in the tool?

Usually in the interaction between the two. The model can only see what the tool puts into its context. If the tool does not re-read a file you edited, the model has no way to know about your change.

How does a whole-file rewrite differ from a patch edit?

A whole-file rewrite replaces the file with the model's version, so anything the model did not know about is lost. A patch edit changes specific lines and usually fails loudly if those lines no longer match, which protects your work.

Does a larger context window solve it?

No. A larger window lets the model hold more old copies, which can make the problem worse. What matters is whether the latest version of the file is in context and clearly marked as the current one.

Which is better: editing by hand between prompts or letting the agent do everything?

Both work if the tool re-reads files. If it does not, keep manual edits and agent edits in separate steps, and tell the agent to reload the file before continuing.

Can version control prevent lost edits?

It cannot prevent them, but it makes them cheap to recover. Committing or staging before each agent request gives you a clean diff to review and a quick way back.

Why does the problem appear more in long sessions?

Long sessions contain many versions of the same file. Some tools also compact or summarise older context, and a summary may describe the file as it was rather than as it is.

Does this happen with API-based scripts too?

Yes, and more often. A chat API is stateless: it sees only the messages you send. If your script sends the original file content and then a new instruction, the model will edit the original, not your updated file.

Step by step

  1. Commit before asking — Stage or commit your working tree so any change the assistant makes appears as a reviewable diff.
  2. Name the files you changed — Tell the assistant which files you edited by hand and ask it to read them again before the next change.
  3. Prefer patch edits — Choose tools or settings that apply targeted replacements instead of rewriting whole files.
  4. Review the diff — Check removed lines for anything you wrote yourself before accepting the change.
  5. Reset long sessions — If edits keep missing, commit, close the session and start again with the current files.

How the outdated copy gets into the conversation

Every coding assistant builds a context for the model out of the conversation so far plus whatever files it decided to read. When the model first opened your file, its full contents went into that context. When it proposed a change, the new version went in too. None of that updates automatically when you type in your editor. Unless the tool notices the change on disk and feeds the new content back, the most recent version the model knows about is its own.

From the model's point of view, nothing is wrong. It is asked to make a second change, it looks at the latest file it can see, and it produces an edit or a rewrite based on that. Your manual tweak is simply invisible.

The model has no file system

Language models do not watch your disk. Tools read files and paste them into the prompt. If the tool does not read again, the model cannot know the file changed.

Its own output looks authoritative

The most recent file version in the conversation is often the one the model wrote itself, so it naturally treats that as the source of truth.

Rewrites versus targeted edits

How badly stale context hurts depends on how the tool applies changes. Some tools ask the model for a full replacement file; others ask for a search-and-replace patch or a unified diff. The first approach silently overwrites anything the model did not know about. The second approach usually fails when the lines it expects are missing, which is annoying but safe.

If you build your own tooling on a chat API, prefer patch-style edits for this reason. They also use fewer output tokens, which matters when answers are capped, as they are at 16,000 tokens on the free endpoint here.

Why full rewrites are risky

A full rewrite is only as current as the copy the model started from. Any change made outside the conversation, by you, a formatter or another agent, is lost without warning.

Why patches fail safely

A patch that says replace these exact lines will not apply if the lines changed. The tool can then re-read the file and ask the model again, using the real current version.

A tailor sewing a patch onto a jacket
Targeted patches fail safely when the original no longer matches.

Context compaction and summaries

Long agent sessions eventually hit the context limit. Many tools respond by summarising older turns, dropping file contents and keeping a description instead. That keeps the session going but introduces another source of staleness: the summary may say a function looks a certain way when it has since changed.

Developers often notice that quality slips after a session has been running for a while, and stale or summarised file state is a common reason. Starting a fresh session with the current files is frequently faster than trying to correct a long one.

Signs the model is working from a summary

It refers to variables or functions that you renamed, proposes code in the wrong place, or describes the file structure as it was an hour ago.

Reset beats repair

When several edits in a row miss, end the session, commit what you have and start again with an explicit instruction to read the relevant files first.

Habits that protect your edits

Most lost-edit incidents can be prevented with small changes in workflow rather than new tools. The common thread is making the current state of each file explicit and recoverable.

Say it explicitly

A one-line prompt such as I edited utils.py, please re-read it before making the next change often fixes the issue immediately, because most tools will then load the file again.

Small, frequent commits

Commits are cheap. A commit before each request turns a lost edit from a debugging session into a single command to restore it.

  • Stage or commit before each agent request, so every change the agent makes is visible as a diff.
  • After editing a file by hand, tell the assistant which file changed and ask it to re-read it before continuing.
  • Keep manual edits and agent edits in separate files when you can, especially during long refactors.
  • Turn off any auto-accept setting for files you are actively editing yourself.
  • Review diffs, not just the final file; a revert of your change shows up clearly as removed lines.
Notes being condensed onto one index card
Summarised context keeps a session alive but can describe files as they used to be.

Building your own assistant on a stateless API

If you write scripts that call a chat endpoint to edit code, the stale-copy problem is entirely in your hands. The API keeps no state between requests, so the model only knows what is in the messages array you send. The rule is simple: read the file from disk immediately before every request and send that, not a version cached from an earlier step.

The sketch below reads the current file, asks for a small replacement block and applies it only if the original text is still present. It uses the OpenAI SDK pointed at this site's keyless endpoint, and works the same with any compatible backend.

Fresh reads every time

Never reuse file content from a previous request. Reading a file costs microseconds; debugging a silent revert costs an afternoon.

Refuse patches that do not match

If the old snippet is not found exactly once, stop and retry with the current file rather than guessing where the change belongs.

import json, pathlib
from openai import OpenAI

client = OpenAI(base_url="https://api.apiclaudekeyfree.com/v1", api_key="none")
path = pathlib.Path("utils.py")

def edit(instruction):
    current = path.read_text()  # always read fresh from disk
    prompt = ("Return JSON with keys 'old' and 'new'. 'old' must be an exact snippet "
              "from the file, 'new' its replacement.\n\nFILE:\n" + current +
              "\n\nTASK: " + instruction)
    r = client.chat.completions.create(model="free-ai", temperature=0,
        messages=[{"role": "user", "content": prompt}])
    out = r.choices[0].message.content
    patch = json.loads(out[out.find("{"): out.rfind("}") + 1])
    if patch["old"] not in current:
        raise RuntimeError("snippet not found, file changed or model misread it")
    path.write_text(current.replace(patch["old"], patch["new"], 1))

edit("rename the function load_cfg to load_config")

When several agents touch the same files

Running multiple agents in parallel multiplies the problem. Each agent has its own context and its own idea of the current file, and the last one to write wins. A common report is that one agent fixes a bug and another, working from an older copy, reintroduces it a few minutes later.

Give each agent its own set of files or its own working copy, and merge their results deliberately. Separate working trees or branches are a simple way to do this. If agents must share files, serialize their writes and force a fresh read before each one. Routing different subtasks to different agents or models is discussed in our article on subagent routing.

One owner per file

Assign each file to a single agent for the duration of a task. Other agents can read it but propose changes through the owner or through you.

Merge, do not race

Let agents work on separate branches and merge with normal version-control tools, which are designed to detect conflicting edits.

Separate trails meeting at a mountain hut
Parallel agents should work on separate paths and meet only at a deliberate merge.

Telling a real sync bug from stale context

Sometimes the tool really is broken: it may fail to detect file changes on certain file systems, in containers, or with editors that save through temporary files. To tell the difference, ask the assistant to print the first few lines of the file as it currently sees them. If they are outdated even after you asked it to re-read, the problem is in the tool, and it is worth reporting with exact steps.

If the content is current after a re-read, the tool works and the issue was simply that it had no reason to look again. In that case, a habit or a setting change is the fix, not a bug report.

Reproduce with a tiny file

Create a ten-line file, ask for an edit, change one line by hand, ask for another edit. Whether your line survives tells you quickly how the tool behaves.

Where a keyless backup fits

None of this is specific to one vendor. Claude-based tools, other commercial assistants and open models all depend on the context they are given. If you prototype your own editing scripts, a free OpenAI-compatible endpoint lets you test the read-patch-verify loop without spending credits, then switch the base URL to your paid provider for real work. This site is not affiliated with Anthropic, and free-ai is not a Claude model.

For serious refactoring across a large codebase, a strong commercial model with a long context will usually do better than a mid-sized open model. For simple, well-scoped edits and for testing your tooling, the smaller model is often good enough, and the same patch discipline applies to both. If you want to generate small self-contained programs rather than edit existing ones, see artifact-style mini apps over an API.

Test the tooling, not just the model

Most lost-edit bugs are in the loop around the model. A free endpoint is a cheap place to make that loop robust before it touches important code.

A circuit board under a magnifying lamp
A tiny reproducible case tells a real sync bug apart from stale context.
Try the free API

Send a test request to the keyless, OpenAI-compatible endpoint on the home page and see how it fits your project.

Read also