Harness Engineering for Agents
Layered Context Engineering
A production agent's context window is not a flat buffer. It is a layered resource where each layer serves a different purpose and obeys different compaction rules. The session loop must decide what to keep always, what to inject on demand, what to compress, and what to discard. Get these decisions wrong and the agent either burns tokens on irrelevant history or loses the conversational thread mid-task. Layered context engineering treats the window as a stack of independently managed segments, each with its own retention policy, injection trigger, and compaction strategy.
Always-On Instructions Versus Progressive Disclosure
Every turn begins with the same core: system instructions defining the agent's identity, output format, and safety constraints. These always-on instructions consume a fixed token budget on every step. Their cost is predictable and bounded. The trade-off is that they cannot address every possible skill or document the agent might need. Packing too much into the always-on layer dilutes attention across rarely-used directives.
The alternative is progressive disclosure: load instructions and reference material only when a skill or document is relevant. Skills folders, tool descriptions, and long reference documents sit outside the always-on layer and are injected as the agent's reasoning path demands them. A file-editing skill is disclosed when the agent decides to modify a file, not before. Each disclosed payload carries a token cost only when used, but the agent must first recognize the need and request the material, adding a round-trip.
| Layer | Injection trigger | Token cost | Risk |
|---|---|---|---|
| Always-on instructions | Every turn | Fixed, predictable | Context dilution |
| Progressive disclosure | On demand, skill-selected | Variable, per-use | Missed disclosure, latency |
Production systems blend both: a compact always-on identity (200-500 tokens) with a registry of skills that the agent can request by name. The session loop checks the disclosure request and injects the skill preamble before the next model call. The agent never sees skills it does not need.
Mental hook: Always-on pays every step; progressive pays only when used. Design the always-on layer as the irreducible minimum, not the complete manual.
Per-Step Dynamic Injection and Memoization
Not all context is static. Some values depend on the current step: the time remaining, the list of open files, the last error message, a counter of retries consumed. Per-step dynamic injection computes these fragments at the start of each turn and appends them to the context. The injection function receives the session state and returns a string or message block. This keeps the context responsive to real-time conditions without the agent having to ask.
Computing the same fragment on every turn is wasteful when the underlying value has not changed. Memoization caches the result keyed on the state inputs that affect it. A ctx.memo wrapper records the input hash and the output string. On subsequent turns, if the inputs match, it returns the cached fragment. This stabilizes the prompt in two ways: it avoids redundant computation and, more importantly, it preserves the exact same token sequence across turns when nothing relevant changed, which keeps the provider's prompt-cache hit rate high.
The memoization key must include every state variable that the injection reads. Missing a dependency produces stale context. Over-specifying the key collapses the cache on every turn. The design rule is: key on the minimum set of variables that would produce a different injection value.
Common trap: Memoizing a dynamic fragment by turn number alone, then wondering why the provider's prompt cache misses constantly. The cache depends on the prefix sequence matching byte-for-byte, not on logical equivalence. Use content-addressed keys, not monotonic counters.
Two-Stage Compaction
Context grows monotonically. Every tool call adds its output. Every turn adds a message pair. Without intervention, the window fills and the model begins to forget earlier context. Two-stage compaction shrinks the history in two passes, each with different information-loss characteristics.
Stage one is tool-output stubbing. Long tool outputs, especially file reads, search results, and shell logs, are replaced with a short stub: the output's command, its exit code, and a SHA-256 hash of the full content. The stubbed entry consumes roughly 100 tokens instead of thousands. The model can still see that the tool ran and exited successfully, but it cannot see the output content. If the agent needs the content again, it must re-read the file. The stub keeps the reasoning trace intact while discarding the bulk data.
Stage two is LLM checkpointing. Once the remaining history exceeds a threshold, the oldest messages are replaced with a single generated summary. The session loop sends the oldest N messages to the model with a prompt like "Summarize the conversation so far, preserving all decisions, constraints, and pending actions." The summary replaces those messages. The model loses fine-grained detail but retains the high-level plan and reasoning chain.
| Stage | Operation | Token saved | Information preserved |
|---|---|---|---|
| Tool-output stubbing | Replace long outputs with stubs | 70-90% per output | Existence and exit code only |
| LLM checkpointing | Replace old messages with summary | 80-95% per block | Decisions, constraints, plan |
The two stages compose because they target different kinds of content. Stubbing removes data noise while preserving conversational flow. Checkpointing compresses the flow itself. Running stubbing first reduces the volume that the checkpointing stage must summarize, which improves summary quality.
Watch out: Stubbing a tool output that the next turn's reasoning step would have quoted verbatim forces the agent to re-read. The compaction policy must know which outputs are worth keeping by cost of re-computation versus cost of retention. Outputs from idempotent reads can be stubbed aggressively; outputs from non-idempotent writes (like a file edit confirmation) should survive stubbing.
Tail Preservation and Workflow Handoffs
Compaction must never touch the most recent context. The tail is a configurable window, typically 10,000-20,000 tokens at the end of the conversation, that is preserved verbatim. It contains the last few turns of reasoning, the most recent tool outputs, and any pending agent state. Compaction stops at the tail boundary. This guarantees that the model always sees the immediate conversational history in full, no matter how aggressively the older history is compressed.
The tail window size is a tuning parameter. Too small, and the model loses the reasoning chain that produced the current state. Too large, and compaction has little effect. The heuristic is to set the tail large enough to hold the last 2-3 complete ReAct cycles plus any in-flight tool outputs.
Workflow handoffs occur when a long-running task (a multi-minute test suite, a webhook wait, a subagent running independently) must continue across compaction boundaries. The handoff writes a structured checkpoint document: the task's current state, the pending actions, and the resources it holds. That document sits at the tail boundary. When compaction triggers, the handoff document survives because it is in the tail. The model on the next turn reads the handoff and resumes the workflow without needing the earlier conversation that led to it.
The relationship between workflows and the tail is symmetric. A workflow that writes its state to a typed document (as covered in commit-first architecture) can be resumed by reading that document back into the tail. The tail preserves the handoff point; the workflow document preserves the execution state.
Mental hook: Compaction shrinks history; the tail preserves recency. Workflow handoffs bridge across compaction boundaries by writing durable state into the preserved tail segment.
AI-generated study article from SophistAI. Sign up free to study it with an AI tutor.