Filed underL06 · AI & Automation
Published
Reading time23 min
Updated
Field notes · L06 AI & Automation

Context engineering for long-running agentsCompaction, memory, sub-agents and what to leave out

Context engineering is budgeting tokens: what goes in, what gets compacted, what lives in memory or sub-agents. Patterns, configs and a cost model.

The short answer

Context engineering is the work of deciding which tokens a model sees on each call of an agent loop: what you load up front, what you fetch on demand, what you summarise, what you store outside the window and what you never send at all. It matters because model accuracy falls as the context grows, even well inside the advertised window. So the window is a budget to spend, not a container to fill. For long-running agents, the toolkit is small and well understood: trim tool results, compact history, keep durable state in external files, isolate noisy work in sub-agents, and arrange everything so the prompt cache keeps hitting.

The rest of this post is how we'd actually build that, where each technique fails, and a budget template you can lift.

01What is context engineering, and how is it different from prompt engineering?

Prompt engineering is writing good instructions. Context engineering is managing the whole state the model receives on every inference: system prompt, tool definitions, retrieved documents, message history, tool results, memory, and the agent's own earlier reasoning.

Anthropic's definition is the most precise one in circulation: "the set of strategies for curating and maintaining the optimal set of tokens (information) during LLM inference" (Anthropic, Effective context engineering for AI agents, September 2025). Cognition reached the same term from the other direction, calling it the next level of prompt engineering for dynamic systems where no human is hand-assembling each call (Cognition, Don't Build Multi-Agents, June 2025).

The distinction matters in practice because a single-shot prompt is static and you can eyeball it. An agent's context is assembled by code (the agent harness around the model), grows with every tool call, and is different on turn 80 from turn 3. Nobody reads turn 80. That is where agents degrade, and it is an engineering problem, not a writing problem.

02Why a bigger context window doesn't solve it: context rot

Current frontier models ship with very large windows. Claude Opus 5.5 and Sonnet 5.5 have 1M-token windows, and Anthropic bills the full window at standard per-token rates (models overview, pricing). The obvious temptation is to stop worrying and send everything.

Don't. Three lines of evidence say quality degrades with length, long before you hit the limit:

  • Position effects. Liu et al.'s Lost in the Middle found a U-shaped curve: models use information at the start and end of the input far better than information in the middle, including models built for long contexts (arXiv:2307.03172, published in TACL, 2024).
  • Length alone. Chroma tested 18 models, including GPT-4.1, Claude 4, Gemini 2.5 and Qwen3, and found that "models do not use their context uniformly; instead, their performance grows increasingly unreliable as input length grows", even on simple retrieval tasks (Chroma, Context Rot, July 2025).
  • Distractors. In the same study, a single plausible-but-wrong passage reduced accuracy, and multiple distractors compounded it. Stale tool output in an agent's history is exactly this: plausible, outdated text.

Anthropic frames the consequence as an attention budget: every token depletes it, so context is "a finite resource with diminishing marginal returns" (source). Anthropic's own compaction docs say the same thing more bluntly: compaction exists partly to keep the active context small, "because response quality degrades as a conversation grows" (compaction overview).

One more practical detail. Claude 4.7 and later use a tokenizer that produces roughly 30% more tokens for the same text than earlier models (pricing). If you set budgets in tokens on an older model and migrated, your budgets are now wrong.

03Where the tokens go in a long-running agent

Before choosing techniques, measure. In every agent we have looked at, the context breaks down into the same six components, and they behave very differently:

Component Grows with Changes how often Typical problem
System prompt Nothing (fixed) Per deploy Bloated with edge-case rules
Tool definitions Number of tools Per deploy 40 tools when 8 would do
Durable memory (notes, plans) Task progress Every few turns Absent, so state lives in history
Message history Turns Every turn Never pruned
Tool results Tool calls × output size Every turn The dominant term, by far
Model reasoning (thinking) Turns × effort Every turn Kept forever by default on some models

Tool results are almost always the problem. A single cat of a log file, a search returning 50 hits or an unpaginated API response can be tens of thousands of tokens, and the model usually needs a handful of lines from it. Anthropic's pricing page gives useful reference sizes for fetched content: roughly 2,500 tokens for an average web page and 25,000 for a large documentation page (pricing, web fetch).

Instrument this. Log input tokens per component per turn. The Messages API reports cache reads, cache writes and, when context editing runs, exactly how many tokens each edit cleared (context_management.applied_edits) (context editing docs). If you cannot plot "tokens by component over turns" for your agent, you are guessing.

04The five levers, in order of how often we reach for them

Diagram
                ┌──────────────────────────────────────────────┐
stable prefix   │ tools │ system prompt │ memory index (small) │
                │ ← cached, rarely changes                     │
                ├──────────────────────────────────────────────┤
compacted past  │ summary of turns 1..k (compaction block)     │
                │ ← rewritten occasionally                     │
                ├──────────────────────────────────────────────┤
working set     │ recent turns k+1..n, trimmed tool results    │
                │ ← grows, cleared by rule                     │
                └──────────────────────────────────────────────┘
outside the window: memory files │ full tool outputs on disk
                    sub-agent transcripts

The goal is that layout. Stable things at the front, where the cache can hold them. A compacted summary of the distant past. A bounded working set. Everything else outside the window, addressable by path.

1. Trim tool results at the source

This is the cheapest and most effective lever, and most teams skip it because it is not in any framework's default path. Every tool should return the smallest useful result and a handle to the rest.

The pattern: write the full output somewhere the agent can reach (a scratch directory, object storage), return a head, a tail, a size and a path. The agent can grep or page through the file if it needs more. This is just-in-time retrieval applied to your own tool outputs.

python
import hashlib
import pathlib

SCRATCH = pathlib.Path("/var/agent/scratch")
MAX_CHARS = 8_000          # ~2k tokens; tune per tool
HEAD, TAIL = 5_000, 2_000

def trim_tool_output(tool_name: str, output: str) -> str:
    """Return a bounded tool result; spill the full text to disk."""
    if len(output) <= MAX_CHARS:
        return output

    digest = hashlib.sha256(output.encode()).hexdigest()[:12]
    path = SCRATCH / f"{tool_name}-{digest}.txt"
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(output)

    lines = output.count("\n") + 1
    return (
        f"[output truncated: {len(output):,} chars, {lines:,} lines]\n"
        f"[full output saved to {path}; use read_file with a line range or grep to inspect]\n"
        f"--- first {HEAD:,} chars ---\n{output[:HEAD]}\n"
        f"--- last {TAIL:,} chars ---\n{output[-TAIL:]}"
    )

Keep head and tail rather than just head. Errors, exit codes and summaries usually live at the end of command output. Make truncation visible in the text, so the model knows it is looking at a partial result and doesn't reason as if it has the whole thing.

Beyond truncation:

  • Paginate by default. Search tools return 10 results with a cursor, not 200.
  • Project fields. If an API returns 60 fields per record and the agent uses five, return five.
  • Prefer identifiers to content. Return file paths, row IDs and URLs; let the agent load what it decides it needs. Anthropic describes this as keeping "lightweight identifiers" and loading data dynamically at runtime (source).
  • Keep errors. Don't strip failed tool calls from history. Manus found that leaving failed actions and error messages in context helps the model avoid repeating them (Manus, Context Engineering for AI Agents, July 2025). Trim them, but keep them.

2. Clear stale tool results by rule

Once the agent has read a file and acted on it, the raw contents are usually dead weight. Clearing old tool results is the lightest form of compaction: no summarisation, no model call, just a placeholder where the old output was.

On the Claude API this is a server-side context edit. You keep the full history in your application; the API strips old tool results before the prompt reaches the model (context editing docs):

python
import anthropic

client = anthropic.Anthropic()

response = client.beta.messages.create(
    betas=["context-management-2025-06-27"],
    model="claude-opus-5-5",
    max_tokens=8192,
    tools=tools,
    messages=messages,
    context_management={
        "edits": [
            {
                "type": "clear_tool_uses_20250919",
                # Start clearing once input passes 120k tokens
                "trigger": {"type": "input_tokens", "value": 120_000},
                # Always keep the five most recent tool call/result pairs
                "keep": {"type": "tool_uses", "value": 5},
                # Clear enough per pass to justify breaking the cache (see cost model)
                "clear_at_least": {"type": "input_tokens", "value": 40_000},
                # Never clear results the agent must keep re-reading
                "exclude_tools": ["memory"],
            }
        ]
    },
)

for edit in response.context_management.applied_edits:
    log.info("context edit", type=edit.type, cleared=edit.cleared_input_tokens)

Defaults if you omit the options: trigger at 100,000 input tokens, keep the last three tool uses. There is also clear_tool_inputs to strip the call parameters as well as the results, which helps when the agent writes large files through a tool and the inputs themselves are big.

The failure mode is obvious once you have seen it: the agent needs something it read 40 turns ago, finds a placeholder, and either re-reads it (fine, if your tool is cheap and idempotent; idempotency keys help when it isn't a pure read) or hallucinates it (not fine). Mitigations: exclude tools whose results are reference material, keep keep high enough to cover a typical edit-test loop, and make sure anything worth remembering was written to memory before it can be cleared.

3. Compact the history

Compaction replaces older turns with a model-written summary. It is the right tool when the conversation itself has become long: many turns of reasoning, decisions and partial results, not just big tool outputs.

Anthropic's description of a good compaction is the one to design to: preserve architectural decisions, unresolved bugs and implementation details; discard redundant tool output (source).

Both major APIs now do this server-side:

  • Claude API, two flavours. Threshold compaction (compact_20260112, beta header compact-2026-01-12) triggers when input crosses a value you set; the default is 150,000 tokens and the minimum is 50,000 (docs). On-demand compaction (beta header compact-2026-09-04) lets your application decide when to compact, can run in the background, and can keep recent turns verbatim; Anthropic recommends it wherever available (compaction overview).
  • OpenAI Responses API. A context_management entry of type compaction with a compact_threshold, or an explicit call to /responses/compact. The compaction item is encrypted and opaque, and OpenAI tells you not to prune what /responses/compact returns (OpenAI compaction guide).

Threshold compaction on Claude, with your own summarisation instructions:

python
COMPACTION_INSTRUCTIONS = """\
Summarise this agent session so a fresh instance can continue it without the transcript.
Keep, verbatim where possible:
- The user's goal and any constraints or acceptance criteria they stated.
- Decisions made and the reason for each (one line each).
- Current state: what is done, what is in progress, what is next.
- Exact identifiers: file paths, function names, ticket IDs, URLs, commands that worked.
- Open problems, failing tests and their error messages.
Drop: raw tool output, file contents, exploratory dead ends that were abandoned
(record only the conclusion), and pleasantries.
Format as Markdown with the headings: Goal, Decisions, State, Identifiers, Open issues.
"""

response = client.beta.messages.create(
    betas=["compact-2026-01-12"],
    model="claude-opus-5-5",
    max_tokens=8192,
    system=[{"type": "text", "text": SYSTEM_PROMPT,
             "cache_control": {"type": "ephemeral"}}],
    tools=tools,
    messages=messages,
    context_management={"edits": [{
        "type": "compact_20260112",
        "trigger": {"type": "input_tokens", "value": 180_000},
        "instructions": COMPACTION_INSTRUCTIONS,
    }]},
)
messages.append({"role": "assistant", "content": response.content})

# Top-level usage excludes the compaction pass; sum iterations for true cost.
total_in = sum(i.input_tokens for i in response.usage.iterations)

Two details that bite people. First, the instructions field replaces the default summarisation prompt entirely, so write a complete one. Second, top-level usage.input_tokens excludes the compaction call; sum usage.iterations if you are tracking spend. Put cache_control on the end of the system prompt so it stays cached independently of each new summary, which the docs recommend for exactly this reason (docs).

The snippets are separate on purpose. At the time of writing, the docs don't say whether clear_tool_uses_20250919 and compact_20260112 can share one edits array, or in what order, so test that before relying on it. On-demand compaction is stricter: its compaction parameter can't be sent on the same request as context_management at all (compaction on demand).

Where compaction fails. Summaries are lossy, and the model doing the summarising doesn't know what turn 140 will need. The classic losses are exact strings (an error message, a flag that worked, a column name) and negative results ("we tried X; it doesn't work because Y"), which disappear and then get retried. Two fixes: tell the summariser explicitly to keep identifiers and dead ends, as above, and write anything that must survive to a memory file before compaction, not after.

When not to compact: short tasks that finish well inside a comfortable budget. Compaction costs a full pass over the history, and an agent that completes in 30 turns gains nothing from it.

4. Keep durable state in external memory files

The window is working memory. Anything the agent must not lose belongs outside it: the plan, progress, decisions, gotchas, the definition of done. The agent reads it at the start of a session and updates it as it goes.

This pattern is now well established. Claude Code uses CLAUDE.md for project instructions and keeps to-do lists; Anthropic cites agents maintaining a NOTES.md as structured note-taking (source). Manus treats the file system as "the ultimate context": unlimited, persistent, and directly operable by the agent, and uses a constantly rewritten todo.md to push the current objective back into the end of the context, where attention is strongest (Manus).

Anthropic's harness for multi-session coding agents is the most concrete reference we know of. An initialiser session creates a progress file, a feature list and an init.sh; each later session reads them, works on one feature, verifies it end to end, commits and updates the progress file. They chose JSON for the feature list because "the model is less likely to inappropriately change or overwrite JSON files compared to Markdown files" (Anthropic, Effective harnesses for long-running agents, November 2025).

On the Claude API, the memory tool (memory_20250818) gives the model a standard file interface under /memories, which your application implements against whatever storage you choose. It needs no beta header, and the API injects a short protocol telling the model to check memory first and to "assume interruption" (memory tool docs). You can equally give the agent ordinary file tools and a convention. The mechanism matters less than the schema.

A memory layout we'd start with:

Text
/memories/
  README.md          # ≤ 40 lines. Index: what each file is for. Loaded every session.
  task.json          # Goal, acceptance criteria, constraints. Written once, rarely edited.
  progress.json      # Items with status + one-line evidence ("tests pass: run 2026-02-04T14:02").
  decisions.md       # Append-only. Date, decision, why, what was rejected.
  gotchas.md         # Things that wasted time. "pnpm, not npm". "Staging DB needs VPN."
json
{
  "goal": "Migrate billing service from Stripe Charges API to PaymentIntents",
  "acceptance": ["All billing integration tests pass", "No Charges API calls in src/"],
  "items": [
    {"id": "B1", "desc": "Replace charge creation in invoice.py", "status": "done",
     "evidence": "tests/test_invoice.py green, commit 3f2a9c1"},
    {"id": "B2", "desc": "Handle requires_action for 3DS", "status": "in_progress",
     "evidence": null, "note": "webhook handler stubbed, not wired"},
    {"id": "B3", "desc": "Remove legacy refund path", "status": "todo", "evidence": null}
  ]
}

(That task is illustrative.) The rules that make this work:

  • Small index, loaded always; detail, loaded on demand. Don't preload the whole memory directory. Load README.md; let the agent open the rest.
  • Status needs evidence. "Done" with no proof is how agents declare victory early, which is one of the failure modes Anthropic's harness post calls out, and one of the agent failure modes in production we see most.
  • Bound it. Cap file sizes and expire stale files, as the memory tool docs advise. A memory directory that grows forever is just context rot with extra steps.
  • Treat it as untrusted input. Memory is written by a model that reads untrusted content. A prompt injection that lands in gotchas.md persists across every future session. Validate paths (the docs spell out traversal attacks such as /memories/../../secrets.env), and review what gets written. We cover the injection side in Securing AI agents: prompt injection, tool permissions and least privilege for MCP.

5. Isolate noisy work in sub-agents

A sub-agent is a separate model call with its own fresh context, a narrow brief, and an obligation to return a short result. Its value for context engineering is isolation: the 150,000 tokens of grepping, reading and dead ends stay in the sub-agent's window, and the parent receives a summary. Anthropic suggests those summaries are typically 1,000 to 2,000 tokens (source). Claude Code's sub-agents work the same way: each runs in its own context window and only returns a summary to the main conversation (Claude Code docs).

This is powerful and expensive. Anthropic's research system found multi-agent runs used about 15× the tokens of a chat, against about 4× for a single agent, while outperforming a single-agent baseline by 90.2% on their internal research eval (Anthropic, How we built our multi-agent research system, June 2025). Cognition argues the opposite default: single-threaded agents, because "actions carry implicit decisions", and parallel agents that cannot see each other's decisions make conflicting ones (Cognition). We weigh the two in our post on multi-agent architecture.

Both are right, about different work. Our rule:

  • Use sub-agents for read-heavy, write-light, separable work. Searching a codebase, surveying documentation, triaging logs, researching options. The output is a finding, not a change.
  • Keep writes in one thread. Anything that edits shared state (code, config, data) should be done by one agent that holds the decisions. Parallel writers produce merge conflicts in the best case and inconsistent designs in the usual one.
  • Define the return contract. The sub-agent's final message is the only thing the parent sees, so specify its shape.

A sub-agent brief we use as a starting point:

markdown
---
name: codebase-investigator
description: Answers a specific question about this repository by searching and reading code. Use for "where/how is X done" questions. Does not edit files.
tools: Read, Grep, Glob
model: sonnet
---

You answer one question about this codebase. You cannot edit files.

Return at most 300 words in exactly this format:

ANSWER: one or two sentences.
EVIDENCE: up to 8 bullets, each `path:line` and what it shows.
CONFIDENCE: high | medium | low, and why.
NOT CHECKED: anything relevant you did not look at.

Do not paste file contents. Do not describe your search process.

The NOT CHECKED line earns its place. A sub-agent's summary hides its coverage, and the parent will otherwise treat a partial search as exhaustive.

05How prompt caching interacts with all of this

Every technique above edits the context. Prompt caching rewards you for not editing it. You have to design for both.

The mechanics on the Claude API: the cache is a prefix match over tools → system → messages, and a change at any level invalidates that level and everything after it. Cache reads cost 0.1× base input on most models, 0.05× on Opus 5.5 and 0.025× on Fable 5.1; five-minute writes cost 1.25×, one-hour writes 2× (prompt caching docs, pricing). Manus calls KV-cache hit rate "the single most important metric for a production-stage AI agent", given its roughly 100:1 input-to-output ratio (Manus). Caching is one lever in wider LLM cost engineering, alongside model routing and batching.

What follows from that:

  • Never put volatile content in the prefix. No timestamps, request IDs or per-user data in the system prompt. Put them in the latest user message.
  • Don't add and remove tools mid-session. Changing tool definitions invalidates the entire cache. Manus masks unavailable tools rather than removing them. If you have many tools, decide the set at session start.
  • Make history append-only between compactions. Serialise deterministically (stable JSON key order), never rewrite earlier turns, and the cache keeps hitting.
  • Batch your clearing. Each tool-result clear breaks the cache from that point and forces a rewrite. The docs recommend clear_at_least so each invalidation clears enough to be worth it (context editing docs).
  • Watch the TTL. If a turn includes a human approval or a slow job that takes longer than five minutes, the default cache expires. Use the one-hour TTL on the stable prefix.
  • Keep thinking blocks if cache matters. Clearing old thinking (clear_thinking_20251015) invalidates the cache; keeping it preserves hits.

06The context budget: a reference allocation and decision matrix

This is the asset we wish existed when we started. Use it in a design review: fill in the right-hand column for your agent, and anything that exceeds its line gets a named mitigation.

Reference budget for a long-running agent

Set an operating ceiling well below the model's window and budget against that. We start at 200k tokens even on 1M-token models, because of the degradation evidence above, and move it only when evals justify it.

Component Budget (of 200k ceiling) Enforcement mechanism Your agent
Tool definitions ≤ 8k (4%) Review in PR; ≤ ~15 tools per agent; split by role
System prompt ≤ 6k (3%) Review in PR; move edge cases to retrievable docs
Memory index (always loaded) ≤ 2k (1%) Hard cap on README.md; detail files loaded on demand
Compacted summary ≤ 10k (5%) Compaction instructions specify length and headings
Working set: recent turns + tool results ≤ 140k (70%) Per-tool output cap; clear_tool_uses trigger
Headroom for current turn's output and thinking ≥ 34k (17%) Compaction trigger set below ceiling

Thresholds that follow from it: compact at about 160k (80% of ceiling); start clearing tool results at about 120k; cap any single tool result at about 2k tokens unless the tool is specifically for reading.

Symptom → technique matrix

Symptom you observe Most likely cause First fix Second fix
Cost per task climbs with task length, quality is fine Low cache hit rate Stabilise prefix; check for volatile tokens and tool churn One-hour TTL
Agent forgets earlier decisions after a while Lossy compaction or cleared results Write decisions to memory file before compaction Stronger compaction instructions
Agent retries an approach that already failed Negative results lost gotchas.md / decisions log; keep error results Instruct summariser to keep dead ends
Agent quality drops mid-session, recovers in a fresh one Context rot Lower clearing and compaction triggers Move exploration to sub-agents
One tool call blows the budget Untrimmed tool output Trim at source with spill-to-disk Pagination, field projection
Agent declares done too early No external definition of done task.json acceptance + evidence-required status Separate verifier sub-agent
Parallel agents produce inconsistent changes Split decisions Single writer; sub-agents read-only Shared decisions file, sequential merges
Agent picks wrong tool among many Tool bloat Cut tool count; clearer names and descriptions Role-specific agents

Worked cost model: caching versus clearing

The question we get most is whether clearing tool results saves money. On current pricing, usually not. Clear for quality, not for cost. Here is the arithmetic.

Assumptions (illustrative, stated so you can substitute your own): Claude Opus 5.5 at $4/MTok input, $5/MTok five-minute cache writes, $0.20/MTok cache reads (pricing). A 60-turn session. A 20k-token stable prefix. Each turn appends 3k tokens. Every turn lands within the cache TTL. Output and thinking tokens are ignored, since they're identical in both cases.

Without caching. Input on turn n is 20k + 3k·n. Total across 60 turns = 60 × 20k + 3k × (60 × 61 / 2) = 1.2M + 5.49M = 6.69M tokens × $4 = $26.76.

With caching. Turn 1 writes 23k. Each later turn reads the previous prefix and writes 3k new. Writes = 23k + 59 × 3k = 200k × $5/MTok = $1.00. Reads = Σ (20k + 3k·(n−1)) for n = 2..60 = 59 × 20k + 3k × 1,770 = 6.49M × $0.20/MTok = $1.30. Total ≈ $2.30, about 91% less.

Now add one clearing event. Say that, at 150k tokens, a clear removes 70k of stale results, leaving 80k. The next request must rewrite that 80k: 80k × $5/MTok = $0.40 one-off. Each later turn now reads 70k fewer tokens: 70k × $0.20/MTok = $0.014 saved per turn. Break-even is $0.40 / $0.014 ≈ 29 turns.

So on a model with cheap cache reads, a clear pays for itself only if the session runs roughly 30 more turns afterwards. Without caching, the same clear would pay back immediately. That is the interplay in one sentence: caching makes long contexts cheap, so the reason to keep them short is quality, and you should tune clearing triggers against evals, not the invoice. On models with a 0.1× read multiplier the break-even shortens (to about 14 turns at the same $4 base price), but the conclusion holds.

07What to leave out

The title promised this, and it is the most underrated part of context engineering. Things we remove by default:

  • Tools the agent doesn't need for this task. Every definition costs tokens on every call and dilutes tool selection.
  • Full file contents when a path will do. Let the agent open what it decides to open.
  • Duplicate information. The same schema in the system prompt, a retrieved document and a tool result is three copies competing for attention.
  • Long few-shot transcripts. A couple of short, varied examples beat ten similar ones. Manus warns that uniform examples make agents over-imitate and drift into repetitive behaviour.
  • Edge-case rules in the system prompt. If a rule applies to 2% of tasks, put it in a document the agent can retrieve when the case arises.
  • Raw conversation history across sessions. Carry forward memory files and a summary, never the transcript.
  • "Just in case" retrieval. Preloading the top 20 RAG chunks is a distractor generator. Retrieve when the agent asks, and retrieve less.

A useful test for each block of context: if this were deleted, would the model's next action change? If you can't say yes, it probably shouldn't be there.

08Where this crosses into the rest of the stack

Context engineering looks like an AI-layer concern, but most of the fixes live elsewhere. Tool outputs are only as trimmable as the APIs behind them allow, so pagination and field selection are a software-layer job. Just-in-time retrieval depends on data that is indexed, permissioned and addressable, which is the data layer; permission-aware RAG is the hard part of that. Memory files are persistent, model-written state: they need the same path validation, retention and review as any other untrusted input, which is security. And because tool outputs spill to disk, the sandbox they run in matters too; we cover that in Sandboxing AI agents that run code: containers vs gVisor vs Firecracker, and locking down egress. The teams that get agents to behave over hundreds of turns are usually the ones that treat the context as an interface between all of those layers, not a prompt.

09FAQ

Is context engineering just RAG with a new name?

No. Retrieval is one input. Context engineering also covers what you remove (clearing, compaction), what you keep outside the window (memory), how you split work (sub-agents), and how you order content for caching. A RAG pipeline that preloads 20 chunks on every turn is often a context-engineering problem, not a solution.

Should we just use the 1M-token window and skip all this?

For a one-off analysis of a large document, maybe. For an agent that runs many turns, no. Accuracy degrades with length well inside the window, and stale tool output acts as a distractor. Set a lower operating ceiling, measure quality against it, and raise it only if evals improve.

Compaction or a fresh session with memory files?

Compaction when the task is continuous and the recent reasoning matters. A fresh session that reads memory files when the task has natural boundaries (one feature, one ticket) and you can write a clean handover. For multi-day work we prefer fresh sessions: the handover is explicit, inspectable and testable, and a summary is neither.

How many sub-agents should we run?

As few as solve the problem. Start with one agent. Add a read-only sub-agent when exploration is visibly polluting the main context. Parallelise only independent, read-heavy work, and expect token use to rise several-fold when you do.

Does context editing break prompt caching?

Yes, from the point of the edit onwards. Clearing tool results or old thinking invalidates the cached prefix after it, and the next request pays cache-write rates on what remains. Batch clears with clear_at_least, keep the system prompt and tools before any edited region, and check the break-even for your own session lengths.

How do we know if our context engineering is working?

Track three numbers per task: cache hit rate (cache-read tokens over total input), peak input tokens, and task success on a fixed eval set run at several session lengths. If success falls as sessions get longer, you have context rot to fix; trajectory evals show where in the run it starts. If cost rises faster than length, you have a caching problem.

If this is the layer that hurts, we should talk.

Tell us which layer hurts →