writingmaclulich.com

Context engineering for coding agents: five changes that keep sessions small

Five changes that keep your coding agents’ context small

  1. Start a fresh session for each unit of workPasting work into one running session grew mine to a 518K-token prompt
  2. Set your agent’s compaction limit yourselfThe default waits until a 1M window is nearly full. I compact at 300K, because 200K thrashed
  3. Cap how many model calls one turn can makeOver ten days, turns past 150 calls cost me about $108. Every other turn together cost $8.47
  4. Trim what a cheap agent loads before its first taskDropping skills and unused MCP servers took a fresh turn from 47K tokens to 10K
  5. Let code, not a model, write each task’s briefMine comes from rules the project committed, plus at most five lessons, each added only after the same rule failed twice
The numbers come from the logs of my own coding agents running in parallel, including two cheap agents over ten days.

Long turns, not token prices, drove my bill

If you run AI coding agents for hours at a time, or several at once, this is for you. I run several in parallel under Rigby, my own harness: a small supervisor that starts them, passes messages between them and merges their finished work.

One agent, the head (Claude Opus), plans the work and hands out units of it. The others, which I call lanes, do the units: Codex on one, a cheap model such as DeepSeek on another.

The most expensive lesson was about long turns, not token prices. A turn is one instruction and all the model calls an agent makes to finish it.

Turns that ran past 150 model calls cost thirteen times all the others

Every turn within 150 calls$8.47
The 134 turns past 150≈ $108
Two cheap DeepSeek lanes over ten days. Those long turns were about 70% of all calls and over 90% of the spend.

One of those turns read the same test file 404 times over three hours, and no change to the prompt wording fixed it.

Drew Breunig’s write-up of his AGNTCon talk, The State of Context Engineering, calls that context inertia. He argues that the work of assembling an agent’s context keeps moving out of model calls and into deterministic code.

Nearly every tactic he lists ended up in my own harness, usually after a measurement showed me that a model couldn’t be trusted to do it.

The head plans, the lanes do the work, and code decides what each one sees

  1. Headplans the work and writes each unit
  2. Rigbybuilds the brief, starts fresh sessions, merges
  3. Lanedoes one unit in one session
  4. Reviewerchecks it against the same brief
Simplified. Everything below is a decision Rigby makes in code, so no model has to remember to make it.

Breunig’s tactics, and where each one lives in my setup

TacticWhat the harness does
QuarantineA producer lane gets a fresh session for every unit, and the reviewer starts fresh from a brief.
SummarisationThe head compacts at 300K tokens instead of near its 1M window.
PruningProducer sessions aren’t pruned. They’re thrown away after each unit.
Tool loadoutCheap lanes get no skill list and one MCP server, so a fresh turn starts at 10K tokens, not 47K.
OffloadingThe plan, messages and history live in git, a mailbox and a roadmap, which makes throwing a session away safe.
AugmentationEvery unit carries a brief built from committed rules. No model writes it.
Context inertiaA 150-call cap on a producer’s turn, and a reset when a lane loops.

I’ve written about how work is handed over and how the agents clean up after themselves. The change that mattered most for context was how long a session is allowed to live.

Start a fresh session for each unit of work

The most useful rule I have is that a producer lane, one that writes the code, gets a fresh session for each unit of work. I didn’t start there.

Early on, a unit sent to a busy lane was pasted into its running turn. That turn never ended between units, so no reset was ever due.

Pasting work into a running turn grew one session to a 518K-token prompt

One session for everything, against one session per unitTop: a single long bar split into sixteen pieces, labelled six work units, four reviews and six messages in one session, ending at a 518K-token prompt. Bottom: five short separate bars labelled unit, review, unit, correction and unit, each one a fresh session that starts from the unit's brief.Before: units pasted into a running turn6 work units, 4 reviews and 6 messages in one session518K-token promptAfter: one unit, one sessionunitreviewunitcorrectionuniteach starts fresh from its brief, and nothing is pasted into a busy turn
The top bar is the real case. The bottom bars are illustrative sizes, not measurements.

Now Rigby decides when a lane starts over, from its own records rather than from the screen or the model’s judgement.

A unit delivered since the lane’s last reset stays in that session, and new units wait behind it. Once the lane reports the unit finished and its turn has ended, the next wake, a doorbell that tells the lane to check its mailbox, starts a fresh session.

Reviews go to the front of the queue, then corrections, then new work.

Before (simplified)

# a new unit of work arrives for a lane
paste_into_lane(unit)   # lands in whatever turn is running, so the session never ends

After (simplified)

# a new unit of work arrives for a lane
if lane.has_open_unit():        # sent since its last reset, not finished
    hold(unit)
elif lane.finished_a_unit() and lane.turn_ended():
    reset(lane)                 # /clear, /new or a fresh process
    wake(lane)                  # a doorbell: "check your mailbox"

The wake itself carries no content, so nothing stale is ever typed into a session that’s busy with something else.

This is Breunig’s quarantine, and close to Anthropic’s Memento pattern, applied where it costs least: the end of a unit, when everything worth keeping is already in a commit or a mailbox record.

So the rule I work to is one unit of work, one session. If your agents run for hours, end the session when a unit is committed and start the next from a short written brief.

Set a compaction limit well below the window

The head is the exception. It holds the plan, so it never gets reset, and it compacts instead, which means summarising its history to free up room.

Claude Code and Codex compact near the model’s window by default. On a 1M-token model, that lets a head carry close to a million tokens of history into every call.

Breunig starts watching his own sessions at around 200–300K tokens. The Gemini 2.5 report saw agents start repeating old actions past roughly 100K.

300K came from measuring what happened on either side of it

200Kthrashed: the fixed context and summary refilled the window within three turns
300Kchosen: about 100 calls between compactions
500Ka median of about 300K tokens per call, across 32,000 calls
1M defaultcompaction waits until the window is nearly full
Measured on my head agents. Your fixed context will move these numbers.

A freshly compacted head restarts at 130–170K tokens, which is why 200K had no room to work. A 300K limit should cut the head’s input by around a fifth.

Both runtimes have a documented setting

# Claude Code
CLAUDE_CODE_AUTO_COMPACT_WINDOW=300000 claude

# Codex
codex -c model_auto_compact_token_limit=300000

If you run long agent sessions, set this yourself. The default lets the window fill almost to its limit before anything is summarised.

Check your agent’s fixed context first, since a freshly compacted session has to fit under the limit with room left to work.

Cap the model calls one turn can make

Compaction did nothing for the turns that cost the most. Context inertia, in Breunig’s words, is a model hyper-focusing on a hypothesis and pursuing it long after it should stop, and the 150-call chart near the top is what it cost me.

The worst turn I traced was a code review that spent nearly three hours reading one test file in the same ten slices.

One review read the same ten slices of a test file 404 times

404
full passes over one test file
19
compactions, one every nine minutes, with no break in the loop
1,095
calls after which the prompt sizes repeated exactly
From the agent’s own log. There were no edits, no tests and no reasoning text between the reads.

Neither of my two loop guards noticed. Both look for the same call repeated back to back, and every call here asked for a different slice.

Two mechanisms handle it now, both outside the model. OpenCode has a per-agent step limit, so its lanes run with agent.build.steps set to 150.

Claude Code has no step limit in an interactive session. Its lanes get a PreToolUse hook that counts the current turn’s model calls from the session transcript.

The lane’s settings

{
  "hooks": {
    "PreToolUse": [{
      "hooks": [{
        "type": "command",
        "command": "python3 turn_cap.py 150",
        "timeout": 5
      }]
    }]
  }
}

At 150 the hook refuses further tools, with a reason telling the model to report what it finished and stop. Ten calls later it ends the turn outright.

What the hook returns at the limit

{
  "hookSpecificOutput": {
    "hookEventName": "PreToolUse",
    "permissionDecision": "deny",
    "permissionDecisionReason": "This turn has made 150 model calls;
      the lane's limit is 150. Call no more tools. Reply with what
      you finished, what is left ..."
  }
}

I tested it live with the limit set to three. The third call was refused, and the model listed what it had done and what was left, then ended the turn.

When a lane loops on a single command, Rigby resets it, and the fresh session gets one line about what happened:

your last session was stopped after repeating: <command> . It returned the same
output every time. That result IS the answer: do not run it again; act on it.

The capitals are a small confession. Breunig is right that shouting in a prompt usually means you’re fighting what the model was trained to do.

The shouting isn’t what does the work here. The reset is, and if the same lane loops twice within an hour, the head is told to split or reassign the unit.

If your agent has no step limit, count a turn’s model calls in a hook and stop it at a number you choose. Mine is 150, and I look hardest at the turns that run long, because that’s where both the quality and the money go.

Trim what a cheap agent loads at startup

A cap limits how far a turn can run. It does nothing about where a fresh one starts, which turned out to be a problem of its own.

Breunig’s example of context clash is an enterprise that loaded 600 skills per engineer at startup. Mine was smaller, but the same shape.

Dropping skills and unused MCP servers took a fresh turn from 47K tokens to 10K

Before47Kincluding a list of 105 skills, about 11K tokens, with skills for slide decks and spreadsheets
After10Kno skill list, and only the supervisor’s MCP server
Measured on a cheap OpenCode lane before it had done any work.

A cheap lane’s settings, in OpenCode and in Claude Code

// OpenCode, cheap lane
{
  "permission": { "skill": "deny" },
  "mcp": { "every-server-but-the-supervisor": { "enabled": false } }
}

# Claude Code, cheap lane
claude --strict-mcp-config --mcp-config '{"mcpServers": {"supervisor": {...}}}'

At cache-hit prices a 47K prefix is cheap per call, so the bill isn’t the main reason to do this. Every skill description is one more thing for the model to weigh on a task that will never need it.

Measure the prompt your agent starts a task with, then remove what a lane will never use.

Let code write the handoff, not a model

A lane’s first message matters as much as what it loads at startup. I covered this in my post on handing work to coding agents, so briefly.

It’s a short brief that Rigby builds from rules the project has committed, matched to the files the unit touches. The reviewer gets the same contract, rebuilt from what the commit actually changed.

The head decides the work, but it can’t leave the written rules out. Past review findings reach the brief through a lessons loop.

Breunig predicts that memory is where the problem moves next, because precise memories pile up and start to conflict. I built the loop with that in mind.

A review finding has to repeat before it becomes a lesson

  1. Findingrecorded by rule and code area when a review blocks
  2. Lessonpromoted when the same rule fails twice in one area
  3. Briefcarries at most five lessons
  4. Retiredwhen the area’s code is deleted or goes quiet
How the lessons loop works, simplified.

If you feed past mistakes back to your agents, make a finding repeat before it goes in, cap how many go in at once, and retire the ones whose code is gone.

How far to trust it

Measured on one setup, with three problems still open

  1. Your numbers will differYour fixed context moves the compaction limit. The cut of around a fifth that I expect from 300K is a projection, and the short session bars in the diagram are illustrative sizes
  2. The head never resetsIt compacts instead, so a head that fixates on a wrong idea can carry it across compactions. Most of its state already lives on disk, which would make a reset safe, but not all of it does yet
  3. Lessons haven’t proved themselvesMy two active projects hold no promoted lessons at all. That’s either the bar working or the bar being too high, and I don’t know yet which
  4. My own instructions still clashMy Claude Code lanes still load my personal skill list and global instructions, including a description of an older agent layout that contradicts the current one

A cheap lane on a non-Anthropic model doesn’t need any of that. The next step is a configuration holding only the supervisor’s hooks and the project’s instructions, then measuring the starting prompt before and after.

Try it on one agent this week

Start with one agent, and measure before you change anything:

  1. Count the model calls in each turn from the session transcript, and read the longest turns first.
  2. Measure the prompt your agent starts a task with, then remove the skills and MCP servers a lane will never use.
  3. Set the compaction limit yourself, well below the window. Mine is 300K on a 1M window, and 200K was too low for my fixed context.
  4. Cap calls per turn outside the model, with a step limit or a hook. Mine is 150.
  5. End a session when its unit is committed, and start the next from a short brief built from your project’s written rules.

The settings for items 2 to 4 are in the sections above, in the lean loadout, the compaction limit and the turn cap.

How code decides what each session sees

I found most of these by measuring first: the share of spend by turn length, the size of a fresh turn’s prompt, and the point where compaction thrashed. Then I moved the decision into Rigby.

Code decides what a session sees, how big it grows and when it ends

  1. BriefBuilt from committed rules and matched to the files the unit touches
  2. Fresh sessionOne per unit, started from Rigby’s records, with a lean loadout
  3. Caps150 model calls per turn, and the head compacts at 300K
  4. ResetWhen the unit is finished, or when a lane loops on one command

The rule behind all of it is that if a model has to remember to manage its own context, sooner or later it won’t.

Breunig’s point that better context is the cheap lever, compared with a bigger model or more thinking time, is what my bills show too. His full write-up is worth reading.