cd /news/large-language-models/context-degradation-in-long-conversa… · home › topics › large-language-models › article
[ARTICLE · art-178471] src=flaviocopes.com ↗ pub= topic=large-language-models verified=true sentiment=· neutral

Context degradation in long conversations: measuring context rot and fixing it

A Node.js benchmark harness run against OpenAI's gpt-4.1-mini from 2,000 to 52,000 tokens found that classic needle-in-a-haystack retrieval accuracy barely dropped, but latency more than doubled and per-turn token cost jumped 25x, according to the author Flavio. The tests covered buried policies, multi-hop facts, noisy multi-turn rule checks and a polluted debugging session, and the author attributes real quality failures in long coding chats to mechanisms such as prefill cost and stale history competing for attention rather than raw prompt length. The author argues that advertised context windows of 128k, 200k or 1 million tokens describe only the hard ceiling before an HTTP 400 context_length_exceeded error, not the size at which a model still reasons reliably.

recommendation

Benchmark your own agent sessions from 2k to 52k tokens on latency and per-turn token cost, not just retrieval accuracy, and strip stale history since prompt caching cuts prefill cost but not attention noise.

more in playbook: Controlling LLM cost
read32 min views16 publishedNov 30, 2026
Context degradation in long conversations: measuring context rot and fixing it
Image: Flaviocopes (auto-discovered)

By Flavio

Tagged: AI

Why long agent chats slow down, cost 25x more, and drift before hitting the context limit, with live 2k to 52k token benchmarks and recovery patterns.

You’re forty turns into a coding session. The status bar says you’ve only used 28% of the context window, so there’s plenty of room left.

Yet the session starts falling apart. The model ignores a naming rule you gave in turn two, then edits a helper function you already fixed twenty minutes ago.

Each reply takes twice as long to start, too. And your usage meter climbs faster with every turn.

People call this context degradation, or context rot. Because the prompt still fits inside the model’s advertised limit, nothing throws an error, so quality, speed, and cost decay quietly while the chat keeps growing.

I wanted to separate the folklore from what happens on a modern model. So I built a small Node.js benchmark harness and ran real prompts against OpenAI’s gpt-4.1-mini from 2,000 tokens up to 52,000 tokens.

The tests covered four scenarios: buried policies, multi-hop facts, noisy multi-turn rule checks, and a polluted debugging session.

The results surprised me. Classic “needle in a haystack” retrieval barely dropped in accuracy, yet latency more than doubled and per-turn token cost jumped 25x.

The real quality failures in long coding chats come from much messier mechanics than raw prompt length.

In this guide, we’ll compare advertised limits with effective capacity and look at the exact numbers from my benchmark. Then we’ll break down the four mechanisms that derail long chats and build recovery patterns you can drop into your own harness or daily workflow.

Advertised context window versus effective context window #

Model release pages highlight huge numbers: 128k, 200k, or 1 million tokens. Those numbers describe the hard architectural ceiling.

They only tell you how many tokens the API accepts without returning an HTTP 400 context_length_exceeded error. They say nothing about whether the model reasons as reliably at token 50,000 as it does at token 2,000.

Why does that happen? A transformer computes attention across every token in the input sequence.

When a prompt holds 2,000 tokens, the model works inside a compact, clean workspace. Your system rules, your target file, and your current question sit right next to each other.

At 52,000 tokens, every extra token adds more keys and values to that attention step. Even with modern rotary positional embeddings (RoPE, which encode token order) and long-context training, two practical costs hit you right away.

The prefill tax and competing history

First, prefill work scales with input length. Before emitting the first output token, the inference engine has to read the whole prompt and build (or load) the key-value cache, the internal memory map it uses across all layers.

Longer inputs mean slower time to first token, even if the reply itself is only three lines long.

Second, every token you leave in the history competes for attention. Old terminal stack traces, superseded diffs, and half-baked theories from thirty minutes ago sit in the same token stream as your current instructions.

The model has no native “archive” flag for stale turns. Unless your harness strips them out, the model has to guess from wording alone which older messages are obsolete and which ones still govern the task.

Prompt caching lowers the bill for resending a long prefix, as I covered in prompt caching, compression, and compaction in coding agents. Caching helps your wallet and trims prefill time on repeated prefixes, but it doesn’t clean the noise out of the attention pass.

A cached 60,000-token mess is still a 60,000-token mess inside the model’s forward pass.

That gap between the maximum input a model accepts and the working size where it stays fast, cheap, and sharp is the effective context window. For most real coding work, your effective context window is far smaller than the number on the marketing page.

What our 2k-to-52k gpt-4.1-mini benchmark measured #

To see what degrades first, I ran four automated probes against gpt-4.1-mini using a local Node.js script (node run.mjs). I saved every prompt token count, latency measurement, and raw reply to JSON.

Here is what the four probes tested:

  • Buried policy with a stale distractor: We hid a 5-field payment retry config (retry_backoff_ms: 1450 ,max_retries: 5 ,idempotency_header: "X-Ledger-Key" ,circuit_open_sec: 42 ,rejects_negative_cents: true ) alongside a stale distractor block. We placed it at thetop ,middle , orbottom of padding ranging from ~2k to ~56k target tokens (actual sizes: 2,092 to 52,034 tokens).
  • 4-fact multi-hop synthesis: Four numeric facts (alpha: 14 ,beta: 27 ,gamma: 19 ,delta: 33 ) scattered across documents of 1,852, 12,983, and 37,843 tokens, asking the model to collect all four and return their exact sum (93 ).
  • 5-rule simultaneous constraint adherence: A SQLite indexing question with five strict formatting and length rules (including a hard 45-word cap and inline SQL keywords). We tested it after 0, 4, 10, and 18 noisy prior turns (102 to 10,712 prompt tokens), then tested it again after a fresh handoff (116 prompt tokens).
  • Polluted versus fresh debugging: A real JavaScript date-math bug on March 29, 2026 inEurope/Rome , a 23-hour DST spring-forward day whereMath.floor((b - a) / 86400000) returns0 instead of1 . We tested it once in a clean prompt and once after earlier turns chased an unrelated IEEE-754 andBigInt hypothesis.

Here is the raw terminal output from the first two suites:

And here is the visual summary comparing context size, position, latency, token count, and rule adherence:

Below are the full numbers from the buried-policy grid and the 4-fact synthesis runs.

Benchmark probe Target size Position Actual prompt tokens Accuracy Latency (ms) Cost multiplier vs 2k
Buried 5-field policy ~2k Top 2,093 5/5 1,053 1.0x
Buried 5-field policy ~2k Middle 2,092 5/5 958 1.0x
Buried 5-field policy ~2k Bottom 2,093 5/5 856 1.0x
Buried 5-field policy ~8k Top 7,096 5/5 904 3.4x
Buried 5-field policy ~8k Middle 7,097 5/5 1,473 3.4x
Buried 5-field policy ~8k Bottom 7,096 5/5 960 3.4x
Buried 5-field policy ~16k Top 13,826 5/5 1,170 6.6x
Buried 5-field policy ~16k Middle 13,826 5/5 1,078 6.6x
Buried 5-field policy ~16k Bottom 13,825 5/5 2,069 6.6x
Buried 5-field policy ~32k Top 28,864 5/5 1,500 13.8x
Buried 5-field policy ~32k Middle 28,866 5/5 2,565 13.8x
Buried 5-field policy ~32k Bottom 28,864 5/5 1,301 13.8x
Buried 5-field policy ~56k Top 52,034 5/5 2,467 24.9x
Buried 5-field policy ~56k Middle 52,033 5/5 1,624 24.9x
Buried 5-field policy ~56k Bottom 52,032 5/5 1,909 24.9x
4-fact synthesis ( sum=93 ) ~2k Scattered 1,852 4/4 + sum 810 1.0x
4-fact synthesis ( sum=93 ) ~16k Scattered 12,983 4/4 + sum 890 7.0x
4-fact synthesis ( sum=93 ) ~44k Scattered 37,843 4/4 + sum 1,563 20.4x

Clean retrieval holds up, but latency and cost climb fast

gpt-4.1-mini aced every single clean retrieval cell in that table. It returned 5/5 fields at top, middle, and bottom all the way out to 52,034 tokens.

It also returned {"alpha":14,"beta":27,"gamma":19,"delta":33,"sum":93} at 1,852, 12,983, and 37,843 tokens without missing a single integer.

Now look at the latency and cost columns instead.

Average latency on the buried-policy test more than doubled, jumping from 956 ms at 2k tokens to 2,000 ms at 56k tokens. Single requests swung from 856 ms at 2,093 tokens up to 2,565 ms at 28,866 tokens (middle) and 2,467 ms at 52,034 tokens (top).

On the 4-fact synthesis task, latency nearly doubled from 810 ms to 1,563 ms.

Per-turn input tokens jumped 24.9x, from 2,093 to 52,034 tokens. And in a multi-turn agent loop, you don’t pay that cost once.

You pay it on every follow-up turn. Ten more turns at 52,000 tokens process half a million input tokens just to make a handful of small edits.

Why needle-in-a-haystack benchmarks mislead developers

If you only checked the 5/5 accuracy column above, you might conclude that long contexts are solved. That’s the trap built into classic needle-in-a-haystack benchmarks.

Modern models are heavily post-trained to pass clean retrieval tests. When a distinctive policy block (X-Ledger-Key, 1450, 42) sits inside generic filler paragraphs, retrieval attention heads have an easy job because nothing else resembles those target keys.

Real coding chats almost never look like clean filler plus one distinct needle.

In a real session, the “haystack” is packed with lookalikes:

  • Old versions of the same file.
  • Half-applied refactors using identical variable names.
  • Earlier messages you later reversed (“scratch that, skip Redis and use SQLite”).
  • 12,000 lines of test output referencing the same functions.

Unlike irrelevant boilerplate, those stale tokens look like valid answers.

What happens in multi-turn conversations

You can already see the early warning signs in our second pair of probes, where we moved from static documents to multi-turn chat history.

Multi-turn probe Session state Prompt tokens Output tokens Latency (ms) Outcome and drift notes
5-rule SQLite answer 0 noisy turns 102 n/a 1,087 5/5 rules, 40 of 45 max words
5-rule SQLite answer 4 noisy turns 2,553 n/a 1,020 5/5 rules, 39 of 45 max words
5-rule SQLite answer 10 noisy turns 6,122 n/a 1,268 5/5 rules, 39 of 45 max words
5-rule SQLite answer 18 noisy turns 10,712 n/a 1,269 5/5 rules, 44 of 45 max words (word creep right to ceiling)
5-rule SQLite answer Fresh handoff 116 n/a 1,082 5/5 rules, 41 words, 98.9% fewer tokens
Europe/Rome DST bug Polluted history 418 132 1,570 Found DST root cause, spent extra tokens rebutting stale IEEE-754 / BigInt theory
Europe/Rome DST bug Fresh session 166 98 1,131 Direct DST explanation, 52% fewer total tokens, 28% faster

Let’s compare the real outputs from the 5-rule SQLite probe at turn 0 and turn 18.

At 0 noisy turns (102 prompt tokens, 40 words):

- Use `CREATE INDEX` to improve query performance by reducing full table scans.
- Run `EXPLAIN QUERY PLAN` to analyze how SQLite uses indexes during query execution.
- Indexes on columns in `WHERE` or `JOIN` clauses optimize data retrieval paths.

After 18 noisy turns (10,712 prompt tokens, 44 words out of the 45-word ceiling):

- Use `CREATE INDEX` to add indexes on columns to improve query performance.
- Run `EXPLAIN QUERY PLAN` to analyze how SQLite uses indexes in your `SELECT` statements.
- Indexes speed up lookups but slow down `INSERT`, `UPDATE`, and `DELETE` operations due to maintenance.

It still passed all five rules, so a binary pass/fail check would say everything looks fine. Yet the reply quietly crept right up to the 45-word limit (one more word and rule 5 fails) while burning 105x more prompt tokens (10,712 versus 102).

When we reset to a fresh handoff, prompt tokens dropped by 98.9% (from 10,712 down to 116). Latency fell back to 1,082 ms, and the reply stayed crisp at 41 words:

- Use `CREATE INDEX` to improve query performance by reducing full table scans.
- Run `EXPLAIN QUERY PLAN` to analyze how SQLite uses indexes during `SELECT` statements.
- Avoid redundant indexes; `DROP INDEX` removes unused or duplicate indexes to optimize storage.

The polluted debugging probe showed a second kind of drag. In the fresh session (166 prompt tokens, 98 completion tokens, 1,131 ms), the model went straight to the root cause:

The root cause is that constructing dates with a time string (' 00:00:00') causes
the Date objects to be interpreted in the local timezone, which on the DST
spring-forward day results in one date being 23 hours apart instead of 24. This
leads to the difference in milliseconds being less than 86400000, so Math.floor
returns 0 instead of 1. The code incorrectly assumes each day is exactly 24 hours,
ignoring DST shifts in the local timezone.

In the polluted session (418 prompt tokens, 132 completion tokens, 1,570 ms), earlier turns had speculated about IEEE-754 floating-point drift and BigInt timestamps. Even though gpt-4.1-mini spotted the DST bug, that stale hypothesis lingered in its reply:

The root cause is that March 29, 2026 is a DST spring-forward day in Europe/Rome,
making that day only 23 hours long, so (b - a) is 23 * 3600000 = 82800000 ms
instead of 86400000 ms, causing the division and floor to yield 0. You should not
rely on fixed 86400000 ms per day for date differences spanning DST changes;
instead, calculate differences using UTC dates or count calendar days. The
IEEE-754 / BigInt fix is unrelated and unnecessary here since the issue is due to
DST-adjusted day length, not floating-point precision.

That polluted turn consumed more than twice the total tokens (550 versus 264) and took 39% longer (1,570 ms versus 1,131 ms) on a tiny 418-token prompt. Now picture what happens when the wrong theory isn’t two short messages, but twelve turns of half-written BigInt helper code, failed unit tests, and agent apologies.

Four mechanisms that break long coding conversations #

Once you stop picturing context rot as “the model forgot a random string in filler text,” the real failure modes get much easier to spot and prevent. In production agent sessions, four mechanisms do most of the damage.

Distractor interference and competing instructions

A coding repository is full of near-duplicates. You might have src/billing/retry.ts, src/billing/retry-legacy.ts, tests/billing/retry.test.ts, and three earlier diffs of src/billing/retry.ts sitting in turns 4, 11, and 19.

Every past file read stays in the message history as a snapshot of what the file used to look like. When turn 32 asks for an error-handling update, attention has to reconcile four slightly different versions of that function plus two user messages that changed the requirements halfway through.

Clean needle tests rarely reproduce this. In a clean test, you have one valid policy surrounded by unrelated prose.

In a real repo session, three plausible versions of that policy share the same variable names. Only timestamps or turn order separate the live version from the obsolete ones.

That leftover context triggers subtle regressions in long sessions. The model reintroduces a deleted parameter, reverts a renamed import, or applies a rule you canceled twenty minutes earlier, because those obsolete tokens are still sitting right there in the prompt.

Multi-turn self-anchoring and reasoning drift

Language models generate each new token based on everything that came before it, including their own earlier assistant replies.

When an agent commits early to a wrong diagnosis, like blaming floating-point math for a timezone bug or blaming CORS for a missing auth cookie, those earlier turns become strong priors. Instead of discarding the bad theory, the model often tries to stay consistent with its own earlier explanation.

You see this in coding sessions all the time. The agent writes a workaround for a bug it misdiagnosed, and the test still fails.

Rather than questioning its first assumption, it stacks a second workaround on top of the first. By turn 25, you have three layers of defensive hacks built around a root cause that never existed.

Starting a fresh session breaks that gravitational pull right away. A fresh model sees only the broken code and the failing test, with no history pushing it to defend turn 6’s wrong guess.

Tool-output flooding

In a chat between two people, a turn adds maybe 50 to 200 tokens. In a coding agent loop, a single shell command can dump 15,000 tokens in one second.

The same culprits show up in almost every project:

  • A full npm test orvitest run where one shared mock fails and prints 90 stack traces.
  • A TypeScript compiler cascade (tsc --noEmit ) dumping 400 type errors caused by one missing export.
  • A git diff that drags inpackage-lock.json or a generated OpenAPI schema.
  • Reading a minified bundle, an SVG asset, or a raw JSON fixture into the conversation.

Once that 15,000-token tool_result enters the message array, it stays there. If the agent takes 15 more turns to finish, you pay for those 15,000 tokens 15 more times: 225,000 extra input tokens from one careless tool call.

Even worse, those raw log lines dilute everything around them and push your original task specification thousands of tokens away from the active turn.

Lossy auto-compaction drift

Many coding tools try to hide context growth by running automatic compaction once a thread crosses 75% or 85% of the window. The harness asks a model to summarize the earlier conversation, drops the raw messages, and puts the summary at the top.

Auto-compaction saves you from hitting a hard token error and can rescue a thread clogged with old tool output. Still, summarization is lossy by nature.

When a summarizer compresses 40 turns into 600 tokens, it keeps the broad narrative (“we are refactoring the ledger retry middleware and fixing failing integration tests”). What quietly disappears are the sharp edges:

  • The exact header name X-Ledger-Key .
  • The rule that negative cent amounts must be rejected before hitting the queue.
  • The fact that you already tried library X and rejected it because of a Bun compatibility bug.

After two rounds of automatic compaction in the same thread, the agent is working from a summary of a summary. Each pass strips away a little more precision while the prose still sounds confident.

Here is how a normal coding session transitions from clean work into context rot, and how a deliberate handoff resets it:

Measuring context health in your own harness #

If you build your own agent loop, or wrap LLM calls inside an internal tool, you don’t have to guess when a session is rotting. You can track context health directly from the data every API response already returns.

Four signals tell you almost everything you need to know:

  1. Input token growth per turn: Trackprompt_tokens (orinput_tokens ) on every turn. Steady growth of 300 to 800 tokens per turn is healthy, while a sudden jump of 10,000+ tokens means a tool output flooded the history.
  2. Prompt-cache hit drop: Comparecached_tokens to totalprompt_tokens . If your prefix cache hit rate suddenly collapses to zero mid-session, something mutated an earlier message or tool definition, so every turn now pays full prefill cost and full latency. Seeprompt caching, compression, and compaction in coding agents for how prefix breaks work.
  3. Repeated tool calls: Hash every tool call (name plus normalized arguments). If an agent reads the same file twice without editing it, or runs the same failing test command three times with no diff in between, something is off. Either the context went stale or the agent is stuck in a self-anchored loop.
  4. Output verbosity and constraint creep: Just like our 5-rule SQLite probe crept from 39 words to 44 out of 45 words at turn 18, rising completion length on simple questions often signals the model is hedging against conflicting earlier turns.

Below is a small, zero-dependency ContextHealthMonitor class in Node.js that tracks these signals on every turn and recommends healthy, compact, or reset. It reads the real usage object returned by the API instead of estimating with chars / 4, and it checks both hard token ceilings and duplicate tool calls.

import crypto from 'node:crypto'

export class ContextHealthMonitor {
  constructor({
    warnTokens = 24000,
    resetTokens = 48000,
    floodSpikeTokens = 8000,
    maxDuplicateTools = 2,
  } = {}) {
    this.warnTokens = warnTokens
    this.resetTokens = resetTokens
    this.floodSpikeTokens = floodSpikeTokens
    this.maxDuplicateTools = maxDuplicateTools
    this.turns = []
    this.toolCounts = new Map()
  }

  recordTurn({ usage, latencyMs, toolCalls = [] }) {
    const promptTokens = usage.prompt_tokens ?? usage.input_tokens ?? 0
    const cachedTokens =
      usage.prompt_tokens_details?.cached_tokens ??
      usage.input_tokens_details?.cached_tokens ??
      0
    const completionTokens = usage.completion_tokens ?? usage.output_tokens ?? 0
    const prev = this.turns.at(-1)
    const deltaTokens = prev ? promptTokens - prev.promptTokens : promptTokens
    const cacheHitRatio = promptTokens > 0 ? cachedTokens / promptTokens : 0

    const duplicateTools = []
    for (const call of toolCalls) {
      const signature = crypto
        .createHash('sha1')
        .update(`${call.name}:${JSON.stringify(call.args)}`)
        .digest('hex')
        .slice(0, 10)
      const count = (this.toolCounts.get(signature) ?? 0) + 1
      this.toolCounts.set(signature, count)
      if (count >= this.maxDuplicateTools) {
        duplicateTools.push(`${call.name} (${count}x)`)
      }
    }

    const alerts = []
    if (deltaTokens >= this.floodSpikeTokens) {
      alerts.push(`tool flood spike (+${deltaTokens} tokens in one turn)`)
    }
    if (prev && prev.cacheHitRatio >= 0.6 && cacheHitRatio < 0.2) {
      alerts.push(
        `cache hit collapse (${Math.round(prev.cacheHitRatio * 100)}% -> ${Math.round(cacheHitRatio * 100)}%)`
      )
    }
    if (duplicateTools.length > 0) {
      alerts.push(`repeated tool calls: ${duplicateTools.join(', ')}`)
    }

    let status = 'healthy'
    if (promptTokens >= this.resetTokens || duplicateTools.length >= 2) {
      status = 'reset'
    } else if (promptTokens >= this.warnTokens || alerts.length > 0) {
      status = 'compact'
    }

    const entry = {
      turn: this.turns.length + 1,
      promptTokens,
      deltaTokens,
      completionTokens,
      cacheHitRatio: Number(cacheHitRatio.toFixed(2)),
      latencyMs,
      status,
      alerts,
    }
    this.turns.push(entry)
    return entry
  }
}

When we wire recordTurn() right after each API call, a healthy session stays quiet while a bloated or looping session surfaces in your logs right away. Here is a four-turn trace where a raw test log dumps 14,900 tokens into turn 2 and the agent starts re-reading the same file on turn 4:

turn 1 |  2,100 tok (+2,100) | cache 0.00 |  940 ms | healthy
turn 2 | 17,020 tok (+14,920) | cache 0.11 | 1,410 ms | compact [tool flood spike (+14920 tokens in one turn)]
turn 3 | 17,640 tok (+620)   | cache 0.89 | 1,280 ms | healthy
turn 4 | 26,410 tok (+8,770) | cache 0.08 | 2,190 ms | compact [tool flood spike (+8770 tokens in one turn), cache hit collapse (89% -> 8%), repeated tool calls: read_file (2x)]

Notice how turn 4 catches three separate problems at once: another large tool payload, a sudden cache-hit drop from 89% to 8%, and a duplicate read_file call. Your harness now has an objective signal to intervene instead of letting the loop burn ten more turns.

Four recovery patterns that work #

Good context engineering comes down to two habits: keeping junk out of the main conversation, and resetting cleanly once a thread outlives its usefulness.

Before we look at the code for each pattern, here is how all five options compare across token reduction, prompt-cache impact, risk of dropping a detail, and best fit.

Strategy What changes in the prompt Token reduction Prompt-cache impact Risk of detail loss Best fit
Keep going Nothing removed, turns keep appending 0% High cache hits until prefix breaks None from compaction, rising rot risk Short focused loops under ~25k tokens
Tool-output truncation Cap raw stdout/stderr at the harness boundary, save full log to disk 40% to 80% on noisy commands Preserves prefix completely Low (agent can read slices from saved log) Every coding agent harness by default
Subagent isolation Run noisy search, log triage, or test bisect in a child context 70% to 95% of exploration noise Zero disruption to parent prefix Low to medium (depends on child report schema) Multi-file exploration, dependency audits, flaky test hunting
Structured deliberate compaction Replace older turns with an explicit structured state summary 60% to 85% One-time cache miss, then new smaller prefix Medium (summary can drop subtle rules if unverified) Mid-feature milestones where architecture is settled
Fresh-session handoff ( HANDOFF.md ) Close the thread, start a new session with a concise on-disk brief 90% to 99% (98.9% in our benchmark) Clean new prefix from turn 1 Low when backed by repo files and tests Phase switches, after 2 failed bug guesses, or past ~40k tokens

Now let’s build the four active recovery patterns with concrete code and templates.

Pattern 1: Tool-output truncation at the harness boundary

The cheapest way to prevent context rot is to stop giant tool results from ever entering the chat.

When your harness runs a shell command like npm test or rg, don’t pass raw stdout straight back as the tool_result. Instead, handle the output at the boundary:

  • Save the full output to a temporary log file on disk.
  • Keep the exit code, the first few lines, and the last few lines (where test summaries and stack trace roots usually live).
  • Extract lines matching failure markers.
  • Hand back the log file path so the model can inspect specific lines, like lines 400 to 460, if it needs to.

Here is a Node.js helper that implements this boundary cleanly. Normal short outputs pass through untouched, and only payloads above a configurable character threshold get summarized.

import fs from 'node:fs/promises'
import path from 'node:path'
import crypto from 'node:crypto'

export async function formatToolOutput({
  command,
  exitCode,
  stdout = '',
  stderr = '',
  maxChars = 3200,
  logDir = '/tmp/agent-tool-logs',
}) {
  const combined = [stdout, stderr].filter(Boolean).join('\n').trim()
  if (combined.length <= maxChars) {
    return `exit_code: ${exitCode}\n${combined}`
  }

  await fs.mkdir(logDir, { recursive: true })
  const id = crypto.randomBytes(4).toString('hex')
  const logPath = path.join(logDir, `tool-${id}.log`)
  await fs.writeFile(logPath, combined, 'utf8')

  const lines = combined.split('\n')
  const head = lines.slice(0, 15)
  const tail = lines.slice(-25)
  const errorLines = lines
    .filter((line) => /\b(FAIL|ERROR|Error:|AssertionError|TS\d{4}:)\b/.test(line))
    .slice(0, 20)

  const omitted = Math.max(0, lines.length - head.length - tail.length)

  return [
    `command: ${command}`,
    `exit_code: ${exitCode}`,
    `full_log: ${logPath} (${lines.length} lines, ${combined.length} chars)`,
    '',
    '--- key failure lines (max 20) ---',
    errorLines.length > 0 ? errorLines.join('\n') : '(none matched)',
    '',
    '--- first 15 lines ---',
    head.join('\n'),
    '',
    `... [${omitted} lines omitted; read specific line ranges from ${logPath} if needed] ...`,
    '',
    '--- last 25 lines ---',
    tail.join('\n'),
  ].join('\n')
}

Picture what this one function saves over a 25-turn debugging session. A single 55,000-character vitest failure (around 14,000 tokens) shrinks to roughly 650 tokens while keeping every failing assertion name, the final summary, and the path to the full log.

If the agent needs lines 310 to 350 of the stack trace, it can read just those 40 lines instead of dragging all 1,800 lines along for the next twenty turns.

Pattern 2: Subagent context isolation for noisy tasks

Some tasks are naturally messy. Finding every caller of an internal function across a monorepo, tracing how an auth cookie flows through six middleware files, or grepping a 200-megabyte nginx access log all require dozens of dead-end reads.

If your main coding agent runs that exploration inside its primary thread, you inherit all 30,000 tokens of dead ends before writing the first line of code.

Subagent isolation splits research from editing. The main agent spawns a read-only child agent with a tight prompt: “Find every file that reads X-Ledger-Key or sets retry backoff delays. Return only a list of file paths, line numbers, current values, and any conflicting defaults.”

The child agent can spend 25,000 tokens reading 18 files, chasing two wrong folders, and inspecting tests. When it finishes, it returns a 350-token report to the parent, and all 25,000 tokens of raw search clutter vanish the moment the child exits.

This pattern works especially well for three jobs:

  • Codebase discovery before editing starts.
  • Triaging a noisy CI log or flaky test failure.
  • Reviewing a finished diff with fresh eyes, free from self-anchoring to the reasoning that produced it.

Skip subagents for a tiny two-file edit where you already know the exact lines to change. Spawning a child adds startup latency and loses implicit nuances unless you put them in the brief, so save isolation for high-volume, low-signal reads.

Pattern 3: Structured deliberate compaction

Automatic compaction usually triggers too late, right when the context is already 85% full and the agent has spent ten turns going in circles. A generic “summarize this conversation” prompt also lets the summarizer decide what matters, and subtle constraints vanish.

Deliberate compaction works much better. You trigger it at a natural milestone, like right after a migration passes or a module’s tests go green, and force the summary into fixed, verifiable sections so key details survive.

Here is the structured compaction prompt I use when I want to stay in the same thread while dropping old tool logs and dead-end attempts:

 implementation and produce a structured compaction checkpoint.
Do not omit exact values, file paths, or rejected approaches.

## 1. Active goal
One or two sentences describing what "done" means for this task.

## 2. Hard constraints (never violate)
Bulleted list of exact rules, config values, header names, schema limits,
and style rules stated by the user. Quote exact identifiers.

## 3. Verified facts and decisions
What we confirmed directly from code or command output, plus why we chose
the current design.

## 4. Rejected approaches (do not retry)
Dead ends we already tested and why they failed.

## 5. Files modified so far
Exact relative paths with a one-line note of what changed in each.

## 6. Current verification state
Last command run, exact pass/fail count, and any remaining failing test names.

## 7. Next concrete step
The single next action to take after compaction.

Section 4 (Rejected approaches) is the secret weapon here. Without it, a compacted session often repeats a broken fix you already ruled out twenty minutes ago because the failed attempt dropped out of the summary.

Keeping two lines like “Do not use BigInt for date diffing. The bug is Europe/Rome DST 23-hour days, not float precision” stops the agent from hitting the same wall twice.

Pattern 4: Fresh-session handoff via an on-disk HANDOFF.md

Structured compaction still leaves you inside the same conversation thread. Some tools retain hidden provider-side state or partial message blocks you can’t inspect.

When a conversation crosses 35k to 45k tokens, or after two wrong debugging guesses in a row, the cleanest fix is a hard reset. You write a short handoff file to disk, close the old session, and start a new chat that reads only that file.

In our benchmark, moving from 18 noisy turns to a fresh handoff dropped prompt tokens from 10,712 down to 116 (a 98.9% reduction). It also restored baseline latency (1,269 ms down to 1,082 ms) and pulled the reply comfortably back inside the word limit.

Here is a real-world HANDOFF.md written for a payment-ledger retry task so a fresh session can pick up in ten seconds with zero dead-end baggage:


## Goal
Update the ledger client retry middleware to match the active production policy
and fix the off-by-one day calculation bug across DST transitions.

## Hard constraints
- `retry_backoff_ms`: `1450`
- `max_retries`: `5`
- `idempotency_header`: `X-Ledger-Key`
- `circuit_open_sec`: `42`
- `rejects_negative_cents`: `true` (must reject before enqueueing)
- Do not change the public signature of `calculateBillingDays(startIso, endIso)`.

## Confirmed root cause (do not re-diagnose)
`new Date(dateStr + ' 00:00:00')` parses in local timezone (`Europe/Rome`).
On 2026-03-29 (spring forward), the day is 23 hours (82,800,000 ms), so
`Math.floor((b - a) / 86400000)` returns `0` instead of `1`.
Fix by parsing as UTC midnight (`Date.UTC(y, m - 1, d)`).
Ignore earlier IEEE-754 / `BigInt` ideas; floating-point precision is not involved.

## Files in scope
- `src/ledger/retry-policy.js` (updated constants, needs negative-cents guard)
- `src/ledger/billing-days.js` (needs UTC fix)
- `tests/ledger/billing-days.test.js` (add 2026-03-29 Europe/Rome regression test)

## Last check
`node --test tests/ledger/*.test.js` -> 11 passed, 2 failed
(`rejects negative cents before retry`, `counts 1 day across Europe/Rome DST`)

## Next step
1. Add the negative-cents guard in `src/ledger/retry-policy.js`.
2. Switch `src/ledger/billing-days.js` to `Date.UTC`.
3. Re-run `node --test tests/ledger/*.test.js`.

If you run your own agent script, bootstrapping a fresh session from HANDOFF.md takes twenty lines of JavaScript. The function below reads the handoff file and builds a clean two-message array with zero prior turns attached.

import fs from 'node:fs/promises'

export async function createFreshSessionMessages({
  systemPrompt,
  handoffPath = 'HANDOFF.md',
  openingInstruction = 'Read the handoff carefully, verify the constraints, then execute Step 1.',
}) {
  const handoff = await fs.readFile(handoffPath, 'utf8')
  return [
    { role: 'system', content: systemPrompt },
    {
      role: 'user',
      content: [
        'Fresh session started from verified handoff state.',
        'Treat the handoff below and the current files on disk as the only source of truth.',
        '',
        handoff.trim(),
        '',
        openingInstruction,
      ].join('\n'),
    },
  ]
}

Once the task finishes, delete HANDOFF.md (or keep it gitignored in .tmp/handoff.md) so temporary session state never pollutes your repository commits.

Verifying what survived compaction before editing continues #

Never assume a summary or handoff captured every important constraint. One of the easiest ways to waste thirty minutes is to compact a long session, immediately tell the agent “great, keep going,” and discover five edits later that compaction dropped an edge case.

Before letting an agent modify files after compaction or a fresh handoff, spend one cheap turn on a survival check.

Send three direct questions in plain text:

Before editing any files, reply in 6 lines or fewer with:
1. The exact hard constraints and config values you must preserve.
2. The exact files you plan to edit.
3. Any rejected approaches you will avoid.

That check costs a couple hundred tokens and takes about one second. Compare the reply against your real expectations.

Here is a concrete example of what it catches. Suppose your pre-compaction thread had our five-field retry policy (retry_backoff_ms: 1450, max_retries: 5, idempotency_header: "X-Ledger-Key", circuit_open_sec: 42, rejects_negative_cents: true).

After auto-compaction, you run the survival check and the model answers:

1. Retry backoff 1450ms, max 5 retries, circuit breaker 42s, custom ledger header.
2. src/ledger/retry-policy.js and tests/ledger/retry-policy.test.js.
3. None noted.

Look at what quietly disappeared in that single compaction pass:

  • The exact header string "X-Ledger-Key" turned into the vague phrase “custom ledger header”, so next turn the agent may inventX-Idempotency-Key and break production clients.
  • rejects_negative_cents: true vanished completely.
  • The rejected approach list is empty.

Catching those omissions before the agent writes code takes ten seconds to fix. Catching them after three commits and a broken staging deploy takes an hour.

Move permanent rules out of chat history

Even better, stop storing permanent project rules inside chat history at all. Conversation memory is volatile by definition.

Anything that must survive every turn, every compaction, and every fresh session belongs in a file on disk:

  • Architecture rules and coding conventions belong in AGENTS.md (or a scoped module README).
  • Behavioral requirements belong in failing unit tests (node --test ,vitest ,pytest ).
  • Exact configuration constants belong in typed schemas or config files the agent can read on demand.

When your constraints live in tests and repo files, compaction can’t lose them. Even if a summary forgets rejects_negative_cents: true, the test suite fails the second the agent breaks it.

How I manage long conversations #

I used to treat a coding-agent thread like a day-long Slack channel, keeping one conversation open for hours while jumping across three unrelated bugs. That habit always produced the worst results: slower replies, rising token bills, and agents that felt weirdly stubborn after turn 30.

Now I treat every conversation as a short-lived workspace scoped to one clean unit of work. It’s the same mindset I use when juggling multiple threads in too many agent conversations.

Here is the decision flow I follow while working:

Four thresholds I use every day

In practice, my rules break down into four clear actions:

  • Keep going when the thread is under 25k to 30k tokens, we’re iterating tightly on one feature or module, the agent’s mental model is accurate, and prompt caching keeps replies fast. Resetting too early wastes time rebuilding context that is still clean and useful.
  • Isolate with a subagent whenever the next step requires reading ten unfamiliar files, grepping across a large dependency, or digging through a huge error log. That keeps my main editing thread tiny and sharp.
  • Run deliberate structured compaction at a clean checkpoint during a longer feature. Use it once the architecture is settled, recent tests pass, and the only dead weight left is 20 turns of earlier diffs and build logs, then run the one-turn survival check right after before approving the next edit.
  • Close the thread and start fresh with HANDOFF.md whenever the session crosses a clean boundary or starts fighting me.

I trigger that hard reset without hesitation in three situations:

  1. Right after finishing exploration and planning, before writing the first line of production code.
  2. After two failed attempts to fix the same bug, since self-anchoring almost always locks the thread into patching the wrong theory.
  3. Whenever the model starts repeating mistakes, re-reading files it just opened, or ignoring a rule we already agreed on.

When resetting is the wrong move

Resetting or compacting isn’t always the right fit.

If I’m in a deep design brainstorming session, weighing subtle trade-offs across 15 back-and-forth turns, forcing an early reset often flattens the nuance we just built up. Until the design settles into concrete decisions I can write into a markdown spec, staying in the live conversation produces better pushback and cleaner synthesis.

For a quick 5-turn task too (fixing a typo, tweaking CSS, writing one small utility function), writing a HANDOFF.md or spawning a subagent adds pure overhead. I just finish the job and close the thread.

Long context windows are a great safety net when you genuinely need to inspect a massive log file or cross-reference five large documents in a single pass. For day-to-day coding, though, smaller and cleaner contexts beat giant cluttered histories every time.

If you keep your active prompt lean, leave raw tool logs on disk, and verify what survives compaction, your sessions stay fast and accurate. And the moment a thread starts fighting you, start fresh.

Want me to talk about your product? You can sponsor this site.

── more in #large-language-models 4 stories · sorted by recency
── more on @openai 3 stories trending now
sponsored brought to you by zahid.host 4,200+ EU-deployed projects
reading about agents? ship yours in a single git push.

Run your AI side-project on zahid.host

EU-based hosting, git-push deploys, automatic HTTPS, no cold starts. Free tier with a custom domain — perfect for shipping the agent you just read about.

$git push zahid main
→ Live at https://your-agent.zahid.host ✓
Get free account → Pricing
from €0/mo · no card required
LIVE [news/context-degradation-…] indexed:0 read:32min 2026-11-30 · —