The practice of curating the optimal set of tokens that enters the model’s context window during inference. As Anthropic’s Applied AI team puts it, the question shifts from “what words go in the prompt?” to “what configuration of context is most likely to generate our model’s desired behavior?”

Mario Zechner frames the same idea operationally: exactly controlling what goes into the model’s context yields better outputs. The problem: most existing agent harnesses make context engineering difficult or impossible. They inject content behind the scenes that isn’t surfaced in the UI, making it hard to reason about or correct.

Two complementary perspectives in this page

Anthropic’s piece supplies the why (architectural foundations: attention budget, context rot, n² scaling) and a high-level anatomy (system prompts at the right altitude, token-efficient tools, canonical examples, just-in-time retrieval). The Vienna-school practitioners (Mario Zechner, Lucas Meijer, Pi (Coding Agent)) supply concrete how — observable harnesses, the 50% rule, the don’t-argue rule, file-as-state, session branching. The combination is the discipline.

Why Context Is a Finite Resource

Anthropic’s central reframe: context is not just “the prompt” but the entire holistic state at any inference step (system prompt, tools, MCP, retrieved data, message history). And it is finite for two architectural reasons:

  1. Context rot (Chroma research) — as token count grows, recall accuracy degrades across all current models. The degradation is gradual, not a cliff, but it’s real.
  2. n² attention pairs — transformers compute pairwise attention across every token; the longer the context, the thinner the attention budget spread per pair. Training distributions also skew shorter, so models have less practice with very long contexts.

The implication: treat context as a scarce attention budget. Every token spent on noise depletes the budget available for real work. Goal: the smallest possible set of high-signal tokens that maximize the likelihood of the desired outcome.

This is the architectural foundation under Lucas Meijer’s practical 50% rule below: he observed in practice what the research now characterizes formally.

Why Context Is the Bottleneck

Models don’t perform uniformly across all inputs. The same model can produce dramatically different outputs depending on:

  • How much total context is occupied (fuller context -> more noise, less focus)
  • What specific content is present (irrelevant tool definitions crowd out relevant code)
  • What’s hidden vs. visible (you can’t fix what you can’t see)
  • When things get loaded (session-start vs. on-demand)

Context engineering is the discipline of managing all of these. It’s engineering in the literal sense: deliberate design of a system, with tradeoffs measured against outcomes.

The Anatomy of Effective Context (Anthropic)

Anthropic’s piece breaks the holistic context into four levers, each with a guiding heuristic:

ComponentHeuristicCommon failure mode
System promptRight altitude — Goldilocks zone between brittle if-else hardcoding and vague high-level guidance that assumes shared contextStuffing edge cases as rules; or skeletal prompts that leave the model guessing
ToolsSelf-contained, robust to error, unambiguous in intent; minimal viable setBloated toolsets with overlapping functions; if a human can’t say which tool to use, the agent can’t either
Examples (few-shot)A small set of diverse, canonical examples, not an exhaustive rule listLaundry-listing every edge case as a separate example
Message historyCurated, tight, informativePassively accumulating tool outputs and chatter

Altitude diagnostic

Brittle = “if user says X, return exactly Y, otherwise call tool Z with parameter…”. Vague = “be helpful and use your judgment.” The right altitude sounds like clear heuristics: what to do, not every step. Start minimal, add only based on observed failure modes.

This anatomy dovetails with Agent Tools - Design Principles (one tool one job, descriptions matter more than the tool), Agent-Computer Interface (ACI) (poka-yoke, format alignment), and Writing Conflict-Free Instructions (precedence and conditional rules in the system prompt).

The Observability Problem

You can’t engineer what you can’t observe. Most harnesses fail here in two ways:

  1. Hidden injection: The harness adds content to the system prompt or messages that’s never shown to the user — tool definitions, memory summaries, retrieved documents, prior session context. You don’t know what the model is actually seeing.

  2. Sub-agent opacity: When a harness spawns a sub-agent, the orchestrating agent decides what context to pass. The user has zero visibility into what that sub-agent saw and what it did. If it fails, debugging requires guessing.

Pi (Coding Agent) was designed from scratch to expose every aspect of the session — every message, every tool call, every result.

Practical Techniques

On-Demand Context Loading

Don’t pay for tool context you aren’t using. Rather than loading all tool definitions at session start (as MCP requires), load them only when needed:

# Agent reads this README only for sessions that need browser tools
@browser-tools/README.md

Result: a browser tools README at 225 tokens vs. 13,700–18,000 tokens for equivalent MCP servers loaded at every session start. See CLI Tools Pattern.

Minimal System Prompts

Pi’s system prompt is under 1,000 tokens total. The rest of the harnesses use 5,000–15,000+ tokens. This is possible because frontier models are RL-trained to understand coding agent tasks — they don’t need extensive instruction. The tokens saved are available for actual work.

Instruction files as bounded behavioral configuration

Kun Chen’s AGENTS.md as a Neural Net metaphor makes the cost model operational. User-level instructions are stable preferences that should be handwritten. Project-level AGENTS.md or CLAUDE.md is a behavioral configuration that can be refined from session evidence. A fixed token budget turns “keep it concise” into an explicit trade-off: add a broad invariant, or remove one, consolidate it, or move a narrow procedure into an on-demand skill.

The important discipline is the backward pass. Use transcripts to identify repeated violations, missing rules, stale rules, and rediscovery. Batch before updating and review the proposed diff. This protects the always-loaded set from becoming a diary of one-off failures.

File-as-State Over Built-in Features

Hidden internal state (built-in todos, plan mode outputs, sub-agent memory) is context you can’t see, edit, or version. File-based equivalents expose the state fully:

  • TODO.md with checkboxes instead of a built-in todo system
  • PLAN.md with sections instead of plan mode
  • Named files for sub-agent artifacts, shareable across sessions

This keeps the context observable and editable — you can co-author PLAN.md with the agent, correct it, and the changes are immediately reflected in subsequent behavior.

Front-Loading Context Gathering

Using a sub-agent mid-session to gather context is a sign you didn’t plan ahead. Better pattern:

  1. Start a dedicated context-gathering session
  2. Produce an artifact (a well-structured document or summary)
  3. Start a fresh implementation session, handing that artifact as context

The implementation session starts clean. The artifact contains exactly what it needs. No context window occupied by tool call outputs from prior exploration.

Session Branching

Pi (Coding Agent)‘s session tree model supports a related technique: branch off a side session to fix a broken tool or explore a design question, then summarize the branch and rewind. The main session is only enriched by the conclusion, not the full exploration trace.

Compaction Management

When a session’s context nears its limit, most harnesses auto-compact: the full conversation is summarized into a shorter representation. This is lossy — detailed proposals, negotiated decisions, and accumulated domain knowledge compress to vague abstractions. A better strategy, documented by Mario Zechner:

  1. At ~20% remaining: ask the agent to write a task-summary.md — proposals verbatim, decisions stated explicitly, next steps listed, relevant file paths included
  2. Iterate on it — there’s still context left; correct the file until it’s accurate. Never trust the first draft.
  3. Quit the session — don’t compact, don’t wait for auto-compact
  4. New session: load spec.md (project context) + task-summary.md
  5. Continue — the summary is the handoff

Advantage over /compact with custom instructions: you inspect and correct the artifact before committing. With built-in compaction you get one shot and can’t fix it.

The file-as-state principle applies here too: the summary file is observable, editable, and versionable. The agent wrote it, you reviewed it, the next session reads it.

The 50% Rule

Lucas Meijer’s hard rule: watch the context percentage shown by your agent. Once you cross 50–60%, the model enters what he calls the “dumb zone” — noticeably degraded output quality as the context becomes noisy. At 50%, start pruning.

In Pi: use /tree to navigate back to a clean branch point and discard the bloated conversation. Options:

  • No summary — throw the branch away (for irrelevant side quests)
  • Summary — compress to a note (for explorations whose outcome is worth keeping)

The insight behind the rule: a shorter, focused context is worth more than a longer one with everything in it.

Don’t Argue — Go Back

When the agent produces something wrong, the instinctive response is to correct it in the same conversation: “No, I didn’t want it like that.” This is a mistake:

  • The wrong direction stays in context, costing tokens
  • The agent carries the prior framing into the new attempt
  • Context lengthens unnecessarily

The correct move: use the session tree (/tree in Pi) to go back to before the wrong turn. Rephrase the prompt from a clean state.

“You should never tell it ‘no I didn’t want it like that’. Don’t argue with these things.” — Lucas Meijer

Query Isolation with jq

For workflows that maintain large JSON state files (porting plans, task databases), never read the full file into context. Use jq or any CLI query tool to extract only the specific fields needed for the current step. A porting plan JSON with 68 file entries stays on disk; the agent queries it for one entry at a time. See Agentic Porting Workflow for a worked example.

Just-in-Time Retrieval vs. Pre-Computation

Anthropic frames a shift in how engineers design retrieval for agents. The two ends of the spectrum:

  • Pre-inference retrieval (classic RAG) — embed the corpus, retrieve the top-k chunks at session start, stuff them into context.
  • Just-in-time retrieval — keep lightweight identifiers (file paths, queries, links) and let the agent load data on demand using tools.

Claude Code is the worked example of the just-in-time end: glob, grep, head, tail, targeted SQL. The agent doesn’t memorize the corpus; it navigates it. This mirrors human cognition — we use file systems, inboxes, and bookmarks rather than memorizing everything.

Three benefits of just-in-time:

  1. Metadata as signal — tests/test_utils.py tells you something different than src/core_logic/test_utils.py. Folder hierarchy, naming, timestamps are all free context.
  2. Progressive disclosure — the agent assembles understanding layer by layer, keeping only what’s needed in working memory.
  3. No stale index — no embedding to refresh; the file system is the source of truth.

Trade-off: runtime exploration is slower, and bad tools or bad heuristics waste context chasing dead-ends. Some workflows are better served by a hybrid: drop a curated front-matter into context up front (e.g. CLAUDE.md), but expose primitives so the agent can dig further on demand. Hybrid suits low-dynamism domains like legal or finance; pure just-in-time suits coding.

This is the same principle behind the CLI Tools Pattern (a CLI + README is just-in-time tooling) and Agent Harness’s “attaching is permanent, reading is transient” rule. Anthropic’s piece supplies the umbrella term.

Long-Horizon Tasks: The Three Techniques

For work that exceeds a single context window — large codebase migrations, multi-hour research, multi-session game-playing — Anthropic identifies three complementary techniques. They’re not alternatives; they fit different shapes of work.

TechniqueWhat it doesWhen it fits
CompactionSummarize the message history near the limit, restart with the summary + recent filesConversational tasks needing extensive back-and-forth
Structured note-taking (agentic memory)Agent writes notes to disk during work (NOTES.md, TODO.md); reads them back across resetsIterative development with clear milestones
Sub-agent architecturesSpecialized sub-agents handle focused tasks with clean contexts; return distilled 1k–2k token summariesComplex research where parallel exploration pays

Key

Compaction is high-recall before high-precision. Anthropic’s tuning advice: first ensure the compaction prompt captures every relevant fact (recall), then iterate to remove superfluous content (precision). The safest, lightest form is just clearing tool results once their findings are summarized — already shipping in the Claude Developer Platform.

This is consistent with Context Window Management Strategies’s warning that auto-compaction “launders mistakes into assertions.” Anthropic acknowledges the same risk: “overly aggressive compaction can result in the loss of subtle but critical context whose importance only becomes apparent later.” The mitigation is human-tuned compaction prompts, not naive summarization.

Note-taking is illustrated vividly by Claude playing Pokémon: without prompting, the agent develops maps of explored regions, level-up tallies (“for the last 1,234 steps I’ve been training Pikachu…”), and combat strategy notes that survive context resets. The insight: persistent files outside the window enable long-horizon strategies that would be impossible inside it. See Agent Memory.

Sub-agent architectures are the multi-agent angle, covered in depth in Multi-Agent Research System - Production Lessons. Each sub-agent burns its own context budget exploring; the lead agent only sees the distilled return value. This separation of concerns is itself a context engineering decision — a fresh sub-agent is a free reset of the window, paid for in coordination complexity.

Worked example

Long-Running Agents - Initializer + Coding Pattern applies all three techniques in one harness: a one-shot initializer agent writes init.sh + feature_list.json + claude-progress.txt (note-taking artifacts); each subsequent coding agent reconstructs context just-in-time and works on a single feature (incremental compaction at the session boundary). It’s the canonical Anthropic blueprint for shifts longer than one window.

The Anti-Pattern: Sub-Agent Proliferation for Implementation

Anthropic’s endorsement of sub-agent architectures applies to research and exploration — read-only tasks where each sub-agent returns a distilled summary. Mario’s anti-pattern warning applies to a different shape: parallel implementation.

Spawning multiple sub-agents in parallel to implement features is the opposite of context engineering. Each sub-agent has incomplete context, produces inconsistent code, and the results are hard to integrate. Mario: “Spawning multiple sub-agents to implement various features in parallel is an anti-pattern in my book and doesn’t work, unless you don’t care if your codebase devolves into a pile of garbage.”

The two views reconcile cleanly:

Sub-agent shapeVerdictWhy
Research / read-only exploration → returns a summary✅ recommendedDetailed search burns its own context; lead agent stays clean
Code review or fresh-perspective check → returns a report✅ valid narrow caseOutput is information, not state changes
Parallel feature implementation → independent code changes❌ anti-patternInconsistent context produces inconsistent code; integration is the cost

Relation to Minimal Agent Design

Context engineering is the why behind Pi (Coding Agent)‘s minimal design choices. Every “no” in Pi’s design (no MCP, no plan mode, no built-in todos, no sub-agents) is a context engineering decision:

  • No MCP: avoids loading large tool schemas that may never be used
  • No built-in todos: avoids hidden state that clutters context
  • No plan mode: avoids an opaque sub-agent loop; use a visible file instead
  • No sub-agents by default: avoids context you can’t inspect or steer

The minimal system prompt (< 1,000 tokens) is context engineering at the foundation.

Sources