Blog

Context engineering for Claude Code: Better agent results

Goon Nguyen•Claude Code Guides••16 min read

Context engineering for Claude Code: A practical guide to better agent results

Detailed prompts alone can't fix missing architecture rules or buried test requirements. Context engineering addresses this broader information environment, helping Claude Code deliver consistent, high-quality code. This guide covers how to organize project context, incrementally improve existing repositories, and maintain clear decisions during long coding sessions. This ensures the right information is available exactly when needed.

Context engineering for Claude Code: Better agent results

What is context engineering in Claude Code?

Context engineering in Claude Code is the practice of selecting, organizing, retrieving, and maintaining task-relevant information so the coding agent can make informed decisions. It connects a request with applicable project guidance, repository evidence, tools, and validation feedback while keeping temporary decisions and outdated material from obscuring the current task.

That information can include user instructions, project guidance, repository files, tool descriptions and results, external documentation, conversation history, task notes, and validation output. These sources are not necessarily loaded together-or automatically.

The context window is the amount of information a model can consider in a request. A larger window does not guarantee useful retrieval or correct reasoning. Think of a “finite attention budget” as a planning metaphor, not a measurable Claude Code diagnostic.

Anthropic’s Effective context engineering for AI agents supports selecting useful context rather than accumulating everything available. Information must still be accessible, relevant, and correctly interpreted.

Context engineering for Claude Code: Better agent results

Context engineering vs. Prompt engineering:

Dimension

Prompt engineering

Context engineering

Focus

Wording the request

Managing the information environment

Scope

Instructions for an interaction

Information across the task lifecycle

Artifacts

Prompts and examples

Project guidance, contracts, notes, tool results

Failure mode

Ambiguous request

Missing, stale, conflicting, or irrelevant evidence

Desired outcome

Clear intent

Informed, verifiable execution

For a profile-update endpoint, prompt engineering clarifies the requested behavior. Context engineering supplies the existing authentication pattern, tenant-access rules, validation schema, and negative tests.

A clear request without these references leaves key decisions incomplete and vague. Conversely, accurate references cannot compensate for contradictory acceptance criteria. The approaches complement each other; context engineering does not make prompt design obsolete.

The Claude Code context map: What each mechanism is for

Choose a location by asking four questions: How often is this information needed? How broadly does it apply? How will Claude discover or load it? How long will it remain valid? Placement should reflect those answers, not convenience alone.

What goes where in Claude Code?

Information type

Best location

Load pattern

Appropriate use

Common misuse

Durable project facts

CLAUDE.md

According to applicable project scope

Commands, architecture, environment constraints

Permanent storage for task history

Domain conventions

Scoped rules

Unscoped or conditionally applicable, depending on configuration

Backend or directory-specific guidance

Assuming every rule is path-scoped

Repeatable procedures

Skills

Discovered and invoked according to configuration

Migration or review workflows

Assuming every skill has isolated context

Feature requirements

Task specification

Supplied or explicitly retrieved

Acceptance criteria and boundaries

Copying temporary requirements into global guidance

External information

MCP or retrieval tools

Retrieved through configured tools

Current documentation or approved records

Treating access as proof of relevance

Bounded investigations

Subagents

Separate working context; results return

Focused exploration or failure analysis

Expecting zero coordination or main-context cost

Temporary working state

Task notes

Explicitly maintained and read

Decisions, open issues, next action

Assuming automatic discovery or memory

Enforceable checks

Hooks, scripts, tests, CI

Run through configured triggers or workflows

Validation and controlled actions

Assuming configuration guarantees coverage

Scoped rules are guidance intended for a particular project area. Skills package reusable procedures; they are not synonymous with subagents. MCP (Model Context Protocol) connects AI applications to tools and information sources; the connected system supplies the information.

Claude Code’s documentation on memory, skills, subagents, hooks, and MCP describes these mechanisms. Check your installed version before relying on exact discovery, inheritance, or invocation behavior. Ordinary task notes are separate from product-managed memory. A filename alone does not ensure that Claude reads it.

Advisory context vs. Deterministic controls

Instructions guide decisions; configured checks and permissions can enforce specific requirements.

  • Advisory: Follow the existing authorization pattern.
  • Verifiable: Test unauthorized and cross-tenant requests, then require those checks before merge.

Hooks can run commands or supported model-based evaluations. Do not treat every hook as deterministic; blocking behavior depends on its type, event, and configuration.

CI (continuous integration) only blocks a merge when relevant checks and repository protections are required. Even reliably executed tests establish covered behavior, not complete correctness.

Use least-privilege tool access and retain human review for security-sensitive changes. Subagent context separation is not an automatic security boundary.

The MINDS framework for Claude Code context engineering

MINDS is a practical mnemonic framework used in this guide; it is neither an official Anthropic standard nor a mandatory sequence:

  • Minimize persistent noise.
  • Isolate specialized work.
  • Navigate to relevant evidence.
  • Document working state.
  • Safeguard important outcomes.

M - Minimize persistent context

Keep durable facts that should influence relevant sessions. Preserve unusual test commands, non-obvious architecture, and important environment restrictions.

Remove duplicate instructions, obsolete workarounds, and generic explanations of the programming language. Ask: “Does this instruction need to influence most sessions in its scope?”

Shorter is not automatically better. Removing a tenant-isolation constraint to reduce file length sacrifices essential context. The objective is less unnecessary material, not fewer lines at any cost.

I - Isolate Specialized Work

Use rules for applicable domains, modular skills for repeatable procedures, and subagents for bounded investigations that would otherwise generate substantial noise.

A database-migration procedure should not occupy every frontend task. Keep it discoverable where migration work begins.

Small tasks often need no delegation. Asking another agent to inspect one obvious function may create more coordination work than simply reading the function in the current session.

N - Navigate to Context Just in Time

Progressive disclosure means retrieving detailed information when the task needs it:

  1. Start with the request and project essentials.
  2. Locate relevant files.
  3. Read the closest contract or implementation.
  4. Retrieve external information only if necessary.
  5. Validate the resulting change.

Agentic search means letting Claude inspect relevant files for the current step. References help only when files are accessible and actually retrieved. A pointer to an outdated document is not useful navigation.

D - Document Task State

Record accepted decisions, completed work, unresolved issues, test status, and the next action. These task notes support continuity without turning permanent instructions into a development diary.

For example, preserve why an authorization approach was rejected, rather than retaining pages of exploratory discussion.

Refresh notes after meaningful decisions and explicitly read them when resuming. The copyable template below provides a compact structure.

S - Safeguard Important Outcomes

Use “thin prompt, thick artifact” to mean a concise request backed by detailed, inspectable acceptance artifacts—not a vague request.

A tenant-isolation requirement should become a negative authorization test, not merely a sentence in CLAUDE.md. Schemas describe contracts; permissions restrict actions; required CI checks can prevent merging unchecked changes.

These context safeguards have limits. Tests may miss defects, and schemas need appropriate validation wiring. Keep human review for security-sensitive or production-impacting work.

Context engineering for Claude Code: Better agent results

How to apply context engineering to an existing Claude Code repository

Start with the smallest useful change, then test it before reorganizing the repository.

  1. Audit the Context Claude Already Receives.
  2. Classify Information by Scope and Lifespan.
  3. Rightsize CLAUDE.md.
  4. Move Specialized Guidance into Modules.
  5. Design Just-in-Time Retrieval Paths.
  6. Convert Critical Requirements into Artifacts.
  7. Review Context Like Code.

Step 1 - Audit the context Claude already receives

Create a context inventory covering:

  • Applicable personal, project, and nested instructions.
  • Rules, skills, and repeated prompt content.
  • MCP connections and task notes.
  • Hooks, scripts, and recurring corrections.

For each entry, record its owner, scope, discovery path, and purpose. Mark problems as duplicate, contradictory, stale, missing, or unnecessarily broad.

This inventory is a review artifact-not a diagnostic command that magically reveals all active context.

Step 2 - Classify information by scope and lifespan

Separate durable repository knowledge from temporary task requirements before moving anything.

Information

Scope

Lifespan

Destination

Project test command

Project

Until tooling changes

CLAUDE.md

Backend convention

Backend

Until architecture changes

Scoped rule

Migration workflow

Migration tasks

Until procedure changes

Skill

Feature requirement

Current feature

Until completion or revision

Task specification

Required validation

Merge or release

Policy-dependent

Script and required CI check

The output is a placement plan. A requirement may need both written explanation and an executable check.

Step 3 - Rightsize CLAUDE.md

Keep information whose absence repeatedly causes wrong assumptions.

Keep

Move or remove

Verified build, test, and lint commands

Task histories

Non-obvious architecture

Temporary acceptance criteria

Important environment constraints

Duplicate instructions

Recurring project-specific gotchas

Generic programming advice

Documenting how to run the linter remains useful. Restating every lint rule usually adds maintenance without equivalent value.

There is no universal line-count target. Review the proposed diff against representative tasks, checking that essential constraints remain discoverable.

Step 4 - Move specialized guidance into modules

Choose the mechanism by purpose:

  • Scoped rule: A path-specific convention.
  • Skill: A repeatable procedure.
  • Subagent: Substantial, bounded exploration.

Give each module a clear name and discovery or invocation path.

A practical failure lesson: moving guidance into a module achieves nothing if the module is never discovered. Test retrieval before declaring the reorganization complete.

Step 5 - Design just-in-time retrieval paths

Identify source-of-truth schemas, relevant directories, comparable implementations, and current external documentation. Provide enough navigation to reach them without copying everything into instructions.

Use MCP when external information materially affects the task. Restrict access and require approval for sensitive actions.

Treat external content as potentially untrusted: embedded instructions can attempt prompt injection, redirecting the agent away from the authorized task.

Step 6 - Convert critical requirements into artifacts

Map important requirements to inspectable evidence:

  • Expected behavior → Test.
  • API contract → Schema or type definition.
  • Formatting → Formatter.
  • Release condition → Required CI check.

A schema does not automatically validate runtime behavior. A mockup guides implementation but is not an executable control.

Confirm that checks are configured and actually run. The output should include validation evidence, not just configuration files.

Step 7 - Review context like code

Assign ownership and version shared context artifacts. Use pull-request review where appropriate, especially for permission changes and security guidance.

Revisit instructions after architecture or tooling changes. Remove obsolete rules and compare task outcomes before and after modifications.

Treat agent-suggested rule updates as proposals requiring review-not autonomous policy changes. Begin with one scoped improvement whose effects you can inspect.

Context engineering for Claude Code: Better agent results

How to prevent context rot in long Claude Code sessions

Context rot is a useful description of degraded task focus when accumulated information becomes stale, contradictory, repetitive, or difficult to use. In Claude Code, it can appear as forgotten requirements or resurfacing rejected approaches. Session length alone does not establish the cause; unclear scope, missing access, and difficult tasks can produce similar symptoms.

Symptom

Response

Rejected approach returns

Preserve the rejection and reason

Decisions conflict

Identify the accepted decision and supporting evidence

Irrelevant files are repeatedly inspected

Restate scope and relevant paths

Requirements disappear

Re-read acceptance criteria

Raw output overwhelms the task

Extract relevant evidence and summarize

Compact raw history, preserve decisions

Context compaction summarizes session history so useful state remains available. Anthropic’s context-engineering guidance discusses compaction as a continuity technique, not a guarantee that every detail survives.

Preserve

Summarize

Requirements, decisions, current changes

Repeated file dumps

Test status, issues, next action

Long logs and redundant results

Failed approaches that should not recur

Repeated exploratory discussion

Keep failure reasons when they prevent repeated mistakes. Verify important details against repository evidence after summarization.

Use subagents for high-noise exploration

Log analysis, repository discovery, and focused test-failure investigation can benefit from a separate working context.

Request a compact return format: Finding, evidence, relevant files, recommended action, remaining uncertainty.

Delegation introduces coordination costs, and summaries can omit important details. Subagents are not guaranteed independent reviewers. Keep direct access to underlying evidence and avoid delegation when the main session can resolve the question simply.

Maintain a small task-state file

Use structured note-taking to preserve working state:

# Task State
- Objective:
- Acceptance criteria:
- Relevant files:
- Accepted decisions:
- Completed work:
- Open issues:
- Test status: [check, result, revision]
- Next step:
- Rejected approaches / do not repeat:
- Last updated / relevant revision:

Refresh the file after meaningful decisions, before handoffs, and when resuming. Explicitly ask Claude to read it; the filename has no special native behavior.

Verify stale notes against the current repository. Keep secrets, customer data, and sensitive logs out of notes and screenshots. Record “not run” rather than implying validation occurred.

Worked example - Adding an authenticated API endpoint

This illustrative scenario adds a profile-update endpoint to a multi-tenant B2B SaaS application. It demonstrates context flow, not measured results.

Weak approach - Prompt only

“Add a secure profile-update endpoint” leaves project-specific decisions open: authentication, route conventions, schema, and expected tests. A prompt-only workflow need not fail, but this request does not explain which existing patterns should govern the implementation or what reviewers will accept.

Weak approach - Load everything up front

Supplying all documentation, unrelated routes, historical discussions, and broad repository dumps introduces competing examples. More material may include the necessary answer, but the agent still needs to identify which evidence applies. No measured performance loss is assumed here; the problem is unnecessary ambiguity.

Better approach - Progressive context disclosure

The task specification requires authentication, permission to update the selected user, tenant isolation, validated input, existing error conventions, and relevant tests.

Use progressive disclosure:

  1. Read applicable project instructions for commands, architecture, and task boundaries.
  2. Inspect the route structure and one comparable endpoint to establish placement and conventions.
  3. Read authentication and authorization code to distinguish identity verification from permission to modify this user.
  4. Inspect the schema and validation contract for allowed fields and tenant-sensitive restrictions.
  5. Read the closest tests, including unauthenticated, unauthorized, invalid-input, and cross-tenant cases.
  6. Implement against explicit acceptance criteria, keeping unrelated files outside scope.
  7. Run relevant tests, linting, and available security checks; inspect runtime feedback and report checks not run.
  8. Record unresolved issues and next actions, including validation gaps requiring human review.

Targeted information supports each decision without carrying unrelated material through the entire task.

Context engineering for Claude Code: Better agent results

Audit and measure your Claude Code context setup

Assess context quality through task outcomes, not configuration-file counts. Establish a lightweight baseline across comparable tasks, recording model/tool versions and configuration or test-suite changes. Small samples provide directional evidence, not causal proof.

Practical context quality scorecard

Metric

Definition

Corrective prompts per task

Corrections of wrong assumptions; exclude new scope

First-pass test success

Tasks whose relevant tests pass on first validation / tasks with that validation

First-pass acceptance rate

Tasks accepted without substantive rework / reviewed tasks

Irrelevant files modified

Files changed outside justified task scope

Repeated instruction frequency

Repetition of guidance that should have been available

Human review effort

Active review effort for comparable changes

Context-related failures

Documented missing, stale, conflicting, or irrelevant information

Fewer corrections and irrelevant edits are useful signals, not universal targets. Clarifying questions can prevent defects. Faster review is not improvement if defects increase; higher test success means little if coverage weakens.

Claude Code context audit checklist

Use these yes/no questions to identify actions, not calculate an artificial composite score:

  1. Does persistent guidance remain relevant within its scope?
  2. Have duplicate rules been removed or consolidated?
  3. Have contradictory instructions been resolved?
  4. Is specialized guidance placed in appropriate modules?
  5. Can Claude retrieve authoritative references when needed?
  6. Are temporary notes separate and explicitly read?
  7. Are critical requirements backed by executed checks?
  8. Are MCP permissions limited to necessary access?
  9. Do shared artifacts have owners and review practices?
  10. Has guidance been refreshed after relevant project changes?

Investigate failures before adding rules. A missing permission, unclear requirement, or broken test environment may need a different intervention.

Frequently asked questions

What is context engineering in Claude Code?

Context engineering in Claude Code is the strategic process of selecting, organizing, and maintaining the specific information provided to an AI agent. It focuses on balancing the agent's attention budget by providing high-signal artifacts-such as specifications, tests, and relevant file contents-instead of overwhelming the model with excessive documentation.

Prompt engineering vs. context engineering: What is the difference?

Prompt engineering focuses on the wording and structure of instructions to guide model output. Context engineering refers to the broader curation of the entire information environment, including file retrieval, tool configurations, and session history. Prompt engineering defines the request, while context engineering provides the necessary world-state to fulfill it.

How does Claude Code prevent context rot during long tasks?

Claude Code prevents context rot by using compaction and subagents to manage information. Compaction summarizes message history to strip redundant tool outputs and raw file reads, while subagents handle high-noise exploration in a separate working context and return a compact result. Neither guarantees that every detail survives - verify important findings against repository evidence.

Where should I store my project guidelines?

You should store project-specific invariants and critical gotchas in CLAUDE.md, which is intended for essential architectural facts. Use scoped rules for path-specific conventions and modular skills for repeatable procedures. Avoid using CLAUDE.md for temporary task requirements, as this leads to stale and bloated configuration files.

What are the benefits of using subagents?

Subagents allow you to delegate high-noise tasks, such as deep repository searches or log analysis, to an isolated process. This keeps the parent session’s context window lean and prevents irrelevant exploration data from degrading the model's performance on the main coding task.

How do I know if my context setup is effective?

An effective setup is measured by task outcomes, specifically tracking metrics like the frequency of corrective prompts, first-pass test success, and the amount of human review effort. If an agent frequently struggles with repository idioms or repeated constraints, use the /doctor command to identify redundant or conflicting instructions.

Should I provide as much documentation as possible to the agent?

No. Providing excessive documentation leads to diminishing returns and potential context rot. Modern context engineering favors "progressive disclosure," where the agent retrieves specific, relevant information just-in-time-such as the exact schema or test contract-rather than loading large, static documentation files that consume limited attention budget.

Read more:

Conclusion

Effective context engineering isn't about loading less data-it's about supplying the right evidence when a decision needs it. By combining clear guidance, timely retrieval, maintained task state, and executable checks (the MINDS framework), you eliminate unnecessary rework. Start small: pick one source of confusion, clarify its acceptance criteria, and validate the output before adding more complexity.

Share this article