Context and long-running agents

  • Advanced
  • 35 min
  • Lesson 3 of 7 in Harness engineering
  • Last verified

Open slides(22 slides)

Before you start

You will be able to

  • Explain context rot and keep a long session productive with a context budget, tool-result clearing and compaction.
  • State what a compaction must keep and what it may drop, and name two ways it goes wrong.
  • Design the handoff artefacts for work that spans many sessions: a restricted-field feature list, a progress file, version control and a startup routine.
  • Explain why instruction files should be short maps and why knowledge the agent needs must live where it can read it.

Story

It is a three-day account clean-up, and every morning a fresh agent session picks it up with no memory of the last one.

The note left for Vihaan on day two is a single line: “Carry on.” By ten he has redone the same batch of accounts and skipped the next.

What should the note have said?

Concept

A model has a fixed amount of text it can work from, and a run that lasts hours or days will not fit in one window. Two different problems follow. Inside one session, the window fills with logs, dead ends and stale file contents, and the model works worse. Across sessions, each new window starts blank, so the agent cannot know what the last one finished. The harness answers the first by budgeting what goes into the window and the second by writing state down in places that outlive a session. This lesson builds on context engineering and memory and takes the harness view.

Why It Matters

Left alone, long agents fail in the two ways the first two lessons described: doing too much at once and leaving half-finished work, or a fresh session seeing earlier progress and declaring victory. Both are cheaper to prevent with a few files and a routine than to fix with a bigger window. Interviewers ask about this to see whether you treat memory as an engineering problem with failure modes, not a feature you switch on.

Mental Model

Vihaan on the second morning is a fresh model with an empty window. The handoff note is the only thing that carries the job from one session to the next. A one-line note is a poor handoff: it names no goal, no finished work and no next step. A good handoff note is a short, structured page that the next session reads first, and it is kept in one place and updated at the end of every session. The harness’s job is to make that page, and to make the routine of reading it automatic.

Context rot and the budget

Anthropic’s engineering team (29 September 2025) describes context rotContext rotHow well a model uses its context falls as the window fills with more tokens, even before the limit. Treat the window as a finite attention budget.Open the glossary entry plainly: the more tokens the window holds, the less accurately the model recalls what is in it. They frame this as a finite attention budget that each new token draws down. The practical rule is to put the smallest set of high-signal tokens in front of the model, not the largest that fits.

Three cheap moves protect the budget, in rising order of cost:

  1. Cap what enters. Truncate and offload large tool outputs, as in the previous lesson.
  2. Clear old tool results. Once a tool has been called deep in the history, the agent rarely needs the raw result again. Anthropic calls this one of the lightest forms of compaction.
  3. Compact the conversation. Summarise it as it nears the limit and continue in a fresh window seeded with the summary.
Diagram: Three moves protect the window, in rising order of cost.

1 Cap what enters
truncate, offload big outputs

2 Clear old tool results
lightest form of compaction

3 Compact the conversation
summarise, continue in a fresh window

Diagram summary: Three moves protect the window, in rising order of cost. Capping what enters costs almost nothing and prevents the most waste, clearing old tool results is next, and compacting the whole conversation is the heaviest option and the last resort.

A worked example with invented numbers shows why the first move matters most. Suppose the window is 200,000 tokens, you reserve 16,000 for output, and the fixed prompt and tool definitions take 12,000. If you start compacting at 70 percent of the 184,000 that remain (about 129,000 tokens), then about 117,000 of that is room for steps. At about 3,000 tokens per tool step that is roughly 39 steps. If tool outputs are uncapped at about 15,000 tokens a step, it is fewer than eight. The numbers are made up; the proportion is the point.

StepTokensRoom for stepsSteps before compaction
Window 200,000 −- output 16,000184,000
Compact at 70%129,000
Minus fixed prompt and tools 12,000117,000
Capped tool outputs, about 3,000 per stepabout 39
Uncapped tool outputs, about 15,000 per stepfewer than 8

What a compaction keeps

Anthropic’s phrase is that the art of compaction lies in choosing what to keep and what to discard. A reasonable policy, as a judgment and not a standard:

  • Keep as written: the user’s goal, the constraints and acceptance criteria, key decisions and the reason for each, open to-dos, the files touched, the last failing command and its error, and any identifiers the model will need.
  • Replace with a pointer: raw tool output (“saved to logs/test-run-14.txt”), repeated reads and exploration that led nowhere.
  • Know the risks. A summary can lose a detail that the model then reinvents with confidence. It can lose negative knowledge, such as “we tried that and it failed because of this”. And changing early context can defeat prefix caching, so compact in one step rather than rewriting history every turn.
Diagram: Compaction splits the history.

Long history

Keep as written:
goal, constraints, decisions and reasons,
open to-dos, files touched, last failing command

Replace with a pointer:
raw tool output, repeated reads, dead ends

New window seeded with the summary

Durable record on disk is the source of truth

Diagram summary: Compaction splits the history. Goals, constraints, decisions and open work are kept as written, bulky or abandoned material becomes a pointer to a file, and the new window starts from that summary. The durable record on disk, not the summary, is what to trust.

For very long jobs there is a second option: start a new window from a short handoff file instead of compacting again and again, because, in our judgment, repeated summaries can compound their own errors. Either way the durable record, not the summary, is the source of truth.

Handoff artefacts for work across sessions

Anthropic’s post on long-running agents (26 November 2025) describes a pattern worth knowing in detail because every part of it answers a failure they observed.

What they observedWhat they added
The agent tried to do too much at once and ran out of context mid-feature, leaving half-built, undocumented workOne feature at a time; commit with a descriptive message and update the notes before ending
A fresh session saw progress and declared the job finishedA feature list written up front, every entry starting as failing
Features were marked complete without end-to-end testingPrompting the agent to test as a human user would, with browser automation
Each session spent time working out how to start the appAn init.sh script and a fixed startup routine

They used two prompts with the same system prompt, tools and harness. An initializer session writes the environment: the init script, a progress file, a first commit and a feature list. Every later coding session works one feature and leaves things clean. The feature list was JSON, because, they report, the model was less likely to change structured JSON inappropriately than Markdown. In their example for a chat-app clone it held more than 200 features, and the agent was told to change only each entry’s passes field.

JSON

{
  "category": "functional",
  "description": "New chat button creates a fresh conversation",
  "steps": ["Open the app", "Click New chat", "Verify an empty conversation appears", "Verify it is listed in the sidebar"],
  "passes": false
}

Remember the earlier correction: “only change passes” is an instruction in a prompt, not a lock. A mechanical version would have the harness itself reject any edit to the other fields, or keep the list where the agent can write only the status.

The startup routine is the other half. Each coding session checks the working directory, reads the git log and the progress file, reads the feature list and picks the most important unfinished item, runs the init script, and does a basic end-to-end check before adding anything new. That catches a broken base before you build on it, and it costs far fewer tokens than rediscovering the state.

Diagram: Every coding session follows the same routine.

no

yes

New coding session starts

Check the working directory

Read the git log and progress file

Read the feature list,
pick the top unfinished item

Run the init script

Basic end-to-end check passes?

Fix the broken base first

Build one feature

Test it end to end like a user

Commit, update the progress file,
flip passes to true

Diagram summary: Every coding session follows the same routine. It reads the repo’s recorded state, brings the app up and checks it still works before adding anything. Then it builds one feature, tests it end to end, and leaves the notes and commit history clean for the next session.
Diagram: An initializer session creates the init script, the failing feature list, the progress file and a first commit.
Repo and filesCoding sessionInitializer sessionHarnessRepo and filesCoding sessionInitializer sessionHarnessloop[each later session]first prompt: set up the environmentinit script, feature list (all failing), progress file, first commitcoding prompt, same toolsread git log, progress file and feature listrun init script and a smoke testbuild one feature, test it end to end, commit, update progress
Diagram summary: An initializer session creates the init script, the failing feature list, the progress file and a first commit. Each later coding session reads that state, checks the app still works, builds and tests one feature, then commits and updates the notes.

Anthropic also noted two limits: their browser tool could not see native alert dialogs, and they could not say whether one general agent beats separate testing or QA agents.

Instruction files are maps, and knowledge must be readable

Osmani’s test for an instruction file, as in the first lesson, is that every line in a good AGENTS.md should trace back to a specific thing that went wrong. That is a reason to keep the file short: a long one crowds the window, makes every rule look equally important, and goes out of date. A common response is to keep the instruction file as a short map that points into a structured documentation folder, where the detail lives and is loaded when needed. That is progressive disclosure again, applied to documents.

Diagram: The instruction file stays short and points into a structured documentation folder.

AGENTS.md
short map

docs/architecture

docs/plans

docs/specs

docs/decisions

Loaded only when the task needs it

Diagram summary: The instruction file stays short and points into a structured documentation folder. The detail is loaded only when a task needs it, which keeps the window small. This is progressive disclosure applied to documents.

The same reasoning gives a second rule: what the agent cannot read does not exist for it. A decision made in a chat thread or in someone’s head has to be written into the repository as plain, versioned text. InfoQ’s summary (21 February 2026, a secondary account of OpenAI’s report) describes a documentation directory of maps, execution plans and design specifications treated as the agents’ single source of truth, with linters and CI checking that the documents stay consistent and cross-linked. Treat that as one team’s reported approach.

Memory inside a harness follows the same discipline. Files that are read at the start of a session and written at the end suit small, high-value state such as conventions and decisions. Scope them: Microsoft’s documentation describes session-scoped file access that fails closed, refusing to fall back to a shared folder when no session or scope is available. Write only facts you are willing to have read again, never raw secrets, and give them a way to expire.

Real-World Application

A migration agent that moves 200 database tables over three days. The first session writes tables.json with every table, its status set to pending and the checks that prove it migrated, a progress.txt, a startup script that opens the connection and runs a smoke test, and a first commit. Each later session reads those, picks one pending table, migrates it, runs the checks, flips only that table’s status, commits and writes a line to the progress file. If the process crashes, the next session starts from the files, not from memory. The agent’s own claim that a table is migrated is never the evidence; the checks are.

Interview Perspective

Expect: “How does an agent work on a task that takes days?” “What should a compaction keep?” “Why not one very long instruction file?” “An agent working through a long checklist keeps declaring the job finished halfway. What do you change?”

A strong answer names both problems (rot within a session, amnesia across sessions), proposes budgeting and clearing for the first and durable artefacts for the second, and says what the startup routine does. Common mistakes: relying on a bigger window; compacting every turn; letting the agent edit its own success criteria; using a Markdown checklist as the source of truth; declaring done on unit tests for a user-facing feature; starting a session without a smoke test.

Provenance: Common industry pattern. These are typical of agent-engineering interviews; none is verified for a named company.

Practice Questions

  • Basic: Why does a long-running agent need an initializer step?
  • Intermediate: Design the startup routine and handoff artefacts for an agent that works for three days on a data migration.
  • Advanced: An agent’s instruction file has grown to 600 lines, and success fell after the last model upgrade. Diagnose it and restructure it.
  • Product-Company: A coding agent works overnight. How does it report progress, stay resumable after a crash, and avoid editing its own acceptance tests?

Activity

Write the one-page handoff note that would have saved Vihaan’s second morning: the goal, what is finished, what is next, how to start, and what to check before building. Then list which of those items belong in a file the harness reads automatically and which belong in the compaction summary.

Homework

Design the full handoff for a research agent that must write a 40-page report across several sessions. Cover the files it keeps (plan, source list, progress), the fields only the harness may change, the startup routine, what a compaction must preserve, and how you would check that a section is really finished before it is marked done.

Quick Revision

  • Two problems: rot inside a session, amnesia between sessions.
  • Budget the window: cap outputs, clear old tool results, compact late and in one step; keep goal, constraints, decisions, to-dos and the last error.
  • Across sessions: a feature list that starts failing, a progress file, version control, and a startup routine with a smoke test; one feature per session.
  • A prompt rule is not a lock: make the harness enforce which fields the agent can change.
  • Short instruction file as a map; knowledge must be in the repo; memory is scoped and fails closed.

Check yourself

  • Walk-through: An agent must build a large app over many sessions. Lay out the artefacts, the session routine and the guards against doing too much at once and against stopping early.
  • Variation: Do it again for a research agent that must produce a 40-page report.
  • Common misconception: “A bigger context window removes the need for any of this.”

Resources & Further Reading

Checked sources to go deeper. The essential ones come first in each group.

Official documentation

Further reading

Research papers

More for this module: Harness engineering resources

Practice

Test what you just read. Quizzes and cards are grouped by module: Harness engineering.

Check yourself10 questions on what this lesson set out to teach

Checking answers needs JavaScript. You can still read every question and option below.

0 of 10 answered

Keyboard: arrow keys move between options. Space or Enter selects the focused option.

ObjectiveExplain context rot and keep a long session productive with a context budget, tool-result clearing and compaction.

  1. Question 1 of 10Why can an agent do worse as its window fills, even well before the limit?

    Choose one answer.

  2. Question 2 of 10A tool-heavy agent keeps every old raw tool result in its history. Which change is the lightest-touch way to recover room?

    Choose one answer.

  3. Question 3 of 10The window is 100,000 tokens, 8,000 are reserved for output and 10,000 are the fixed prompt. Compaction starts at 75 percent of what remains after the output reserve, and each capped tool step adds 2,000 tokens. About how many steps fit before compaction?

    Choose one answer.

ObjectiveState what a compaction must keep and what it may drop, and name two ways it goes wrong.

  1. Question 4 of 10Which should a compaction keep as written? Select all that apply.

    Choose all that apply.

  2. Question 5 of 10After a compaction the agent tries an approach that had already failed twice. Which loss does this show?

    Choose one answer.

ObjectiveDesign the handoff artefacts for work that spans many sessions: a restricted-field feature list, a progress file, version control and a startup routine.

  1. Question 6 of 10Why should the feature list for a long-running agent start with every entry marked failing?

    Choose one answer.

  2. Question 7 of 10A coding session is starting on a long project. Which first steps match the startup routine?

    Choose one answer.

  3. Question 8 of 10A prompt tells the agent to change only the passes field of each feature entry. How much protection does that give?

    Choose one answer.

ObjectiveExplain why instruction files should be short maps and why knowledge the agent needs must live where it can read it.

  1. Question 9 of 10A rule that exists only in a team chat thread keeps being broken by the agent. What is the best fix?

    Choose one answer.

  2. Question 10 of 10Why keep the instruction file short and point into a documentation folder?

    Choose one answer.