Context Engineering for Long-Horizon Agents
An agent built on a frozen language model has only one place to hold what it learns during a run: the token sequence passed to the next call. Model weights stay fixed across the session, so a hypothesis sketched three turns ago, a traceback from the last command, and an environment rule inferred twenty minutes earlier influence the next step only if they remain in the prompt in a form the model attends to.1 Long sessions pull that window in two directions at once. Models read tokens near the beginning and end of a long prompt more reliably than tokens buried in the middle,2 while every retained token occupies GPU key-value (KV) cache that serving engines can reuse across turns only as long as the leading token IDs stay identical.3
Context engineering decides what enters that window, how tool outputs report state changes, when old turns are evicted, and how failed experiments are recorded. The measurements below come from two long-horizon harnesses built for the ARC Prize, both serving a 125B mixture-of-experts reasoning model on vLLM with a sandboxed Python interpreter as the sole tool. The first is a program-synthesis solver for ARC-AGI-2, where each puzzle gives roughly three small colored-grid input/output examples and the agent writes Python code across dozens of turns to infer the underlying transformation rule. The second is an interactive agent for ARC-AGI-3, where the agent plays multi-stage grid games with undisclosed rules over hundreds or thousands of actions.
Across both systems, four empirical results ran counter to common agent designs:
- Keeping raw prior reasoning in the prompt outperformed summarizing history or stripping old thinking blocks.
- State distinctions pushed into every action receipt changed agent behavior, whereas optional pull-based diagnostic helpers went unused.
- Deleting repeated prompt reminders and hints beat adding instructions or handing stalled stages to clean-context subagents.
- Full-budget stalls consistently began when a
"no effect"observation was recorded as an unconditional rule rather than tied to the state in which the action ran.
Working memory and atomic block drains
On each turn of an interactive session, the harness appends a short state header, the latest board observation, the model’s reasoning block, the Python code it executed, and standard output from the sandbox. Re-rendering that growing conversation through a string-based chat template on every call quietly breaks prefix caching whenever the template normalizes whitespace or strips prior reasoning blocks. After turn one, the harness instead appends exact generated token IDs and tokenized tool responses directly on the completions endpoint, keeping prefix-cache reuse above 90% until the window fills.
Keep raw reasoning while it fits
As a session approaches the model’s 131,072-token context limit, old thinking blocks look like easy weight to shed. In the interactive game agent, reasoning blocks made up roughly half of every prompt. Auditing transcripts showed why deleting them backfires: roughly 40% of assistant turns referenced coordinates, object counts, or partial deductions that appeared only inside earlier thinking blocks and had never been echoed into Python code or tool output.
Testing thinking-block compaction directly on mid-run synthesis checkpoints (stripping earlier reasoning blocks while preserving every line of code and sandbox output) cut downstream solve rates by nearly 11 percentage points and lost at every remaining token budget. On the very first turn after compaction, median reasoning length jumped more than sixfold (from roughly 1,000 to 6,300 tokens) as the model spent its turn reconstructing intermediate deductions that had just been erased. Replacing old turns with a curated digest of literal excerpts failed even worse on multi-stage games. Reasoning tokens carry live working state, and at turn 12 no static summarizer knows which partial observation turn 80 will depend on.
Drain full windows in sawtooth blocks
Once a session reaches the context ceiling, how old history is evicted determines both serving cost and prompt integrity. Dropping the single oldest turn on every request (a rolling sliding window) shifts token zero on every call, invalidating the entire cached prefix and forcing a full-window re-prefill on every step. Trimming by raw token count also risks severing a tool output from the assistant call that produced it.
Instead, sawtooth block eviction lets the prompt grow to roughly 90% of the context window (~118K tokens, leaving room for a full reply and wrapper tokens), then drops the oldest complete (user, assistant, tool) turn blocks down to ~45% capacity (~57K tokens) in a single step and prepends a short milestone header listing defined Python helpers and cleared stages.
Draining half the window at once pays a single 4-to-6-second re-prefill roughly every 40 turns, followed by ~40 turns of append-only cache hits (93.6% cached prompt tokens across full runs), while atomic block boundaries guarantee no tool response is orphaned. Because the prefix is already invalidated on a drain turn, that step is also the one free moment to compact surviving observations (replacing older full-board renders with pointers to the sandbox’s state array and middle-truncating verbose logs) while leaving surviving reasoning and code untouched. Cutting the per-session context cap in half so more concurrent games could share one GPU doubled trim frequency, inflated tokens spent per action by 27% as the model re-derived evicted history, and lowered game scores despite 32% higher raw token throughput.
Designing the observation channel
An agent perceives its environment entirely through tool responses, so the execution sandbox and its output format act as its sensors.4 Exposing a single python read-eval-print loop (REPL) inside an isolated subprocess gives the model a far richer action space than fixed JSON tool schemas: it can write loops, inspect slices of state, and test candidate hypotheses in one step,5 solving roughly 6.7 times as many synthesis tasks per generated token as plain chain-of-thought without code execution.
Bounded diffs and subprocess isolation
How a sandbox reports failure shapes how fast the agent converges. Returning a bare False forces blind guesswork, while dumping an entire grid on every mismatch floods the prompt. In the synthesis harness, a preloaded verify helper catches exceptions as structured text and prints at most a handful of mismatched coordinates:
def verify(transform, pairs, max_cells=8):
"""Run a candidate across input/output examples and report exact mismatches."""
all_ok = True
for i, (grid_in, want) in enumerate(pairs):
try:
got = transform([row[:] for row in grid_in])
except Exception as exc:
print(f"pair {i}: ERROR {type(exc).__name__}: {exc}")
all_ok = False
continue
if [len(row) for row in got] != [len(row) for row in want]:
print(f"pair {i}: SHAPE got {len(got)}x{len(got[0]) if got else 0}, "
f"want {len(want)}x{len(want[0])}")
all_ok = False
continue
diffs = [(r, c, got[r][c], want[r][c])
for r in range(len(want)) for c in range(len(want[r]))
if got[r][c] != want[r][c]]
if not diffs:
print(f"pair {i}: OK")
continue
all_ok = False
shown = ", ".join(f"({r},{c}) {g}->{w}" for r, c, g, w in diffs[:max_cells])
extra = f" (+{len(diffs) - max_cells} more)" if len(diffs) > max_cells else ""
print(f"pair {i}: {len(diffs)} cells differ: {shown}{extra}")
return all_ok
pairs = [([[0, 1], [1, 0]], [[1, 0], [0, 1]]),
([[2, 0, 0]], [[0, 0, 2]])]
verify(lambda g: g[::-1], pairs) # vertical flip: matches pair 0, fails pair 1
Running that candidate pinpoints the error in two lines even when hundreds of cells disagree on larger grids:
pair 0: OK
pair 1: 2 cells differ: (0,0) 2->0, (0,2) 0->2
Keeping a Python sandbox fast and trustworthy across hundreds of turns also meant closing four mechanical traps that short single-turn benchmarks rarely trigger:
- Passing incremental state deltas into the worker process instead of re-serializing the full transition history on every turn removed quadratic serialization growth and sped up late-session turns ~3.6x.
- Running each turn in a fresh isolated interpreter (
python -I -B) while carrying forward only top-leveldefhelpers and AST-verified literal constants whose values stayed unchanged at the end of the call preserved reusable code without leaking mutated globals into later turns. - Pausing the per-turn CPU timeout while external environment RPCs waited on I/O kept valid search loops from timing out, and raising a
BaseExceptionsubclass when an episode hit its action cap prevented generatedexcept Exception:blocks from swallowing the limit. - Streaming
stdoutincrementally let timeout handlers return the head and tail of printed output rather than an empty string; similarly, when generation hitmax_tokensmid-thought before emitting code, quoting the tail of the truncated reasoning into the next prompt kept the unfinished deduction intact.
Push critical state into receipts, not optional helpers
Models read harness output literally, turning vague status strings into persistent false beliefs. In the interactive game harness, every executed action returns a one-line receipt distinguishing five outcomes: ACTION -> effect, -> NO-OP (executed, no state change), -> ANIMATED (cells changed and reverted; zero net change), -> STAGE COMPLETED, and -> ATTEMPT ENDED. An early build reported transient animations with the same "nothing moved" string as NO-OPs, convincing the agent that live controls were dead. A similarly vague exception on stale game states led the model to wrap action calls in try/except and keep executing blind after an attempt had already ended. Disambiguating those two receipts alongside a leaner opening prompt produced one of the largest single score jumps in development.
Optional pull-based helpers had the opposite record. Preloaded Python functions to test world-model hypotheses against transition logs, run breadth-first search, or list untried (state, action) pairs were called on roughly 1% of turns, and preloading an unsolicited object-graph library in the synthesis harness slightly lowered solve rates. Calling a diagnostic function requires suspecting your current belief is wrong, and the exact turns where an agent most needs a check are the turns where it is confident and mistaken. State distinctions that matter belong in the receipts the model already reads on every step.
Subtracting prompt clutter and isolating the bottleneck
Once history retention and action receipts are clean, adding extra guidance to the prompt usually hurts. Irrelevant or repeated text degrades single-turn reasoning6 and fills the context window faster across multi-hour runs.
Across iterative ablations, deleting repeated prompt elements beat every instructional addition tested. Printing the tool-usage reminder only on turn one and right after sawtooth drains (rather than on every turn) and dropping a redundant visual diff frame lifted scores on both development and held-out suites. Conversely, adding an explanatory bundle of coordinate hints, layout deltas, and a stale-state warning (which fired on ~60% of turns while relevant on ~5%) lowered game scores by more than 6 points, and five separate rounds of “stuck-turn” advice nudges all tested neutral to negative.
Handing a stalled game stage to a fresh “consultant” subagent with a clean context window hurt performance as well. Blind grading rated roughly 90% of consultant hypotheses inaccurate: wiping the context discarded sunk bias and hard-won empirical observations together, whereas more than half of stages still open late in a run cleared when the main trajectory simply kept working.
An oracle check on 14 hard synthesis tasks explained why prompt nudges could not unstick hard episodes. Appending a short plain-English statement of the true transformation rule (written strictly from the visible training examples) jumped solves from 4.5 to 13 out of 14 (~93% implementation accuracy once the rule was stated), whereas supplying the closest analogous rule from solved tasks barely moved the score. Writing Python was rarely the bottleneck. Empirical rule discovery was, and discovery failed sharpest when interpreting negative results.
Negative evidence and discriminating probes
Whenever an agent runs an action in a stateful system and sees no expected effect, at least two explanations fit the log: the action never works, or a hidden state precondition was missing. Re-reading past turns cannot separate those hypotheses; running a controlled probe that toggles the precondition can.7
A familiar software bug shows the structure cleanly. Suppose a coding agent runs PRAGMA foreign_keys = ON in SQLite, sees no error, and then watches an INSERT with a missing parent key succeed anyway. "The Python driver ignores foreign keys" fits the transcript; so does "a transaction (BEGIN) was already open, and SQLite ignores foreign-key pragma changes inside multi-statement transactions." Toggling that single precondition in an isolated in-memory probe settles the question in ten lines:
import sqlite3
from contextlib import closing
def probe(begin_before_setting):
with closing(sqlite3.connect(":memory:", isolation_level=None)) as db:
db.execute("PRAGMA foreign_keys = OFF")
db.execute("CREATE TABLE parent (id INTEGER PRIMARY KEY)")
db.execute("CREATE TABLE child (parent_id REFERENCES parent(id))")
if begin_before_setting:
db.execute("BEGIN")
db.execute("PRAGMA foreign_keys = ON")
if not begin_before_setting:
db.execute("BEGIN")
flag, = db.execute("PRAGMA foreign_keys").fetchone()
try:
db.execute("INSERT INTO child VALUES (42)")
except sqlite3.IntegrityError:
return flag, "rejected"
return flag, "accepted"
print(probe(True)) # (0, 'accepted')
print(probe(False)) # (1, 'rejected')
A probe earns its keep only when competing hypotheses predict opposite outcomes on it:
| Candidate probe | Driver always ignores setting | Setting requires no open transaction |
|---|---|---|
Repeat PRAGMA inside BEGIN and read flag | 0 (Off) | 0 (Off) |
Run PRAGMA before BEGIN and read flag | 0 (Off) | 1 (On) |
| Reinstall driver and rerun full test suite | Confounded | Confounded |
Why false negatives lock in
Every full-budget stall audited across the interactive game transcripts (12 of 12 across public and held-out suites) started through the same mistake: zero to two confounded failed tries were generalized into an unconditional "does nothing" rule, such as "boundary is impassable" after pushing only from blocked angles or "clicks are inert" after clicking once an attempt had already ended.
Execution treats the two error directions asymmetrically. When an agent adopts an overly optimistic rule (a false positive, predicting an action will move a piece when it cannot), the planner schedules that action inside its legal search set and the very next NO-OP receipt refutes the prediction. When an agent adopts an overly broad "inert" rule (a false negative), that rule fits 100% of recorded history (1,965 of 1,965 transitions in one stalled agent’s self-check) and prunes the action from future plans, sealing off the untested precondition that would refute it.
Grouping all 180 click actions from a 5,079-action stall by selection state exposes the missing cell in the agent’s test matrix directly:
| State immediately before click | Total clicks | Clicks on right-hand target (39, 28) |
|---|---|---|
| No object selected | 151 | 4 |
| Left object selected | 29 | 0 |
Four clicks on the right-hand target at (39, 28) with nothing selected changed zero cells, and the agent wrote down "target (39, 28) is inert" before declaring the stage unsolvable. Replaying from the start to test the empty cell broke the stall immediately: clicking the left object at (14, 28) selected 20 cells, clicking (39, 28) while selected docked 478 cells, and two follow-up moves cleared the stage in four actions total. Recording "click (39, 28) did nothing with selection empty; selected case untried" preserves the open branch that an unconditional "inert" label erases.
Event-triggered audits over standing reminders
Standing system-prompt rules urging the model to test preconditions went ignored during every stall. Injecting a short audit prompt only on the turn the agent claimed impossibility (matching phrases such as "unsolvable", "inert", or "does nothing", with a cooldown between firings) prompted an explicit code-and-action probe roughly a third of the time on forked mid-run checkpoints and rescued several stuck stages without losing any. Keyword matching still proved noisy: more than half of triggers matched valid elimination reasoning on stages the agent was already on track to clear, keeping full-run lift modest. Structured harness state that tracks which (action, precondition) pairs remain untried is far cleaner than regex nudges over free-text reasoning.
Over long horizons, reliable agent harnesses come down to discipline around state: keep raw reasoning intact until capacity forces an atomic sawtooth drain, return bounded diffs and unambiguous push receipts from an isolated REPL, strip standing prompt clutter, and bind every "no effect" observation to the exact state in which it was tested.
References
Shunyu Yao, Jeffrey Zhao, Dian Yu, Nan Du, Izhak Shafran, Karthik Narasimhan, and Yuan Cao. 2023. ReAct: Synergizing reasoning and acting in language models. In The Eleventh International Conference on Learning Representations (ICLR 2023), 2023. ↩︎
Nelson F. Liu, Kevin Lin, John Hewitt, Ashwin Paranjape, Michele Bevilacqua, Fabio Petroni, and Percy Liang. 2024. Lost in the middle: How language models use long contexts. Transactions of the Association for Computational Linguistics 12, (2024), 157–173. ↩︎
Woosuk Kwon, Zhuohan Li, Siyuan Zhuang, Ying Sheng, Lianmin Zheng, Cody Hao Yu, Joseph E. Gonzalez, Hao Zhang, and Ion Stoica. 2023. Efficient memory management for large language model serving with PagedAttention. In Proceedings of the 29th Symposium on Operating Systems Principles (SOSP ‘23), 2023. 611–626. ↩︎
John Yang, Carlos E. Jimenez, Alexander Wettig, Kilian Lieret, Shunyu Yao, Karthik Narasimhan, and Ofir Press. 2024. SWE-agent: Agent-computer interfaces enable automated software engineering. In Advances in Neural Information Processing Systems 37 (NeurIPS 2024), 2024. 50528–50652. ↩︎
Xingyao Wang, Yangyi Chen, Lifan Yuan, Yizhe Zhang, Yunzhu Li, Hao Peng, and Heng Ji. 2024. Executable code actions elicit better LLM agents. In Proceedings of the 41st International Conference on Machine Learning (ICML 2024), 2024. 50208–50232. ↩︎
Freda Shi, Xinyun Chen, Kanishka Misra, Nathan Scales, David Dohan, Ed H. Chi, Nathanael Schärli, and Denny Zhou. 2023. Large language models can be easily distracted by irrelevant context. In Proceedings of the 40th International Conference on Machine Learning (ICML 2023), 2023. 31210–31227. ↩︎
Dana Angluin. 1988. Queries and concept learning. Machine Learning 2, 4 (1988), 319–342. ↩︎