Slides · Harness engineering

Context and long-running agents

Context and long-running agents

How a harness keeps one long session productive and carries work across sessions that each start blank.

By the end you can budget a context window, write a compaction policy, design the handoff artefacts for multi-session work, and explain why knowledge must live where the agent can read it.

Concept

Two different problems

  • A three-day clean-up gets a fresh agent session each morning. The note left for day two says only “Carry on”, so the agent redoes one batch and skips the next.
  • Inside a session: the window fills with logs, dead ends and stale file contents, and the model works worse.
  • Across sessions: every new window starts empty, so the agent cannot know what the last one finished.
  • The harness answers the first by budgeting what enters the window, and the second by writing state down where it outlives a session.

Concept

Context rot and the attention budget

  • Anthropic (29 September 2025) describes context rot: 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 on.
  • The rule that follows: put the smallest set of high-signal tokens in front of the model, not the largest set that fits.
  • So a bigger window does not remove the need to manage what goes in it.

Source1 Effective context engineering for AI agents

Diagram

Three moves, cheapest first

Diagram: Reading down, the moves rise in cost.

1 Cap what enters
truncate, offload

2 Clear old tool results
lightest compaction

3 Compact the conversation
summarise, fresh window

Diagram summary: Reading down, the moves rise in cost. Capping large tool outputs costs almost nothing and prevents the most waste. Clearing old raw tool results, which Anthropic calls one of the lightest forms of compaction, comes next. Summarising the whole conversation and continuing in a fresh window is the heaviest and the last resort.

Source1 Effective context engineering for AI agents

Math

The budget as arithmetic

steps=⌊t (W−O)−Fs⌋\text{steps} = \left\lfloor \frac{t\,(W - O) - F}{s} \right\rfloor
SymbolMeaning
WWtotal context window, in tokens
OOtokens reserved for the model’s output
ttfraction of the remaining window at which compaction starts
FFfixed tokens: system prompt and tool definitions
ssaverage tokens one tool step adds
stepstool steps that fit before compaction starts

Capping tool outputs lowers s, and s is the term you control most.

Worked example

Worked example: capped versus uncapped steps

Illustrative numbers: W = 128,000, O = 8,000, F = 10,000, t = 0.60.

StepCalculationResult
Remaining after output reserve128,000−8,000128{,}000 - 8{,}000120,000
Compaction trigger0.60×120,0000.60 \times 120{,}00072,000
Room for steps72,000−10,00072{,}000 - 10{,}00062,000
Capped, s=2,500s = 2{,}50062,0002,500=24.8\dfrac{62{,}000}{2{,}500} = 24.824 steps
Uncapped, s=12,000s = 12{,}00062,00012,000=5.17\dfrac{62{,}000}{12{,}000} = 5.175 steps
Cap needed for 40 steps62,00040\dfrac{62{,}000}{40}1,550 per step
  • Same window, nearly five times the steps, because of the cap.
  • All figures are made up; the proportion is the point.

Compare

What a compaction keeps

Anthropic says the art of compaction is choosing what to keep and what to discard, and that Claude Code’s compaction preserves architectural decisions, unresolved bugs and implementation details. The table is a judgment-based policy, not a standard.

Keep as writtenReplace with a pointer
the user’s goal, constraints and acceptance criteriaraw tool output (“saved to logs/run-14.txt”)
key decisions and the reason for eachrepeated reads of the same file
open to-dos and files touchedexploration that led nowhere
the last failing command and its error
identifiers the model will need again

Source1 Effective context engineering for AI agents

Concept

How compaction goes wrong

  • Invented detail: a summary can drop a fact, and the model then fills the gap with a confident guess.
  • Lost negative knowledge: “we tried that and it failed because of X” is easy to cut and costly to lose.
  • Cache cost: in Anthropic’s API the prompt cache matches an exact prefix, and a change early in the prompt invalidates everything after it. Rewriting early history every turn therefore throws the cache away, so compact once, not constantly.
  • Compounding: for very long jobs, start a new window from a short handoff file instead of re-summarising repeatedly; in our judgment, repeated summaries can compound their own errors.
  • Either way the durable record on disk, not the summary, is the source of truth.

Source2 Prompt caching

Check yourself

Check: a rewrite on every turn

A harness shortens the oldest 20 messages after every turn, to keep the history tidy. Latency and cost per call climb, even though the history is shorter. Give one likely reason and a fix.

Answer

Changing early messages changes the prompt prefix, so a prefix cache keyed on exact matches cannot reuse it, and the cached part of the prompt that follows the change is lost (a stable tools and system prefix can still be cached). Fix: leave history stable, clear or compact in one step when you cross the trigger, and put volatile material at the end of the prompt. Whether and how much you save depends on the provider’s caching rules, so check the current docs.

Compare

Each handoff artefact answers a failure

Young (Anthropic, 26 November 2025) reports these failures in long-running coding agents, and what was added.

ObservedAdded
tried to do too much, ran out of context mid-feature, left half-built undocumented workone feature at a time; commit with a clear 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 marked complete without end-to-end testingprompting the agent to test as a human user would, with browser automation
each session spent effort working out how to start the appan init.sh script and a fixed startup routine

Source3 Effective harnesses for long-running agents

Diagram

Initializer first, then coding sessions

Diagram: The same harness starts every session with a different prompt: the first sets up the environment (init script, failing feature list,...
RepoSessionHarnessRepoSessionHarnessloop[each later session]first prompt: set upinit.sh, features, notescoding promptread state, smoke testone feature, commit
Diagram summary: The same harness starts every session with a different prompt: the first sets up the environment (init script, failing feature list, progress file, first commit), and each later one reads that state, builds and tests one feature, then commits and updates the notes.

Source3 Effective harnesses for long-running agents

Code

The feature list

In Anthropic’s example, a clone of a chat app produced a list of more than 200 features, all starting as failing. They chose JSON because, they report, the model was less likely to change JSON inappropriately than Markdown. Agents were told to change only the 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"],
  "passes": false
}

“Only change passes” is an instruction, not a lock. The next slide makes the harness enforce it.

Source3 Effective harnesses for long-running agents

Code

A guard the harness runs, not the prompt

Illustrative check, run in a scratch script. The harness accepts an edit only if every feature has the same set of keys, every field except passes has the same value (compared as canonical JSON, so 1, true and 1.0 differ), and passes is a real boolean. Any error while comparing counts as a rejection.

Python

def canon(x):
    return json.dumps(x, sort_keys=True)           # 1, true and 1.0 serialise differently

def check_feature_edit(old, new):
    try:
        if len(old) != len(new):
            return "Rejected: feature count changed."
        for i, (o, n) in enumerate(zip(old, new)):
            if set(o) != set(n):                   # added or removed keys
                return f"Rejected: feature {i} fields changed."
            for k in o:
                if k != "passes" and canon(o[k]) != canon(n[k]):
                    return f"Rejected: feature {i} field '{k}' changed."
            if not isinstance(n["passes"], bool):
                return f"Rejected: feature {i} 'passes' must be true or false."
        return None                                # accepted
    except Exception as e:                         # fail closed
        return f"Rejected: could not compare ({type(e).__name__})."
Edit tried (2-feature list)Result
flip passes on feature 0accepted
edit a descriptionrejected
steps [1, 2] to [true, 2] or [1.0, 2]rejected
nested {"k": 1} to {"k": true}rejected
passes set to 1rejected
add a key with value None, or remove a keyrejected
delete a featurerejected
an old entry that has no passes keyrejected (KeyError caught; a new entry that adds passes is rejected by the field-set check, so a legacy list cannot gain passes through this guard)

The guard only helps if the agent cannot write the file by another route: let it update the list through this check and keep the file out of its direct write permissions.

Diagram

The startup routine

Diagram: Reading down, every session reads the recorded state and runs a basic end-to-end check first; a failure sends it back to fix the base, and...

no

yes

Session starts

Check directory, read git log,
progress file, feature list

Run init.sh and a
basic end-to-end check

Check passes?

Fix the broken base

Build one feature,
test like a user

Commit, update notes,
flip passes

Diagram summary: Reading down, every session reads the recorded state and runs a basic end-to-end check first; a failure sends it back to fix the base, and only a pass lets it build, test and commit one feature. Anthropic’s version starts with pwd, git logs, the progress file and init.sh.

Source3 Effective harnesses for long-running agents

Check yourself

Check: the smoke test fails at the start

A documentation agent starts session 6 on a site-building project. It reads the notes and runs the smoke test; the build fails because the previous session left a half-edited navigation file. Nine features are still pending. What should the session do first, and what does skipping that step cost?

Answer

Repair the build before any new feature, using git history to see what the last session changed or to revert it. If the session builds on a broken base, new bugs stack on old ones and it becomes unclear which session introduced each failure. The smoke test is cheap compared with rediscovering the state later.

Diagram

Instruction files are maps

Diagram: Reading down, the instruction file stays short and points into a structured documentation folder, and the detail is loaded only when a task...

AGENTS.md
short map

docs/architecture

docs/plans

docs/decisions

Loaded only when
the task needs it

Diagram summary: Reading down, the instruction file stays short and points into a structured documentation folder, and the detail is loaded only when a task needs it. Osmani’s test is that each line of a good AGENTS.md traces to a past failure, which keeps it short. This is progressive disclosure applied to documents; the folder names here are examples.

Sources4 Agent Harness Engineering5 OpenAI Introduces Harness Engineering: Codex Agents Power Large-Scale Software Development

Concept

If the agent cannot read it, it does not exist

  • A decision made in a chat thread or someone’s head is invisible to the agent. Write it into the repository as plain, versioned text.
  • A long instruction file crowds the window, makes every rule look equally important and goes stale.
  • InfoQ (21 February 2026) summarises OpenAI’s report as a documentation directory of maps, execution plans and design specs treated as the agents’ single source of truth, with linters and CI checking the documents stay consistent and cross-linked. That is a secondary account of one team’s approach.
  • When a document is not enough, promote the rule into code: a lint or structural test.

Source5 OpenAI Introduces Harness Engineering: Codex Agents Power Large-Scale Software Development

Concept

Memory is files with discipline

  • Files read at the start of a session and written at the end suit small, high-value state: conventions and decisions.
  • Scope them. Microsoft’s Agent Framework documents session-scoped file access that fails closed: with no session id or explicit scope, it refuses rather than using the shared folder.
  • Keep secrets out. Anthropic’s memory-tool docs say the model usually refuses to write sensitive information but advise stripping it with your own validation, and say to cap file sizes and delete files not accessed for a long time.
  • Validate paths. The same docs warn that a path such as /memories/../../secrets.env can escape the memory directory unless every path is checked.

Sources6 Agent Harness7 Memory tool

Check yourself

Check: whose notes are these?

A shared agent writes notes to agent-files/. A bug leaves one request without a session id. Compare what a fail-open and a fail-closed design do, and which you prefer.

Answer

Fail-open falls back to the shared folder, so this request may read or overwrite notes that belong to another session or tenant. Fail-closed refuses the file access and returns an error, which is visible and fixable. Prefer fail-closed, because a leaked or overwritten note is much harder to detect than a refused request.

Summary

Recap

  • 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 failing-first feature list, a progress file, git 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.
  • Keep instruction files short; put knowledge in the repo; scope memory and fail closed.

References

References & Sources (1 of 2)

  1. Effective context engineering for AI agents (opens in a new tab)

    Prithvi Rajasekaran, Ethan Dixon, Carly Ryan, Jeremy Hadfield2025Article

    Used for Context rot as a finite attention budget, the smallest-set-of-high-signal-tokens rule, tool-result clearing as light compaction, and what compaction should keep.

  2. Prompt caching (opens in a new tab)

    Anthropic2026Documentation

    Used for Why the prompt cache matches an exact prefix, so rewriting early history invalidates what follows.

  3. Effective harnesses for long-running agents (opens in a new tab)

    Justin Young2025Article

    Used for The observed failures of long-running coding agents and the initializer, feature list, progress file, git and startup-routine fixes.

  4. Agent Harness Engineering (opens in a new tab)

    Addy Osmani2026Article

    Used for The test that every AGENTS.md line should trace back to a specific failure.

  5. OpenAI Introduces Harness Engineering: Codex Agents Power Large-Scale Software Development (opens in a new tab)

    Leela Kumili2026Article

    Used for A secondary account of one team treating a structured docs directory as the agents' source of truth, with linters and CI checking it.

References

References & Sources (2 of 2)

  1. Agent Harness (opens in a new tab)

    Microsoft Learn (Agent Framework)2026Documentation

    Used for Session-scoped file access that fails closed when no session or scope is available.

  2. Memory tool (opens in a new tab)

    Anthropic2026Documentation

    Used for Memory security advice: strip sensitive data, cap file size, expire stale files, and validate paths.