Context Engineering for Claude Code and Codex: A Practical Guide
Most developers try to improve an AI coding agent by giving it more context. They paste longer specifications, load more documentation, preserve old conversations, and ask the agent to inspect the entire repository before touching the code.
This often makes the result worse.
A large context window can hold more information, but it cannot guarantee that the information is relevant, current, or internally consistent. As a session grows, useful constraints compete with stale plans, failed attempts, verbose command output, unrelated files, and corrections that no longer apply. The agent has more material available—and a less reliable picture of what matters.
Context engineering is the practice of controlling that picture. It means deciding what should load automatically, what should appear only when needed, what belongs in a separate agent, what must survive compaction, and when a clean session is better than continuing an old one.
The best coding session is not the one with the most context. It is the one in which every piece of context still helps the agent make the next decision.
This guide presents a practical context-management workflow for Claude Code and Codex. It uses one realistic feature change from exploration through review, then provides reusable prompts and a decision framework for recovering when a session starts to drift.
What is context engineering?
Prompt engineering shapes the immediate request. Context engineering designs the complete information environment in which the agent interprets that request.
For an AI coding agent, that environment can include:
- the current task and conversation;
- project instructions such as
CLAUDE.mdorAGENTS.md; - files the agent reads and command output it receives;
- plans, specifications, screenshots, and issue descriptions;
- skills and their reference material;
- tool descriptions and external data;
- summaries returned by subagents;
- memories or artifacts carried across sessions.
Good context engineering gives each layer one job. Repository-wide rules remain durable. Task-specific evidence enters only when relevant. Noisy investigation happens outside the main implementation conversation when practical. Decisions survive a handoff, while discarded hypotheses do not.
This is different from simply shortening every prompt. A compact but ambiguous request can be worse than a detailed specification. The goal is not minimum context. It is minimum sufficient context: enough information to make the next decision correctly, without unrelated material competing for attention.
What is context rot?
Context rot is the gradual loss of decision quality as a working context becomes larger, noisier, or internally inconsistent. It is not a formal error message, and it does not begin at one universal token count.
You can recognize it through behavior:
- the agent repeats an approach that already failed;
- an earlier constraint disappears from the implementation;
- a superseded plan is treated as current;
- the agent edits files outside the agreed scope;
- answers become generic even though specific evidence was previously available;
- verification checks the implementation against its own assumptions rather than the original requirement;
- each correction fixes one detail but introduces another contradiction.
The problem is often relevance rather than capacity. A session may still fit inside the model's context window while containing three plans, two conflicting requirements, thousands of lines of test output, and several abandoned debugging paths. Technically available information is not necessarily useful information.
Why a larger context window is not the solution
Larger windows are valuable. They let an agent inspect more code, retain longer histories, and complete more tool-heavy work before compression becomes necessary. But capacity and context quality are separate variables.
Imagine placing every design document, source file, log, and previous conversation from a project on a developer's desk. Nothing is missing, but the developer must still determine which version is authoritative, which files matter, and what changed since the plan was written. An agent faces the same selection problem.
More context can introduce four costs:
- Competition. Critical requirements compete with repeated or irrelevant material.
- Contradiction. Old and new decisions coexist without a clear source of truth.
- Latency and cost. Long histories and large outputs must be processed repeatedly.
- Bad continuity. Continuing a contaminated session feels efficient even when a focused restart would be faster.
Anthropic's Claude Code guidance treats context as a primary constraint: files, messages, instructions, tool results, and loaded extensions all occupy the session, while compaction and isolated subagents control what remains. OpenAI's Codex customization model similarly separates durable instructions, on-demand skills, and delegated agents instead of assuming one prompt should carry the entire workflow.
The context stack: put each fact in the right layer
Use this hierarchy before adding more information to a session:
| Layer | What belongs there | What does not |
|---|---|---|
| Task prompt | Current objective, scope, acceptance criteria, immediate constraints | Every repository convention |
| Project instructions | Commands and rules needed in most sessions | One feature's temporary decisions |
| Scoped rules | Conventions for a directory or file type | Global policy duplicated across files |
| Skill | A reusable procedure or specialist reference | Always-on background material |
| Plan or spec | Decisions and sequence for one substantial change | Raw exploration transcripts |
| Tool output | Evidence needed for the current decision | Unfiltered logs kept indefinitely |
| Subagent result | A compact finding, patch, or verification report | The worker's full conversation |
| Handoff artifact | Current state, decisions, evidence, risks, and next action | Every attempt made along the way |
If a rule matters for nearly every task, put it in CLAUDE.md or AGENTS.md. If it is a repeatable procedure, make it a Skill. If it matters only to this feature, keep it in the task specification or plan. Our guide to Instructions vs. Skills covers that boundary in more detail.
A practical workflow: changing an authentication system
Suppose you need to add refresh-token rotation to an existing application. The change touches token issuance, persistence, logout behavior, migration safety, and tests. A weak prompt is:
Add refresh-token rotation. Inspect the repo and make everything work.It invites unlimited exploration and leaves the agent to invent the definition of done. A better workflow deliberately changes the context between phases.
Step 1: create a context packet
Before the agent reads the repository, provide a compact contract:
Objective: add refresh-token rotation without changing the access-token format.
Scope:
- token issuance and refresh endpoints
- refresh-token persistence
- logout and revocation behavior
- database migration and automated tests
Constraints:
- preserve existing API response fields
- reuse the current hashing abstraction
- do not replace the authentication library
- migration must be reversible
Definition of done:
- reuse of a rotated token is rejected
- logout invalidates the active token family
- existing login clients remain compatible
- focused and integration tests pass
First inspect the relevant entry points and existing conventions. Do not edit yet.
Return the files that matter, current behavior, open questions, and a proposed plan.This packet does not explain the entire authentication architecture. It tells the agent what evidence to find and how to know when exploration is sufficient.
Step 2: bound the exploration
Repository exploration is one of the fastest ways to fill a context window. Ask for entry points and dependency paths, not an indiscriminate tour.
Trace refresh-token creation, storage, validation, and revocation from the HTTP
route to persistence. Read only directly relevant files and their tests. Stop when
you can name the current flow, the smallest likely change surface, and any decision
that cannot be resolved from the repository. Cite paths and symbols in the summary.For a large codebase, delegate this read-heavy phase to a subagent. The main session should receive a map of the system, not every file the explorer opened. Context isolation is one of the highest-value uses of multi-agent coding.
Step 3: turn discoveries into explicit decisions
Do not let the implementation depend on a long conversational trail. Record the decisions that now govern the work:
## Approved decisions
- Store only hashed refresh tokens.
- Rotate on every successful refresh.
- Revoke the full token family when reuse is detected.
- Keep the current response schema.
- Add the migration before changing application writes.
## Evidence
- Route entry point: src/auth/routes.ts
- Token service: src/auth/token-service.ts
- Persistence pattern: src/auth/session-repository.ts
- Integration suite: tests/auth/refresh.test.tsThe exact paths will differ, but the shape matters: decisions, evidence, and unresolved questions are separated. A plan that still contains three competing designs is not ready to become implementation context.
Step 4: implement in bounded checkpoints
Split the work at observable boundaries:
- migration and persistence model;
- issuance and rotation behavior;
- reuse detection and revocation;
- compatibility and integration tests;
- final diff review.
After each checkpoint, keep a short ledger:
Checkpoint: persistence complete
Changed: migration, session repository, repository tests
Verified: migration up/down; focused repository tests
Decision changed: none
Remaining: service behavior, endpoint tests, final reviewThis is more useful than preserving raw command output. When a test produces hundreds of lines, retain the command, exit status, and relevant failure excerpt. The complete output can remain in the terminal or a temporary artifact until it is needed.
Step 5: separate verification from implementation history
The implementer has seen every justification for the chosen design. A reviewer should instead receive the requirement, the final diff, and the claims that need proof.
Review the current diff against the original refresh-token requirements. Focus on
token reuse, concurrent refresh requests, logout behavior, migration rollback,
and backwards compatibility. Do not assume the implementation plan was correct.
Return only evidence-backed defects and missing tests, with file references.An independent reviewer context reduces confirmation bias, but it does not replace deterministic tests or human ownership. See AI Code Review Best Practices for a risk-based review model.
When to correct, compact, delegate, or restart
These actions solve different problems:
| Situation | Best response |
|---|---|
| One requirement was misunderstood, but the session is otherwise coherent | Correct it immediately and restate the affected acceptance criterion |
| The history is relevant but tool output and old details consume too much space | Compact with explicit preservation instructions |
| A bounded investigation requires many file reads or large logs | Delegate it to an isolated subagent |
| The task has changed or failed approaches dominate the conversation | Start a clean session with a written handoff |
| The agent repeatedly violates the same durable repository rule | Fix the project instructions, not only the current prompt |
| Several agents need the same evolving contract | Store the contract in a shared artifact rather than copying chat summaries |
A restart is not failure. It is a context reset. If you have corrected the same misconception multiple times, a new session seeded with the final facts is often more reliable than another paragraph added to a contradictory history.
Context engineering in Claude Code
Claude Code exposes unusually visible context-management controls. Its context window includes the conversation, files, command results, CLAUDE.md, memory, loaded skills, and system instructions. The official documentation explains what loads at startup and what is restored after compaction.
Keep CLAUDE.md concise
Use CLAUDE.md for facts that should guide nearly every session: build commands, important architecture boundaries, repository conventions, and required verification. Anthropic recommends concise, specific instructions and supports scoped rules for content that applies only to certain paths.
Do not paste a product specification or a complete internal handbook into the root file. Always-on instructions consume context even when irrelevant. Move occasional procedures into skills and path-specific guidance into scoped rules.
Inspect before guessing
Run /context when the session feels crowded. It shows how the window is distributed across categories such as messages, memory, skills, and tools. Diagnosis is better than assuming the model suddenly became worse.
Compact with a purpose
Claude Code compacts automatically as the context fills, but you can guide the result:
/compact Preserve the approved authentication decisions, modified files, failing
tests, commands already run, and remaining acceptance criteria. Drop superseded
hypotheses and verbose command output.The documentation also describes which mechanisms are reloaded after compaction. Root instructions and memory behave differently from transient file reads or earlier hook output, so important durable policy should live in the mechanism designed to preserve it.
Clear between unrelated tasks
Use /clear when moving from refresh-token work to an unrelated UI feature. Reusing the same conversation saves a prompt but carries a large body of irrelevant evidence into every subsequent decision.
Use subagents as context filters
Claude Code subagents receive separate context and return a summary. Use them for repository mapping, documentation research, log analysis, or independent review. Give them a narrow question and a required return format; otherwise you merely move an unbounded investigation into another window.
See Anthropic's official guides to the Claude Code context window , memory and CLAUDE.md , and subagents .
Context engineering in Codex
Codex provides the same architectural building blocks with different product surfaces. The practical approach is to treat project instructions, skills, delegated agents, and saved artifacts as separate context layers.
Use AGENTS.md for durable repository guidance
AGENTS.md should contain instructions the agent needs repeatedly: project structure, authoritative commands, code conventions, and verification requirements. Files can be scoped by directory, which lets a monorepo provide focused guidance near the code it governs.
Avoid turning AGENTS.md into a knowledge dump. A short instruction that points to an authoritative command or document is often more durable than copying the full material. Our AGENTS.md guide provides a detailed structure.
Let skills load procedures when needed
A release checklist, migration workflow, or security-review method does not need to occupy every task. Package repeatable procedures as Skills so Codex can load the full instructions for the relevant job. This keeps global guidance smaller and makes the procedure reusable.
Delegate noisy work
Codex subagents can handle bounded exploration or review in their own contexts and return focused results to the coordinating task. A strong delegation prompt specifies the question, permitted scope, whether edits are allowed, and the evidence expected back.
Use a read-only subagent to trace refresh-token persistence and revocation. Return
only the call path, relevant files and symbols, current invariants, and unresolved
risks. Do not propose unrelated authentication refactors.Use artifacts as external working memory
For work that spans sessions, preserve state in a plan, task ledger, or handoff file inside the project. Do not rely on a new session reconstructing every decision from Git changes alone. The artifact should be concise enough to read at startup and specific enough to distinguish completed, verified, and merely proposed work.
See OpenAI's official documentation for Codex customization , AGENTS.md , and subagents .
A reusable handoff template
Use a handoff when starting a fresh session, transferring ownership, or stopping at a safe checkpoint:
# Task handoff
## Objective
One sentence describing the user-visible outcome.
## Current state
- Completed and verified
- Implemented but not verified
- Not started
## Decisions
- Current authoritative decisions only
## Changed files
- path: purpose
## Verification
- command: result
- command: result
## Remaining work
1. Next concrete action
2. Following dependency
## Risks and open questions
- Evidence-backed uncertainty that still mattersThe receiving agent should validate the handoff against the repository and current Git state. A handoff is a compressed map, not a substitute for evidence.
Five reusable context prompts
Start a task
Before editing, restate the objective, scope, constraints, and definition of done.
Inspect only the entry points needed to test your current assumptions. Return a
short evidence-backed plan and list any question the repository cannot answer.Stop infinite exploration
Stop exploring. Summarize the relevant call path, files, confirmed facts, and
remaining unknowns. Explain whether each unknown blocks implementation. Do not
read more files unless one blocks the next decision.Recover a drifting session
Reconcile the current work against the original acceptance criteria. Identify
superseded assumptions, unrelated context, and any decision that changed. Produce
a clean current-state summary before making another edit.Prepare compaction
Preserve the objective, approved decisions, modified files, verification results,
remaining work, and known risks. Remove verbose outputs, failed hypotheses, and
instructions that have been superseded.Hand off to a fresh agent
Create a concise handoff for a new agent. Separate completed and verified work from
unverified changes. Include current Git state, changed files, commands and results,
remaining acceptance criteria, and the next recommended action.Common context-engineering mistakes
Asking the agent to read the entire repository
Repository-wide discovery is rarely a useful first action. Start from entry points, search for concrete symbols, and expand only when evidence creates a dependency.
Treating chat history as documentation
A conversation records the route taken, including wrong turns. A specification or decision log records what is currently true. Move durable conclusions into an artifact.
Loading every tool and instruction globally
Always-on context should earn its place. Use scoped instructions, on-demand skills, and the smallest relevant tool set.
Compacting without stating what matters
Automatic summaries may preserve different details than the next phase needs. Before a major transition, name the decisions, evidence, file state, and acceptance criteria that must survive.
Delegating without a return contract
“Investigate authentication” can produce a long essay. Ask for specific evidence: call paths, file references, invariants, risks, and a clear stopping condition.
Continuing because the session already contains work
Sunk context is still a sunk cost. Restart when the history is dominated by failed approaches, conflicting instructions, or a different task.
The practical checklist
Before starting:
- Can the objective and definition of done fit in a short context packet?
- Are repository-wide rules in
CLAUDE.mdorAGENTS.mdrather than repeated prompts? - Is occasional guidance scoped to a Skill, rule, or referenced document?
- Does exploration have a boundary and a stopping condition?
During the task:
- Are decisions recorded separately from hypotheses?
- Are large outputs reduced to relevant evidence?
- Would a read-heavy investigation be better in a subagent?
- Does each checkpoint state what changed and what was verified?
Before continuing a long session:
- Is the current plan still authoritative?
- Has the agent repeated a failed assumption?
- Should you correct, compact, delegate, or restart?
- Could a fresh agent resume from the written state without reading the full transcript?
Context engineering is an engineering discipline
Good context does not mean exhaustive context. It means deliberate selection, clear authority, and timely disposal.
Claude Code and Codex will continue to gain larger windows, better memory, smarter compaction, and more capable subagents. Those improvements make context engineering more important, not less. The agent can act for longer and across more systems, so stale assumptions and ambiguous instructions can travel further before a human notices.
The durable workflow is simple: keep permanent rules concise, scope exploration, convert discoveries into decisions, isolate noisy work, preserve evidence at checkpoints, and start fresh when the conversation no longer represents the task.
Frequently asked questions
What is context engineering for coding agents?
Context engineering is the practice of designing what information an AI coding agent receives, when it receives it, how long it remains relevant, and how important decisions survive across phases or sessions.
Is context engineering the same as prompt engineering?
No. Prompt engineering focuses on the immediate instruction. Context engineering also covers project rules, retrieved files, tool output, skills, memory, subagents, compaction, and handoff artifacts surrounding that prompt.
What causes context rot?
Common causes include stale plans, contradictory corrections, irrelevant file reads, verbose command output, mixed tasks, and long histories of failed attempts. The issue can appear before the model reaches its maximum context size.
Should I always start a new session for a new task?
Start fresh when the new task is unrelated or the existing session contains significant irrelevant history. Continue when the prior decisions and evidence are genuinely needed and remain coherent.
When should I use a subagent for context management?
Use a subagent when a bounded investigation, review, or log analysis would require substantial context but the main task needs only its conclusions. Specify the scope and expected return format.
Is AGENTS.md or CLAUDE.md a replacement for a task prompt?
No. These files are best for durable repository guidance. The task prompt should still define the current objective, scope, constraints, and definition of done.
Does compaction remove the need for handoffs?
No. Compaction helps continue one conversation within its context budget. A handoff is an explicit, inspectable artifact for transferring current state between sessions or owners.



