---
name: context-engineering
description: Manage your own context window across long sessions — prune stale tokens, compact history, externalize state to files, delegate to fresh-window subagents, and load reference material only when relevant.
---

# Context Engineering

You are an agent that actively manages what occupies your context window. The
window is attention, not storage. Every token competes for focus, and quality
degrades as the window fills (context rot). Your job is to keep the window lean,
current, and relevant at every step — not to cram in everything that might help.

Apply these practices continuously, not just when you're near the limit.

## Core principle

Default to the smallest viable representation of any information. Hold an index;
fetch detail on demand. Externalize state to files. Drop what's resolved or
stale. When you catch yourself with a noisy window, clean it before continuing.

## When to compact (summarize history)

Compact your conversation history when ANY of these is true:

- The window is roughly half full and you need headroom for upcoming work.
- You just finished a distinct phase or sub-task (a natural seam).
- The history contains resolved errors, superseded file versions, or verbose
  tool output that no longer matters.

When you compact, produce a summary with this structure and place it where
attention is strongest (top of the retained context):

```
## State (current)
- <the current, true state of the system / task>
- <key decisions made AND why>

## Open threads
- <unfinished work, in priority order>

## Constraints discovered
- <hard limits, gotchas, conventions found along the way>

## Dropped (recoverable elsewhere)
- <what detail you discarded and where to find it: git, logs, a file>
```

Rules for good compaction:

- Preserve decisions, current state, open threads, and constraints.
- Discard the play-by-play: failed attempts, resolved stack traces, exploratory
  reads, directory listings.
- Never silently drop a load-bearing fact. If unsure it's safe to drop, keep it
  in the State block.
- Note what you dropped and where it can be recovered, so you don't re-derive it.

## When to spawn a fresh-context subagent

Delegate to a subagent with a clean window when the work is WIDE but the result
is NARROW — lots of reading or trial-and-error, small clean output. Examples:

- Researching a topic across many sources.
- Reviewing or refactoring a self-contained module.
- Searching a large codebase for candidates.
- Any exploration that would dump large intermediate state into your window.

How to delegate well:

1. Give the subagent a crisp return contract: exactly what to return and in what
   shape. Example: "Return a list of `{file, line, severity, one-line note}`."
2. Pass only what it needs to start. Do NOT hand it your full context — a fresh
   window is the entire point.
3. Treat the returned value as the interface. Act on it without re-reading the
   subagent's process. If you can't, your contract was too loose — tighten it.

The mess stays in the subagent's window. Only the clean result enters yours.

## What to prune

Prune aggressively. Bias toward dropping. Remove from active context:

- **Resolved errors and stack traces** — once fixed, they are dead weight and
  actively mislead.
- **Superseded file versions** — if you've read or edited a file multiple times,
  keep only the latest. Earlier copies are stale.
- **Verbose successful tool output** — replace "all 412 tests passed" for the
  full log. Keep counts and the relevant lines, drop the rest.
- **Repeated reads** — collapse duplicate reads of the same content.
- **Irrelevant retrieval** — drop chunks that turned out not to matter.
- **Boilerplate and metadata** — keep the payload, strip the wrapper.

Before adding large tool output to your reasoning, ask: do I need all of this, or
a summary plus a way to fetch detail? Default to the summary.

## What to pin vs. drop

Keep RESIDENT (near the top/bottom of the window, where attention is strongest)
only the short list of things you'd be in trouble without:

- The current goal / task.
- Hard constraints and the user's key requirements.
- The current "state of the world" summary.
- The active plan (or a pointer to the plan file).
- Critical conventions for the task at hand.

DROP or fetch-on-demand everything else: completed sub-task detail, resolved
errors, old file versions, verbose output, reference docs not relevant right now.

If your pinned list is growing long, that's a signal to split the work into
phases or delegate part of it. Pinning a lot is a smell.

## Using scratchpad and memory files

State lives on the filesystem. The window is for thinking, not storage.

**Plan file (`plan.md`).** Before a complex task, write a numbered plan to a
file. As you work, check items off IN THE FILE, not in the conversation. Hold a
pointer to the plan, not its full text.

**Findings file (`findings.md`).** During research or audits, append bullet
findings with sources to a file rather than narrating each into context. Read the
file once at the end to synthesize.

**Notes / decisions (`NOTES.md`, `DECISIONS.md`).** Maintain structured note
files with consistent headings. Because the structure is predictable, grep for a
section instead of reading the whole file.

**Persistent memory.** For facts that should survive across sessions (user
preferences, project conventions, a domain glossary): read relevant memory at the
start, write durable new facts as you learn them. Query memory as a tool — fetch
the specific note you need — rather than loading the whole store every turn.

Workflow for a long task:

1. Write the plan to `plan.md`.
2. Work each step, updating the file as you go.
3. Append results/findings to a file instead of into the window.
4. Prune resolved detail continuously.
5. Compact at phase boundaries, preserving the State block.
6. Read the relevant file(s) once at the end to produce final output against a
   clean window.

## Progressive disclosure

Do not load everything up front. Load a small index, fetch detail only when it
becomes relevant.

- Prefer a table of contents (one-line summaries) over full text. Request bodies
  on demand.
- Keep API specs, schemas, and style guides in files you read only when the task
  touches them — not pinned permanently.
- For large documents, read a synopsis first; pull full sections only if the
  synopsis says the detail matters.
- When a tool can return a summary plus a handle, take the summary and expand the
  specific slice you need.

This is how skills themselves work: you hold a one-line description of each, and
read the full instructions only for the one that matches the task.

## Retrieval discipline

When pulling external knowledge into context:

- Retrieve few, high-precision items. Top-3 right beats top-20 noisy.
- Re-rank candidates by actual relevance before including them.
- Gate on a relevance threshold. If nothing clears it, say so — an honest "no
  relevant source" beats a confident answer built on a weak chunk.
- Carry source and freshness metadata with each item; reason about recency.
- Prefer deterministic lookups (a database query) over semantic search when the
  answer is structured.

## Self-audit

Periodically — especially before a major step or when you sense degraded
performance — run this quick audit:

- Is anything in my window stale (resolved errors, old file versions)?
- Is any verbose tool output here that should be summarized?
- Am I pinning something that should live in a file?
- Is a critical constraint buried in the middle where I might ignore it?
- Should the next chunk of work be delegated to a fresh-window subagent?

Fix what you find before continuing. A loud window is the leading cause of an
agent getting "dumb" late in a session — clean it and your quality recovers.