Skip to content
The AI Agent Factory

Chapter 26. Context Engineering for Long-Running Agents

Approved by
Panaversity ·
32 min read

Start here if you skipped Chapter 25

If you read Chapter 25, skip this. These are the words from it, and from the chapters before it, that this chapter builds on.

WordWhat it meansWhere this chapter uses it
TokenA small piece of text, often part of a word. A model reads and writes tokens, and a request's size and its price are both counted in them (21.12)Everywhere
ConnectorThe AP MCP server: the program through which the worker reads Brightline's vendors, invoices, purchase orders and policyEverywhere
HarnessThe program around a model that runs the loop for you, offers tools and keeps the conversation. The Claude Agent SDK is one, and a coding agent is another (Chapter 22)26.3, 26.4, 26.5, 26.8
The worker's instructionsThe rules of the operator, whoever runs the application (here you, for Brightline), for every run, which the worker's code sends as the system prompt of every request (25.2)Everywhere
Tool call, tool resultThe model's request to run one tool, and what running it returned. A tool result reaches the model as data, not as an instructionEverywhere
The four toolsThe AP connector's read tools: list_open_invoices, find_vendor, get_purchase_order and search_policy. None of them changes anything26.1, 26.3
The conversation you ownEach request must carry the whole history, and the model reads only what that request holds. Your code keeps that history as a list (21.5)26.2, 26.3, 26.4
TraceA record of one run, one line for each model call and each tool call (21.10)26.2
Check by codePlain code, with no model call, that tests an answer against the tool results. In Lab 23 it reads the morning triage, the worker's run every weekday at 7:10The point, 26.1, the lab
Rule 2An answer must cite a policy line, written as (file.md:N). One citation anywhere in the answer passes itThe point
Context lossOne of six names for a failure: the worker leaves out, or stops following, something it was given earlier in the run (24.7)26.1

The point

Friday, April 30, 2027, 4:10 in the afternoon. Dave Kowalski, Brightline's controller, asks for the month-end review in one sentence: "Tell me which open invoices are a problem, and why, with the policy line for each." You are the builder. You start one session of the AP worker with that sentence as its request, on a review's budget of $1.00, and you go home. AP is accounts payable, the team that checks and pays a company's bills.

The worker lists the open invoices. For each one it makes three tool calls, find_vendor, get_purchase_order and search_policy, in about sixty turns. A turn is one call to the model and its reply. Everything a tool returns stays in the conversation, so each request is longer than the one before. The context window is everything one request to the model holds, and also the most it can hold.

Part of the way through, the conversation reaches a size you set before you left. The API then replaces the older turns with a summary that the model writes. This is compaction. The summary keeps the task. It drops six words, "with the policy line for each". From there to the end, each problem invoice has a reason and no policy line. No error is reported, and the run ends inside its budget.

Monday, May 3, 8:40 in the morning. Nothing told you on Friday. Lab 23's check by code reads the morning triage only, and the review was one request, started by hand. So you extend that check to a review, and run it on Friday's answer. It fails on every problem invoice that came after the summary.

Two other rules held through the whole run. The worker never pays, approves or changes anything, and it did none of these. Rule 2 asks that an answer cite a policy line, and Friday's answer passes it, because the invoices before the summary carry their lines. Both rules are in the worker's instructions. "For each" was only in Dave's sentence.

You have met every piece of this before. In 12.5 you had four moves for a long session, and two of them were to compact, and to start a fresh session (/clear). In 16.3 you learned that "A correction typed into a chat helps once and is gone." In 21.5 you kept the conversation yourself. In 23.16 code checked the worker's report. In 25.2 the operator's rules went in the system prompt. This chapter gives that last rule a second reason: no summary rewrites the system prompt.

So before you fix Friday's run, answer one question. In Chapter 12 you cleared and compacted, and each time something was thrown away. What is safe to lose, and where must a rule live so it is still there afterward? Start with its first step: where was "for each" on Friday, that a summary could lose it?

For managers

An AI Worker that runs for a long time can stop following one of your rules, and report no error. This chapter shows why, and what a builder does about it before the run starts.

A worker reads only what one request to the model holds. That is its context window: its instructions, its tools, the request, everything its tools have returned, and its own earlier answers. In a long run the window fills, mostly with what the tools returned. So something is cut. Old tool results are cleared. Or a short summary, written by the model, replaces the older part of the conversation. Or the work starts again in a new session.

What is cut can be a rule. Dave Kowalski, Brightline's controller, asks for a month-end review of the open invoices, "with the policy line for each". The builder starts the run on a Friday afternoon and leaves. Part of the way through, a summary replaces the older turns. It keeps the task and drops those six words. From there, each problem invoice has a reason and no policy line. The builder learns of it on Monday morning, when a check fails.

The fix comes before the run. The builder sorts what the window holds into three kinds, by where else each one lives:

  1. Rules must be as true on the last invoice as on the first. A rule lives in the worker's instructions. Every request carries them whole, and no summary rewrites them. A rule that was only said in a request, or typed later as a correction, is part of the conversation. A summary can lose it.
  2. The state of the work is what the worker has decided so far. The worker writes each decision to a progress file outside the window, as it makes it. The file opens with the request, word for word.
  3. Evidence is what the tools returned. The business system can return it again, so it is the one kind that is safe to cut.

After the run, plain code tests the rule on every invoice, and the builder reads the result the next working morning.

Ask your builder five questions before a long run goes live:

  1. Where is each of my rules written? The answer you want is "in the worker's instructions".
  2. What tests each rule after the run, on every item? A check that looks for one policy line passes a review that lost the line on its last invoices.
  3. If the run stopped halfway, could a new session finish it? It can when the instructions and the progress file are enough to start again.
  4. What does the worker cut when its window fills? Tool results are safe, because they can be fetched again.
  5. Whose notes can the worker read? A store of notes belongs to one person at one company. A note the worker saved is never a rule.

If the builder cannot answer the first three, the worker is not ready for a long run that nobody watches.

Why it matters

In 12.5 you sat in front of the session, and the page could say "You will see it happen." Nobody sits in front of a month-end run. Anthropic's own guide for its coding agent describes the result: "In a run you started before going to bed, nobody tells it, and you find out the next morning that it spent the whole night building on the wrong assumption."1

Every fix in this chapter removes part of the conversation, or keeps part of it out. So before anything is cut, the builder sorts what the window holds into three kinds, by where else each one lives.

The three kinds are rules, the state of the work and evidence, and each has a different home: the worker's instructions, a progress file outside the window, and the connector, which can return evidence again.

On Friday only the evidence had a second home. Figure 26.1 shows it.

Figure 26.1. Friday's run. The instructions and the tool results each live somewhere else too. The rule inside the request and the worker's decisions live only in the window.

How this chapter works

The chapter has eight concepts and one lab. Read the concepts in order.

The concepts name no beta setting. Several of the settings behind them are in beta, a test stage that can still change. So 26.8 and the lab carry those with their dates. Claude comes first, then OpenAI, then open source.

One word is kept narrow. From here on "clear" always means that the API clears old tool results. Chapter 12's /clear is written "start a fresh session (/clear)". A fresh session is a new conversation with an empty history.

Five subjects belong to other chapters. A subagent is a second agent with a context window of its own, and whether a design should have subagents at all is Chapter 27's. Text that is planted in a worker's memory to give it orders is Chapter 28's. Measuring what each choice costs is Chapter 29's. What a worker learns between runs is Chapter 31's. A context policy for many workers is Chapter 33's.

After this chapter you can:

  • Tell the two causes of drift apart, from a trace and a failing check.
  • Sort what a window holds into rules, state and evidence, and give the first two a home before a long run.
  • Cut tool results at the tool and in the API, and say what each cut costs.
  • Tell a summary what to keep, and check what it kept.
  • Move side work to a subagent, with the rules it needs in its own prompt.
  • Say when a fresh session is the right move, and what makes it safe.

What you will build

Who's who. You are the builder. Dave Kowalski is Brightline's controller. He owns AP policy, and he asks for the month-end review. Brightline Wholesale Supply is the invented wholesale distributor whose AP worker you have built since Chapter 16.

Where you are. At the end of Lab 25 the AP worker runs in Brightline's portal, Brightline's web application. It has its instructions, the connector's four read tools, and a check by code on the morning triage. No check by code tests a review on every invoice. Nothing is written outside the window during a run.

What you build instead, in Lab 26, in two sittings, from tag ch25 to tag ch26:

  1. The check, built first, where it fails. You extend Lab 23's check by code to a review, and run it on the recorded session of about 60 turns.
  2. A home for the rule and for the state. You find which kind had no home. "For each" goes into the instructions, and the worker writes each decision to the progress file. The check passes.
  3. The first cut. find_vendor returns only the terms, and the API clears old tool results.
  4. The summary, with your instructions. You tell the summary what to keep, and you read what it kept.
  5. The lookups in a subagent, in its own window.
  6. The same session on Codex and on OpenCode, with the rules in an instruction file. That is the file a coding agent loads into every request (CLAUDE.md or AGENTS.md, the rules file of 12.4).

Tasks 2 to 5 each end the same way. You run the check, and you read the tokens by part and the run's cost, before and after.

Task 1 replays Friday's recorded run and sends no request. Tasks 2 to 4 run on your own loop from Chapter 21, where you can see the conversation, the token counts and each setting. Task 5 uses the harness of Chapter 22, because a subagent needs one, and Task 6 replays the session in two coding agents. As in Chapters 17 to 25, coding agents write every file and run every command. You specify, check and approve.

In this chapter

SectionThe question it answers
26.1 Why long sessions drift and bloatWas the rule still in the window, or had a cut removed it?
26.2 Reading context use in a traceWhich kind filled the window, and what was cut, and when?
26.3 Tool-output pruning and context editingWhich kind is safe to cut, and who should cut it?
26.4 Compaction: by threshold and on demandWhat does a summary lose, and what must go outside first?
26.5 Isolation with subagentsWhat reaches a subagent, and what never does?
26.6 Memory outside the window, scoped per person and companyWhat lives outside the window, and whose is it?
26.7 When to start a fresh sessionWhen is starting again the right move, and what makes it safe?
26.8 How today's tools realize itOn each product, what comes back after a summary?
Lab 26A review that drifts, a check that fails, a home for the rule and the state, and three ways to make the window smaller, from tag ch25 to tag ch26
Check yourselfOne open question for each concept, with an outline of its answer
  1. Best practices for Claude Code, Anthropic.↑
Owner
Panaversity