# Chapter 26. Context Engineering for Long-Running Agents (/building-ai-workers/context-engineering/overview)

---
type: Document
title: Chapter 26. Context Engineering for Long-Running Agents
description: 'Keep a long AP session''s rules true from the first invoice to the last: give each rule and the state of the work a home outside the window, cut only what can be fetched again, compact and isolate with care, and know when to start fresh. Built on Claude first, then ported to OpenAI and to open source.'
status: stable
order: 326
ksor:
  owner: team:panaversity
  audience:
    - public
  approval:
    by: process:panaversity
    at: 2026-11-30T08:16:26Z
chapter: '26'
part: III
expert_status: manager
objectives:
  - id: CCDV-F.D6.S1
    label: primary
  - id: CCDV-F.D1.S3
    label: supporting
word_budget: 3000
prerequisites:
  - '01'
  - '02'
  - '03'
  - '04'
  - '05'
  - '06'
  - '07'
  - 8
  - 9
  - '10'
  - '11'
  - '12'
  - '13'
  - '14'
  - '15'
  - '16'
  - '17'
  - '18'
  - '19'
  - '21'
  - '22'
  - '23'
  - '24'
  - '25'
build_step: 'A month-end AP review that keeps its rules: a check by code that fails on the drifting run, the rule in the worker''s instructions and the state of the work in a progress file, tool output cut at the tool and in the API, compaction with a check after it, side work in a subagent, and a port'
artifact: brightline-ap with an extended check-triage.ts, a progress file, context editing and compaction settings, a subagent, tag ch26
lab_data: https://github.com/panaversity/agentfactory-v2-resources/releases/latest/download/brightline-lab-ch26.zip
delta_entries:
  - D-022
concepts:
  - '26.1'
  - '26.2'
  - '26.3'
  - '26.4'
  - '26.5'
  - '26.6'
  - '26.7'
  - '26.8'
last_verified: '2026-11-30'
sources:
  - id: claude-code-best-practices
    title: Best practices for Claude Code (verified 2026-11-29)
    resource: https://code.claude.com/docs/en/best-practices
generated:
  at: 2026-11-30T08:16:26Z
  by: esl-rewrite/1.2.0+ksor.1
trust_tier: unverified
build_id: sha256:d6ce3f28a2cf8e492a60bae1b426b7cc6466e35e83d70c3b9763db2c55009f4b
dirty: true
ksor_version: 0.0.60
---

<!-- EDITOR: which objective ids does the front matter carry? This draft keeps `CCDV-F.D6.S1` (primary) and `CCDV-F.D1.S3` (supporting), because they equal `specs/v2plan/data/chapters.yaml`, which the checker compares. The other option: the ids of the guide's copy for version 1.1 (`CCDV-F.D6.O1`, and the matching id for 1.3), with 8.1 and 8.3 added as supporting, as the chapter's spec lists them. That needs the data file changed first. -->

## Start here if you skipped Chapter 25

*If you read [Chapter 25](../prompts-and-structured-output/overview.md), skip this. These are the words from it, and from the chapters before it, that this chapter builds on.*

| Word | What it means | Where this chapter uses it |
| --- | --- | --- |
| **Token** | A 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](../agent-loop-by-hand/tokens-caching-and-what-a-call-costs.md)) | Everywhere |
| **Connector** | The AP MCP server: the program through which the worker reads Brightline's vendors, invoices, purchase orders and policy | Everywhere |
| **Harness** | The 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 instructions** | The 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](../prompts-and-structured-output/system-or-user.md)) | Everywhere |
| **Tool call, tool result** | The model's request to run one tool, and what running it returned. A tool result reaches the model as data, not as an instruction | Everywhere |
| **The four tools** | The AP connector's read tools: `list_open_invoices`, `find_vendor`, `get_purchase_order` and `search_policy`. None of them changes anything | 26.1, 26.3 |
| **The conversation you own** | Each 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](../agent-loop-by-hand/the-conversation-is-an-array-you-own.md)) | 26.2, 26.3, 26.4 |
| **Trace** | A record of one run, one line for each model call and each tool call ([21.10](../agent-loop-by-hand/reading-a-trace.md)) | 26.2 |
| **Check by code** | Plain code, with no model call, that tests an answer against the tool results. In [Lab 23](../hosted-agents/lab.md) it reads the morning triage, the worker's run every weekday at 7:10 | The point, 26.1, the lab |
| **Rule 2** | An answer must cite a policy line, written as `(file.md:N)`. One citation anywhere in the answer passes it | The point |
| **Context loss** | One of six names for a failure: the worker leaves out, or stops following, something it was given earlier in the run ([24.7](../evaluating-ai-workers/naming-the-failure.md)) | 26.1 |

<!-- EDITOR: the wording of the token row. This draft uses the book's own definition from 21.12 ("small pieces of text (often part of a word)"). The other option is a size in words, such as "about three quarters of a word", which no Chapter 26 source note gives, and which differs from 0.1.2's "a little under two tokens" for an English word. -->

## 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.

<!-- OPEN: recorded run. The number of open invoices on April 30, the turn of the summary, the tokens in the window at that turn and the run's cost are not fixed until the run is recorded (spec, raised point 8). This draft gives none of them. -->

**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.

<!-- EDITOR: why was Friday's run not caught? This draft says the month-end review is one request started by hand, so Lab 23's check, which runs when a morning triage session goes idle, never read it. The other reading: the review runs inside that loop. Then the check fails on Friday, both feedback rounds fail, the builder finds needs_review on Monday, and the worked run changes. -->

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](../agentic-coding/context-sessions-effort.md) 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](../skills-and-plugins/writing-a-skill-with-the-expert.md) you learned that "A correction typed into a chat helps once and is gone." In [21.5](../agent-loop-by-hand/the-conversation-is-an-array-you-own.md) you kept the conversation yourself. In [23.16](../hosted-agents/loops-check-feedback-and-stop.md) code checked the worker's report. In [25.2](../prompts-and-structured-output/system-or-user.md) 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."[^claude-code-best-practices]

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.

<!-- EDITOR: where is the full list of the three kinds? This draft gives it twice only: in "For managers", which must stand alone, and in 26.6's table. "Why it matters" names the three kinds and their homes in one sentence. The other option: the full numbered list stays here too, so that a reader who skips "For managers" meets it before 26.1, at the cost of the same list twice, 22 lines apart. -->

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

<!-- FIGURE 26.1: "What the window holds in Friday's run, and where else each part lives." LEFT: one tall column labeled "the context window, Friday's run", with five stacked boxes, top to bottom: "instructions", "tools" (the four tool definitions), "the request", "tool results", "the worker's turns". Inside "the request" box, a smaller marked strip reads: "with the policy line for each" (a rule). Inside "the worker's turns" box, a smaller strip marked in the same way reads: "its decisions, one for each invoice". RIGHT: two boxes outside the column. Top right: "the instruction file". Bottom right: "the connector". ARROWS: (1) one arrow from "instructions" pointing right to "the instruction file", labeled "also lives here". (2) one arrow from "tool results" pointing right to "the connector", labeled "came from here". (3) a second arrow from "the connector" pointing left, back to "tool results", labeled "can be fetched again". So the connector pair runs both ways. NO arrow leaves "the request" or its marked strip. NO arrow leaves "the worker's turns" or its marked strip. Both marked strips carry the same mark and the same label: "no other home". "tools" has no arrow and no mark. A note under the column: "On Friday the request has no home outside the window. In the second run the request and the decisions each have an arrow to the progress file (Figure 26.3)." The alt text must say which two boxes have an arrow out, that the connector's arrows run both ways, and that the rule in the request and the worker's decisions have none. -->

*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.

<!-- EDITOR: may the chapter's question use "cleared" for Chapter 12's `/clear`? This draft keeps the spec's wording of the question ("In Chapter 12 you cleared and compacted") in "The point" and on the first flashcard, and makes the word rule above start "From here on", so the rule is true as written. The other option: the rule says "In this chapter", and the question is reworded to "you started fresh sessions and compacted". The editor has not yet confirmed the question. -->

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.

<!-- EDITOR: should the page name Lab 23's optional grader? Lab 23's optional Task 21b graded a review with a grader model against "every open Cedar Ridge invoice has a decision and a cited policy line". This draft says only that no check by code tests a review on every invoice, here and in the lab's "The job", and does not name that grader. The other option: one sentence that names it and says why a grader model is not the end check here, for a reader who remembers 23.17. -->

**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](../agentic-coding/rules-the-agent-reads.md)).

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](../agent-loop-by-hand/overview.md), 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.

<!-- OPEN: the lab page's name and anchor are not fixed, so "Lab 26" carries no link in this part. The task numbers named in 26.1 and 26.2 follow the spec's lab plan and are proposed until the lab is built. -->

<!-- EDITOR: which runtime runs the month-end session? This draft: the reader's own loop (Chapter 21) for Tasks 1 to 4, where the array, usage and both settings are visible, and the SDK worker for Task 5, which first makes a baseline run of its own. The other options: the hosted worker on Managed Agents, where compaction is always on and no page read gives a trigger or tool-result clearing, or the SDK worker throughout, which loses the visible array and settings. The choice also decides what enforces the $1.00 budget, which this page does not say for the reader's own loop, and whether the portal's citation check read Friday's answer. -->

## In this chapter

| Section | The question it answers |
| --- | --- |
| [26.1](why-long-sessions-drift-and-bloat.md) Why long sessions drift and **bloat** | Was the rule still in the window, or had a cut removed it? |
| [26.2](reading-context-use-in-a-trace.md) Reading context use in a trace | Which kind filled the window, and what was cut, and when? |
| [26.3](tool-output-pruning-and-context-editing.md) **Tool-output pruning** and context editing | Which kind is safe to cut, and who should cut it? |
| [26.4](compaction.md) Compaction: by threshold and on demand | What does a summary lose, and what must go outside first? |
| [26.5](isolation-with-subagents.md) Isolation with subagents | What reaches a subagent, and what never does? |
| [26.6](memory-outside-the-window.md) Memory outside the window, scoped per person and company | What lives outside the window, and whose is it? |
| [26.7](when-to-start-a-fresh-session.md) When to start a fresh session | When is starting again the right move, and what makes it safe? |
| [26.8](how-todays-tools-realize-it.md) How today's tools realize it | On each product, what comes back after a summary? |
| Lab 26 | A 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 yourself | One open question for each concept, with an outline of its answer |

[^claude-code-best-practices]: Best practices for Claude Code, Anthropic.
