ByteCosts
context-poisoning-fresh-session.mdx

AI Coding Agents

Context Poisoning in Coding Agents: Compact, Rewind, or Start Fresh

Context poisoning is when an error enters a coding agent’s context and keeps being referenced, repeatedly influencing later steps. Rewind to a trustworthy checkpoint if you can locate the mistake. Start a fresh session from a verified handoff when repeated corrections fail or the error is hard to isolate, and use focused compaction to shorten history you still trust.

Context poisoning occurs when an agent repeatedly relies on an error already in its context, such as a misread stack trace, a hallucinated path, or a guessed constraint. Check whether you can identify the turn where the error entered. A known checkpoint gives you a place to rewind. If the premise has spread across the session or corrections keep failing, start a fresh active context with a handoff built from evidence you verified.

A taxonomy for what went wrong

Developer Drew Breunig’s June 2025 post “How Long Contexts Fail” names four failure modes. He synthesizes published reports into a taxonomy you can use to diagnose a stalled session.

  • Context poisoning: “a hallucination or other error makes it into the context, where it is repeatedly referenced.” An error in an earlier diagnosis can become the basis for later edits.
  • Context distraction: the context “grows so long that the model over-focuses on the context,” neglecting what it learned in training and repeating past actions instead of solving.
  • Context confusion: “superfluous content in the context is used by the model to generate a low-quality response.” An unrelated log excerpt can steer the response even if the excerpt is accurate.
  • Context clash: new information in the context “conflicts with other information in the context,” for example an early wrong answer sitting next to the later correct one.

Breunig uses Gemini Plays Pokémon to illustrate two failure modes. Google reports an anecdotal tendency to repeat actions as context grew significantly beyond 100k tokens. Separately, the appendix describes false game-state information persisting in goals and summaries. In a coding session, a similar pattern is an agent continuing to edit the same component after a reproduction points to a different module. Check the reproduction and the agent’s stated reason for the edit before calling the session poisoned. The repeated edit may also reflect a real dependency that you have yet to verify.

Breunig’s follow-up post names the countermeasures: context pruning (removing unneeded content), context summarization, context offloading to external storage, context quarantine in dedicated threads, retrieval for adding only relevant content, and tool loadout for shrinking the tool list. The commands below act on different parts of the session, from a single branch of work to the entire active transcript.

What the official docs recommend

Claude Code’s best-practices page gives a rule for failed steering. It recommends that “after two failed corrections run /clear and write a better prompt instead of a third.” The reasoning is mechanical: “a third correction mostly adds to a conversation that already contains two failed attempts for Claude to keep re-reading.” The same page advises /clear between unrelated tasks because “it costs nothing, and it means the next task doesn’t keep paying for the previous one’s history,” and suggests naming the session you are leaving (/clear oauth-migration) so claude --resume oauth-migration can pick it back up later; the costs page gives the same flow as /rename before clearing, then /resume.

For sessions worth keeping, the toolkit is more surgical. /compact accepts a focus, like /compact focus on the auth bug fix, so the summary keeps what you choose; note that on a long session “/compact is itself a big request, since it reads the whole conversation to summarize it.” /rewind rolls the code, the conversation, or both back to an earlier prompt, and its menu offers “Summarize from here” and “Summarize up to here” for compacting only part of the transcript. Claude Code also compacts automatically near the window limit. As of November 30, 2026, Claude Code can compact an idle session above roughly 200K tokens shortly before its one-hour cache expires, when idle compaction is enabled.

OpenAI’s Codex guidance recommends keeping chats focused on one unit of work. Staying in one chat “preserves the reasoning trail,” while running a whole project in one chat “leads to bloated context and worse results over time.” In the Codex CLI, use /compact for a summarized version of earlier context (Codex also compacts automatically), /fork to create a new chat while preserving the original transcript, with the instruction to “fork only when the work truly branches,” and /resume for returning to saved chats.

A decision table by symptom

Symptom in the sessionLikely failure modeFirst move
Work is on track, context is just longNone yet; rising rot riskContinue; run /compact with a focus at the next natural break
You corrected the same thing twice and it is still wrongPoisoning or clash/clear, then write one new prompt that folds in what you learned
The agent took an approach you now want to abandonHealthy context, wrong branch/rewind to the turn before the branch, keeping code or conversation as needed
A “fact” from early in the session is wrong and keeps being citedPoisoningFresh session with a handoff note; a summary may carry the false fact forward
The task itself changedStale, irrelevant history/clear between tasks; name the old session first so you can resume it
The work genuinely splits in two directionsTwo coherent units of workFork (Codex /fork) or open a second session for the branch
Agent repeats an action loop instead of planningDistractionFresh session with a handoff note; shrink what exploration reaches the main thread

Rewind when you can identify a trustworthy checkpoint before the error. Compact when the history is still reliable. Fork when the work branches. Start a fresh active context when the bad premise is hard to isolate or repeated corrections have failed.

Suppose the agent claims a job times out because of the retry delay and then repeats that claim after a reproduction shows the failure occurs before the retry starts. Look for the last turn where the agent had the verified reproduction and had yet to adopt the diagnosis. If that checkpoint exists, rewind the conversation to it. Check the diff separately before choosing whether to rewind code too. If the old session contains edits worth preserving, inspect the diff and record which changes remain in the working tree so the next session can verify them.

Write the handoff note before you clear

A fresh session only fixes poisoning if the bad content does not travel with you. Write the note yourself or have the agent draft it for your review, then start the new session with the note plus a pointed first prompt. Keep it short enough that you actually read it.

Goal and acceptance check:
Verified facts (with the check that proved each):
Disproved hypotheses (what was tried and ruled out):
Exact error text or code being chased:
File paths involved (project-relative):
Current diff state (committed, staged, or unsaved):
Next action and what would confirm it:

Record disproved hypotheses with the evidence that ruled them out. For example, note that increasing the retry timeout left the failure unchanged. Include the conditions of that check, such as which test you ran and which failure you observed. Keep the conclusion within that scope. The unchanged result can rule out that specific timeout adjustment without resolving every possible retry bug.

Review the note against the working tree before clearing. For an exact error, copy the line the agent should search for and record where it came from. For a changed file, record its path and whether the edit is already present. If you can reproduce the failure with a short command, include the command and what output would confirm the current diagnosis.

Ask the new session to state the goal, identify the evidence it will check, and explain what result would make it revise the diagnosis. If it repeats a disproved hypothesis, check the handoff against the repository and repeat the verification before editing. For the timeout example, make the first action locating the failure relative to the retry call in the reproduction. The answer should name the observation that supports it and direct the next check.

What the switch costs

This API estimate isolates a fixed history prefix over ten requests. It assumes a five-minute cache, a cache write on each cold start, and a hit on each subsequent request. The warm continuation starts with the prefix already cached. New messages, tool calls, outputs, and compaction are outside the estimate.

Rates are for Claude Sonnet 5.5 as of November 30, 2026. Per million tokens, base input is $2, output is $10, cache reads are $0.10, and five-minute cache writes are $2.50. See the provider pricing index for current rates.

Path over 10 requestsToken assumptionsHistory-prefix input cost (estimate)
Continue, cache warmRead the 150k-token prefix from cache on every request10 × 150k × $0.10/1M = $0.150
Continue after a break, cache coldWrite the 150k-token prefix once, then read it from cache150k × $2.50/1M + 9 × 150k × $0.10/1M = $0.510
Fresh sessionWrite a 20k-token starting prefix once, then read it from cache20k × $2.50/1M + 9 × 20k × $0.10/1M = $0.068

Under these assumptions, the fresh prefix costs about 45% of a warm continuation and 13% of a cold continuation. Subscription allowances use their own accounting. If you need the old history, compare the cost of the compaction request and the subsequent shorter prefix with the cost of continuing. A warm cache can discount the summarization request. After expiry, Claude Code reads that history as uncached input, generates the summary, and rebuilds the conversation cache on the next request.

Include the cost of reconstructing evidence when you compare a restart with a continuation. A short launch prompt can still lead to repeated file reads and a long tool transcript. Estimate which files and checks the new agent will actually need, then include those requests in any comparison of total cost. When a false premise keeps driving edits, use the handoff verification as your first acceptance check. The price table compares prefix lengths, while the verification tells you whether the new session can proceed from the evidence you retained.

What to do next

For evidence on how longer inputs affect specific retrieval and reasoning tasks, read context rot in coding agents. To decide what a compaction should keep verbatim versus summarize, see lossless versus lossy context compaction. The prompt caching explainer covers the mechanics behind the cost table above, compaction versus cache cost goes deeper on what each option bills, and managing long sessions expands the handoff note into a full continuity workflow.

Sources

Interactive report

  • The Long-Context Mirage: A model can accept a million tokens and still miss the line of code you need. Follow the published accuracy results, then price the decision to keep, trim, or leave a long conversation.

How this note was produced

Drafted with AI assistance from committed ByteCosts pricing snapshots and deterministic cost formulas. Figures are grounded in the linked sources (last updated 2026-11-30). Read our editorial & automation policy, inspect the methodology, or report a discrepancy.

Context Poisoning in Coding Agents: Compact, Rewind, or Start Fresh. ByteCosts. Updated 2026-11-30. https://bytecosts.com/blog/context-poisoning-fresh-session/

Sources