Slides · Harness engineering
Context and long-running agents
1 / 22
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.
Diagram
Three moves, cheapest first
Math
The budget as arithmetic
steps=⌊st(W−O)−F⌋| Symbol | Meaning |
|---|---|
| W | total context window, in tokens |
| O | tokens reserved for the model’s output |
| t | fraction of the remaining window at which compaction starts |
| F | fixed tokens: system prompt and tool definitions |
| s | average tokens one tool step adds |
| steps | tool 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.
| Step | Calculation | Result |
|---|---|---|
| Remaining after output reserve | 128,000−8,000 | 120,000 |
| Compaction trigger | 0.60×120,000 | 72,000 |
| Room for steps | 72,000−10,000 | 62,000 |
| Capped, s=2,500 | 2,50062,000=24.8 | 24 steps |
| Uncapped, s=12,000 | 12,00062,000=5.17 | 5 steps |
| Cap needed for 40 steps | 4062,000 | 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 written | Replace with a pointer |
|---|---|
| the user’s goal, constraints and acceptance criteria | raw tool output (“saved to logs/run-14.txt”) |
| key decisions and the reason for each | repeated reads of the same file |
| open to-dos and files touched | exploration that led nowhere |
| the last failing command and its error | |
| identifiers the model will need again |
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.
Source[2] 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.
| Observed | Added |
|---|---|
| tried to do too much, ran out of context mid-feature, left half-built undocumented work | one feature at a time; commit with a clear message and update the notes before ending |
| a fresh session saw progress and declared the job finished | a feature list written up front, every entry starting as failing |
| features marked complete without end-to-end testing | prompting the agent to test as a human user would, with browser automation |
| each session spent effort working out how to start the app | an init.sh script and a fixed startup routine |
Diagram
Initializer first, then coding sessions
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.
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 0 | accepted |
| edit a description | rejected |
steps [1, 2] to [true, 2] or [1.0, 2] | rejected |
nested {"k": 1} to {"k": true} | rejected |
passes set to 1 | rejected |
| add a key with value None, or remove a key | rejected |
| delete a feature | rejected |
an old entry that has no passes key | rejected (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
pwd, git logs, the progress file and init.sh.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
Sources[4] Agent Harness Engineering[5] 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.
Source[5] 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.envcan escape the memory directory unless every path is checked.
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)
Effective context engineering for AI agents (opens in a new tab)
Prithvi Rajasekaran, Ethan Dixon, Carly Ryan, Jeremy Hadfield2025Article
https://www.anthropic.com/engineering/effective-context-engineering-for-ai-agents
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.
Prompt caching (opens in a new tab)
Anthropic2026Documentation
https://platform.claude.com/docs/en/build-with-claude/prompt-caching
Used for Why the prompt cache matches an exact prefix, so rewriting early history invalidates what follows.
Effective harnesses for long-running agents (opens in a new tab)
Justin Young2025Article
https://www.anthropic.com/engineering/effective-harnesses-for-long-running-agents
Used for The observed failures of long-running coding agents and the initializer, feature list, progress file, git and startup-routine fixes.
Agent Harness Engineering (opens in a new tab)
Addy Osmani2026Article
https://www.oreilly.com/radar/agent-harness-engineering/
Used for The test that every AGENTS.md line should trace back to a specific failure.
Leela Kumili2026Article
https://www.infoq.com/news/2026/02/openai-harness-engineering-codex
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)
Agent Harness (opens in a new tab)
Microsoft Learn (Agent Framework)2026Documentation
https://learn.microsoft.com/en-us/agent-framework/concepts/harness
Used for Session-scoped file access that fails closed when no session or scope is available.
Memory tool (opens in a new tab)
Anthropic2026Documentation
https://platform.claude.com/docs/en/agents-and-tools/tool-use/memory-tool
Used for Memory security advice: strip sensitive data, cap file size, expire stale files, and validate paths.
Keys: ← → move, Home End first and last, F full screen.