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:
- 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.
- 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:
| Component | Heuristic | Common failure mode |
|---|---|---|
| System prompt | Right altitude — Goldilocks zone between brittle if-else hardcoding and vague high-level guidance that assumes shared context | Stuffing edge cases as rules; or skeletal prompts that leave the model guessing |
| Tools | Self-contained, robust to error, unambiguous in intent; minimal viable set | Bloated 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 list | Laundry-listing every edge case as a separate example |
| Message history | Curated, tight, informative | Passively 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:
-
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.
-
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.mdResult: 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.mdwith checkboxes instead of a built-in todo systemPLAN.mdwith 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:
- Start a dedicated context-gathering session
- Produce an artifact (a well-structured document or summary)
- 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:
- At ~20% remaining: ask the agent to write a
task-summary.md— proposals verbatim, decisions stated explicitly, next steps listed, relevant file paths included - Iterate on it — there’s still context left; correct the file until it’s accurate. Never trust the first draft.
- Quit the session — don’t compact, don’t wait for auto-compact
- New session: load
spec.md(project context) +task-summary.md - 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:
- Metadata as signal —
tests/test_utils.pytells you something different thansrc/core_logic/test_utils.py. Folder hierarchy, naming, timestamps are all free context. - Progressive disclosure — the agent assembles understanding layer by layer, keeping only what’s needed in working memory.
- 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.
| Technique | What it does | When it fits |
|---|---|---|
| Compaction | Summarize the message history near the limit, restart with the summary + recent files | Conversational 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 resets | Iterative development with clear milestones |
| Sub-agent architectures | Specialized sub-agents handle focused tasks with clean contexts; return distilled 1k–2k token summaries | Complex 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 shape | Verdict | Why |
|---|---|---|
| Research / read-only exploration → returns a summary | ✅ recommended | Detailed search burns its own context; lead agent stays clean |
| Code review or fresh-perspective check → returns a report | ✅ valid narrow case | Output is information, not state changes |
| Parallel feature implementation → independent code changes | ❌ anti-pattern | Inconsistent 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.
Related
-
Context Window Management Strategies — the six ways a harness handles transcript growth; the four failure modes of auto-compaction
-
Long-Running Agents - Initializer + Coding Pattern — Anthropic’s blueprint for multi-context-window work; file-as-state in production form
-
Agent Memory — short-term vs. long-term; structured note-taking as the bridge to long-horizon work
-
Multi-Agent Research System - Production Lessons — the production case study behind sub-agent architectures
-
CLI Tools Pattern — on-demand context loading via README + CLI; the just-in-time pattern in miniature
-
Agent Harness — the runtime substrate; “attaching is permanent, reading is transient”
-
AGENTS.md as a Neural Net — transcript-based refinement of always-loaded project instructions within a fixed budget
-
Pi (Coding Agent) — reference implementation of context engineering principles
-
Claude Code Internals — what claude-trace revealed about hidden context injection in Claude Code
-
Agentic Porting Workflow — worked example of query isolation + session handoff
-
Self-Extending Agents — building tools that respect context budgets
-
Agent Tools - Design Principles — tool descriptions as context spend
-
Agent-Computer Interface (ACI) — the engineering discipline that makes tools robust under context pressure
-
Writing Conflict-Free Instructions — the precedence and conditional-rule layer of system-prompt altitude
-
Agentic Coding - Risks and Discipline — the discipline context engineering requires
-
PRINCE - Production Agentic RAG at Bayer — a production worked example: “context discipline” routing planning/retrieval/evidence/synthesis context to four different agents, and schema-slicing for Text-to-SQL
-
12-Factor Agents — factor 3 (“own your context window”) argues you are not obliged to use the standard messages array; custom event formats for token and attention efficiency
Sources
- Effective context engineering for AI agents — canonical source — “Effective context engineering for AI agents” (Rajasekaran, Dixon, Ryan, Hadfield, Anthropic Engineering, 2025-09-29); the attention-budget framing, the anatomy of context, just-in-time retrieval, and the long-horizon trio (compaction / note-taking / sub-agents)
- What I learned building an opinionated and minimal coding agent — Pi’s design as context engineering at the foundation; the practical “no” list
- I can’t sleep gud anymore - A Practical Guide to Agentic Computering — claude-trace internals, compaction management, the LSP+jq porting workflow
- A love letter to Pi — the 50% rule, don’t-argue rule, evaluation packs, /tree branching
- Context Systems and Agent Factories — context engineering at company scale: ontology, sync-everything, permissions, context rot
- Knowledge Factory — the claim that after context, the missing piece is maintained knowledge: skills, domain facts and data access guidance