Context Engineering for Long-Horizon Agents: Compaction, Tool-Output Offloading & Notes
Why 'just use a 1M context window' fails in practice (Context Rot): offloading giant tool outputs to scratchpad files, trajectory Compaction at ~70% fill, and persistent structured notes (NOTES.md) for multi-hour coding & research agents.
Context Engineering keeps long-horizon agents sharp by offloading huge raw tool outputs to files/handles, compacting old turns, and maintaining a concise structured scratchpad.
Dumping 50,000 lines of logs directly into the prompt triggers 'context rot' where the agent loses track of the user's original goal and burns massive token bills.
In 2025–2026, Context Engineering replaced 'prompt engineering' as the #1 skill separating toy agents from frontier coding agents like Claude Code, Cursor, and Antigravity!
Offloading a single 18,000-token API response to /tmp/out.json and returning a 120-token preview saves ~178,000 billed tokens over a 10-step agent run AND keeps reasoning razor-sharp!
Understanding why attention quality decays long before the hard 200K/1M context limit explains why clean 15K-token compacted context beats 150K tokens of raw logs every time.
Cutting-edge Agentic AI interview question: 'How do you keep a coding agent coherent across 60 steps without suffering Context Rot or blowing up token costs?'
What is Context Rot in long-horizon AI agents?
- Define Context Engineering as curating the smallest high-signal token set needed for the current agent step
- Diagnose Context Rot (attention dilution as noisy raw tool logs pile up past 30%–50% of the context window)
- Implement Tool-Output Offloading (save bulky JSON/logs to disk and return a concise summary + file path pointer)
- Combine Trajectory Compaction with Persistent Structured Notes (
NOTES.md/TODO.md) for multi-hour long-horizon agents
Imagine trying to solve a hard math proof on a desk buried under 200 crumpled scratch sheets from yesterday's dead ends (Context Rot). Context Engineering clears the desk every hour: bulky raw reports go into a labeled filing cabinet (Tool-Output Offloading), and you keep ONE crisp 1-page checklist (Compaction + NOTES.md) right in front of you!
1. Context Rot: Signal-to-Noise Beats Raw Window Size
Never treat a 200K context window as a garbage dump — curate every token like precious RAM!
The 4 Levers of Context Engineering (Write, Select, Compress, Isolate)
- Write: Save durable progress & plans outside the window (
NOTES.md, scratch files). - Select: Pull only the exact files, memories, or tool schemas needed right now (Just-in-Time retrieval!).
- Compress: Offload giant tool outputs and run Trajectory Compaction at ~70% fill.
- Isolate: Delegate noisy sub-tasks (e.g., searching 30 files) to a Sub-Agent whose own messy context is discarded once it returns a clean 1-paragraph summary!
2. Tool-Output Offloading: Pointers Instead of Raw Dumps
Toggle Inline Raw Dump vs. Offload to File in the mini-lab below to see the massive 10-turn token savings!
logs/out_4.json) and returning only a 10-line summary + file path saves 95% of context tokens!Clean Offloading Rule
Whenever a tool output exceeds e.g. 4,000 characters:
- Save the full payload to
/scratch/tool_<id>.txt. - Return ONLY the first 20 lines + schema/count +
"Full output saved at /scratch/tool_<id>.txt — use grep/read_lines to inspect specifics."!
Tool-Output Offloading Savings (10-Step Agent Run)
3. Trajectory Compaction & Persistent Structured Notes
Compaction resets bloat while preserving exact architectural decisions, edited files, and remaining TODOs.
goals, files_edited, next_step), resetting context bloat on long-horizon coding/research runs!What a Good Compaction Summary MUST Preserve
- User's exact goal & constraints (never drop negative constraints like "Do NOT modify the database schema"!)
- Files created/edited & key symbol names
- Failed approaches already ruled out (so the agent doesn't repeat them!)
- Exact next concrete step
Worked Example: Isolating a Noisy Codebase Search via Sub-Agent
Main agent needs to find where OAuth cookies are configured across 40 files.
Adds 60,000 tokens of irrelevant code permanently into the main conversation!
Which Context Engineering technique lets a main agent investigate 30 noisy files WITHOUT adding those 30 files to its own context window?
During Context Compaction, what happens if your summarizer accidentally omits a failed approach ('Tried next/font/google, crashed Docker build')?
The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.
Instead of pre-loading 50 docs into the prompt upfront, you give the agent lightweight pointers (file paths, table names, search tools) so it loads only the exact 20 lines it needs right when it needs them!
Long-Horizon Context Compaction Animator (Beating Context Rot)
Watch context utilization climb toward 80% during a long coding run, then compact cleanly into a 18% high-signal handoff summary.
NOTES.md), Select (Just-in-Time loading), Compress (Tool Offloading + Compaction), and Isolate (Sub-Agents).Autonomous Coding Agents (Claude Code, Cursor, Antigravity)
Combines Tool-Output Offloading, Sub-Agent Isolation, and /compact Trajectory Compaction for hours-long tasks.
# Context Offloading: Spill Large Tool Outputs to Disk & Keep a Compact Handle in Prompt
def offload_large_tool_output(tool_name: str, payload: str, max_inline_chars: int = 120) -> str:
if len(payload) <= max_inline_chars:
return payload
artifact_id = f"/tmp/{tool_name}_output.txt"
preview = payload[:80].replace("\n", " ")
# In production, write `payload` to artifact_id and let the agent grep/read slices on demand
return (
f"[OFFLOADED {len(payload)} chars -> {artifact_id}]\n"
f"Preview: '{preview}...'\n"
f"Hint: Use read_slice('{artifact_id}', start, end) to inspect specific lines."
)
huge_log = "INFO: request ok\n" * 40
print(offload_large_tool_output("fetch_logs", huge_log))