Agents & MCPDeveloper skill

Context Engineering

Managing an agent context window: progressive disclosure, token budgets, summaries, pruning, and cross-session handoff.

What it does

An AI assistant can only hold so much at once. On a long task it starts forgetting decisions it made an hour ago, redoing work it already finished, or answering in a vaguer way than it did at the start. It looks like the model getting tired. What is actually happening is that everything it has read is still sitting in front of it, competing for attention, including the parts that stopped mattering ten steps ago.

With this skill active, the working memory gets managed on purpose. Instructions stay put and stay identical. Big files are referenced by name and opened only on the step that needs them. Finished work is boiled down to a short status block holding the goal, the decisions made and the exact file names, and the raw material behind it is dropped. When a session is about to end, a handoff note gets written so the next one starts informed instead of guessing.

The result is an assistant whose accuracy at step thirty resembles its accuracy at step three, and a written trail you can read yourself.

You end up with a context plan, a running state block, and a handoff note that keeps a long run on task.

When to reach for it

Use it when you are designing an assistant or automation that runs many steps or reads large files, and whenever a long session starts forgetting, repeating itself, drifting off the original goal, or hitting a limit.

Skip it for short tasks. On anything that finishes in a few steps this is pure overhead, and a bigger context window is not a reason to start managing one that is not causing problems.

What's inside

context-engineering/
├── SKILL.md
└── references/
    └── examples.md
SKILL.md
---
name: context-engineering
description: Manages what an AI agent can see at any moment - budgeting the context window in layers, loading information only when a step needs it, compacting finished work into state, pruning stale tool output, and handing off across sessions. Use when an agent forgets earlier decisions, repeats work, drifts off task on long runs, gets vaguer as a session grows, or hits context limits.
---

# Context Engineering

You decide what an agent can see, when, and for how long. Context is a finite resource with diminishing returns: past a certain fill, every extra token competes with every other for the model's attention, and accuracy falls even though nothing was technically dropped.

The goal is not a full window. It is the smallest set of high-signal tokens that makes the next step likely to be correct.

## Workflow

1. **Name the shape of the task.** One long conversation, a multi-step agent loop, or a batch pass over large files. They fail differently: conversations bloat with history, loops bloat with tool output, batches bloat with the source material.
2. **Budget the window in layers.** Roughly: instructions and schemas (stable, small), current task state (small, always fresh), retrieved material (loaded per step, discarded after), and headroom for the model's own reasoning and output. Overfilling any layer starves the rest.
3. **Set the instructions at the right altitude.** Specific enough to guide behavior, general enough to leave judgment. Exhaustive if-then rules are brittle and expensive; vague encouragement gives the model nothing to act on. Aim for the level a competent new teammate would need.
4. **Take the smallest workable tool set.** Every tool description sits in context for the whole session. Overlapping or ambiguous tools cost tokens twice: once in the window, and again when the agent picks wrong.
5. **Load just in time.** Keep lightweight pointers in view - file paths, section titles, ids - and fetch the content on the step that needs it. This is how skills themselves work: names always loaded, bodies loaded on trigger.
6. **Compact instead of accumulating.** When history grows, replace finished work with a short state block: goal, decisions, current step, open threads, key paths. Keep conclusions, drop the path to them.
7. **Prune deliberately.** Once you have taken three fields from a large tool result, the rest of that result is noise. Say so and drop it.
8. **Push isolated work to sub-agents.** A wide search or a long file sweep can run in its own context and return only its conclusion. The main thread pays for the answer instead of the process.
9. **Write a handoff before the session ends.** Goal, state, decisions, next action, file paths. The next session reads that instead of re-deriving everything.

```text
Context health checklist
[ ] The current goal is restated near the most recent turn
[ ] Instructions and schemas are stable and not repeated per turn
[ ] Every tool in the set is distinct and currently useful
[ ] Large content is referenced by path, not pasted
[ ] Tool outputs are compacted once their conclusion is captured
[ ] Superseded drafts and dead ends are gone
[ ] File paths, ids and exact constraints survived every compaction
[ ] A handoff note exists before the window is reset
```

## The four layers

| Layer | Contents | Changes | Rule |
| --- | --- | --- | --- |
| Instructions | System prompt, schemas, tool definitions, style rules | Rarely | Keep byte-identical so the prefix can be cached |
| State | Goal, decisions, current step, open threads | Every few steps | Small, rewritten rather than appended |
| Retrieved | The file, page, or rows this step needs | Every step | Fetched on use, dropped after |
| Headroom | The model's reasoning and output | Every turn | Never squeeze it to fit more input |

Keeping the instruction layer identical between calls matters beyond tidiness: a stable prefix can be cached, which makes long sessions cheaper and faster. A timestamp injected at the top of an otherwise stable prompt quietly invalidates that.

## Just-in-time retrieval

Pre-loading everything the agent might need is the intuitive approach and the wrong one. It is expensive, it goes stale, and it buries the relevant part.

Instead, keep the map and fetch the territory:

- A file tree, not the files.
- A schema, not the rows.
- Search results with ids and one-line excerpts, not full documents.
- The three fields you extracted, not the forty-field response.

The name of a thing usually carries most of what the agent needs to decide whether to open it. `tests/auth/test_token_refresh.py` says enough to know when it matters.

A hybrid approach works well in practice: pre-load the few things needed on every step, retrieve everything else on demand.

## Compaction

Compaction is rewriting history into state, and it is a lossy operation you control rather than one that happens to you.

**Preserve exactly:** file paths, ids, exact constraints and numbers, decisions not yet acted on, unresolved questions, the current goal.

**Discard:** raw tool output whose conclusion you kept, superseded drafts, exploratory paths that led nowhere, verbose reasoning about a decision already made.

A good state block is short enough to reread every step:

```text
GOAL   Add rate limiting to the public API
DONE   Chose token bucket (fixed window rejected: bursty traffic)
       Middleware written at src/mw/rate_limit.py, unit tests pass
NOW    Wiring the middleware into src/server.py
NEXT   Redis-backed counter so limits survive a restart
FACTS  Limit 100 req/min per key. Keys live in the api_keys table.
       Config lives in config/limits.yaml, not in env vars.
OPEN   Do we return 429 or 503 when Redis is unreachable?
```

Test a compaction by asking whether the next step is still possible using only what remains. If it needs a path that is gone, the compaction was too aggressive.

## Structured note-taking

For work spanning many steps or several sessions, keep the state outside the window entirely: a file the agent writes after each meaningful step and reads at the start of the next. The window holds a pointer; the file holds the memory. This survives resets, and it makes the state auditable by a human.

## Sub-agents

When a step needs to read widely to produce a small answer, give it its own context. A sub-agent that reads thirty files and returns "the token refresh happens in `auth/session.py:88`, and it ignores the clock skew setting" has spent thirty files of context that the main thread never pays for.

Use this when the work is genuinely separable and the return value is small. It is a poor fit when the sub-agent would need most of the main thread's context to do its job, since you then pay for that context twice.

## Rules

- More context is not better context. Irrelevant material actively degrades the next decision.
- Keep the current goal near the most recent turn. Attention drifts toward whatever is most present.
- Never compact away a path, an id, or an exact constraint. Those are the things that cannot be re-derived from a summary.
- Prefer a pointer to a paste, and a retrieval to a pre-load.
- A larger context window is a reason to do more work, not a reason to stop pruning.
- Measure before optimizing: if a session is failing at step 4, the problem is not the window.

## Example

**Symptom.** A 30-step agent working through a repository starts drifting around step 12: it re-reads files it already read, forgets a decision made at step 5, and its edits start contradicting each other.

**Diagnosis.** By step 12 the window holds eleven full file reads, four superseded diffs, and a transcript in which the original goal is 40,000 tokens behind. Nothing was dropped, and that is the problem.

**The fix, in three moves:**

1. Replace the transcript with a state block, rewritten after every step, holding goal, decisions, current step, and the file paths in play.
2. Keep the tool definitions, drop every past tool result once its conclusion is in the state block.
3. Fetch each file on the step that touches it, using the tree for orientation between steps.

**Result.** The window stays roughly flat from step 12 to step 30 instead of growing, and the agent stops re-reading, because the state block tells it what it already knows.

## Edge cases

- **The task genuinely needs a large document in view**, such as a contract being edited clause by clause. Chunk it and keep only the active section plus a table of contents, with the full text on disk.
- **The agent keeps re-reading a file you pruned.** You pruned one step early. Keep the extracted facts, not the file, and put them in the state block.
- **A tool returns thousands of rows.** Fix the tool, not the window: add a limit, a filter, or a summary mode. Truncating downstream loses the wrong rows.
- **Multi-day work.** Move state to a file and treat each session as a fresh window that starts by reading it.
- **A short task.** Do nothing. Context engineering on a five-step task is overhead with no payoff.
- **Compaction that keeps losing something.** Add it to a "facts" section of the state block that is copied verbatim and never rewritten.

## Files

- `references/examples.md` - three worked cases: a long agent loop rebuilt around a state block, a retrieval pipeline that was stuffing instead of searching, and a session handoff note in full. Read when deciding how aggressively to compact.

Install it

Claude Code (this project)

Unzip the download into .claude/skills/. The folder is already named right.

Claude Code (every project)

Unzip into ~/.claude/skills/ to use it everywhere.

claude.ai

Upload the zip under Settings, then Capabilities, then Skills (paid plans).

How to call it

Just describe the task. The description line inside the skill does the matching. Or call it directly:

/context-engineering my agent forgets what it decided earlierit keeps redoing work it already finishedthe assistant drifts off task on long runswe keep hitting the context limithow do I hand off a long session cleanly

Works beyond Claude

Skills use the open Agent Skills format. The exact same folder works in OpenAI Codex, Gemini CLI, Cursor, GitHub Copilot and other tools that read the format.

Using a plain chat app? Paste SKILL.md into ChatGPT or Gemini as instructions. You lose auto-triggering, but the method still works.

agentskills.io

Pattern credit: Anthropic — Effective context engineering for AI agents

Related skills