Model

Context engineering: how to build a working context for a model

How to organise an agent's instructions into layers, remove conflicts and repetition, and shorten context without reducing the quality of its work.

In this articleWhat goes into context

An agent's instruction file started with ten lines. Six months later it has three hundred: rules for every occasion, examples, a history of old mistakes, and the same requirement in three places. The agent has become slower; sometimes it stops halfway through a task to ask which of two rules to follow. Adding another rule will not help. You need to rebuild what the model receives before each request.

That is the purpose of context engineering. You tailor a prompt to one request. Persistent context affects every request, so you manage it as an architecture: layers, one owner for each rule, details loaded when needed, and any reduction tested on the same set of tasks.

What goes into context

Context engineering means designing everything the model receives besides the user's current message: the system prompt, project files, skills, tool descriptions, memory and connected material.

A prompt can be fitted closely to one task. Persistent context serves many requests, including ones you do not know about yet. Everything added “just in case” takes up space in the context window — the amount of text a model keeps in play — and creates noise. Noise makes important rules harder for the model to notice. Claude Code's documentation says this directly: excess context does more than fill the window; it gets in the way — skills trigger at the wrong time and the model loses track of project conventions.

The main technique is progressive disclosure: keep a short core with pointers to detailed instructions in persistent context, and load the instructions themselves when they are needed.

Five layers and what belongs in each

It is useful to build a working context from five layers. Each holds a different kind of information.

Five layers of context: the system prompt, project file and memory are always loaded; skills and references load per task
The layers work as one whole, but only some of them are always loaded.
  • System prompt. The agent's role, the product it works in, criteria for the result and mandatory constraints. This is not the place for project details, long procedures or repeated tool descriptions.
  • Project file — CLAUDE.md, AGENTS.md or an equivalent. The project's purpose, main commands, conventions and non-obvious features. This is not the place for detailed reference manuals or things the agent can already see in the files.
  • Skills and topic-specific instructions. Repeatable procedures and reference material needed for only some tasks. Load them when required. They are not the place for rules that must always apply.
  • References. Code, tests, HTML mock-ups, specifications and assessment rubrics for the current task. Attach them for that task. An imprecise summary of something that could be provided in full works particularly badly here.
  • Memory. Lasting decisions and lessons needed across sessions. It is not the place for incidental details from one task or duplicates of project rules.

There is no universal length limit. Claude Code's documentation offers a practical guide: keep CLAUDE.md under 200 lines and move reference material into skills or narrowly scoped rules. A sensible target for a small project may be considerably lower. If a file is growing, check which lines genuinely change the model's behaviour and need to load in every session.

One owner for each rule

When instructions contradict one another, the model spends reasoning effort choosing between them. Anthropic saw this in its own transcripts: a system prompt asked for documentation where appropriate, a skill forbade adding comments, and the user said “just do it like the old version”. The model generally manages, but has to think longer. Claude Code's documentation adds that when two instructions conflict, the model may choose one arbitrarily.

Who should own a rule:

  • how to use a particular tool — that tool's description;
  • what is true for a project or repository — its project file or a rule with the appropriate scope;
  • how to carry out a repeatable procedure — a skill;
  • what is true across all the agent's tasks — the system prompt;
  • what must be enforced without exception — code, a data schema, access rights or a hook, rather than text alone.

A hook is a script the environment runs automatically on a particular event, for example before a tool call. Claude Code's documentation stresses the difference: an instruction in CLAUDE.md remains a request to the model, while a PreToolUse hook can actually block a prohibited action.

If a rule appears in several layers, choose one owner and remove the duplicates.

What changed with newer models

Anthropic reported removing more than 80% of the Claude Code system prompt for models such as Claude Opus 5 and Claude Fable 5 without measurable loss on its internal coding evaluations. This shows that accumulated instructions can be cut substantially. But that figure comes from Claude Code tasks: the appropriate reduction depends on the product, the number of tools and the constraints accumulated, and must be tested against another agent's own workload.

In its GPT‑6 Astra guidance, OpenAI advises checking the skills and other files available to the model. The model follows long instructions better, but is more sensitive to the contents of those files: an unclear or contradictory instruction in a skill can make it stop at the very start of a task. OpenAI recommends stating explicitly that user instructions take precedence over skills and setting the expected degree of autonomy directly.

This leads to five changes in how to write context.

A criterion instead of an absolute

A rigid rule blocks a dangerous scenario but also breaks legitimate exceptions. An old Claude Code system prompt contained a general ban on multiline comments. It produced the wrong result for complex code and projects with their own requirements. Anthropic replaced the ban with a criterion:

Before:
Do not write comments by default. Never write multi-paragraph
docstrings or multiline comment blocks; at most one short line.

After:
Write code so it reads like the surrounding code: match its
comment density, naming and idioms.

Reserve “always” and “never” for real invariants: deleting data, handling secrets, writing to external systems or a mandatory response format. If a breach is unacceptable, add a technical constraint instead of relying on the wording.

The tool interface instead of explanations in the prompt

Examples of calls sometimes help, but tie the model to the scenario shown. Improve the tool itself first: typed parameters, an enumeration of valid values and a meaningful description of its behaviour. Anthropic revised Claude Code's task-list tool in this way: about 9,100 characters of examples became a short description, a list of statuses and one rule.

Weak interface + explanation in the general prompt:
tool: update_task(payload: string)
prompt: "Pass JSON with status; valid values are pending,
in_progress and completed"

Expressive interface:
tool: update_task(
  task_id: string,
  status: "pending" | "in_progress" | "completed"
)
description: "Updates task status. Keep no more than one task
in_progress at a time."

The enumeration defines valid data, while the behavioural rule stays with the tool. General context no longer needs to repeat it.

A short core and an instruction map

One large central file blurs priorities. A short core can direct the agent to the right document at the right time:

AGENTS.md                # purpose, main rules, instruction map
docs/
  verification.md        # checking work before completion
  release.md             # release procedure
  data-model.md          # non-obvious relationships in the data schema
  incident.md            # actions during an incident

AGENTS.md itself retains only routing: “before verifying changes — docs/verification.md”, “before a release — docs/release.md”.

Skills and tools work similarly in Claude Code. At the start of a session the model sees only skill names and descriptions; the full text loads when a skill is invoked or selected by meaning. With MCP servers — connected external services — tool names load first, while full schemas wait until a particular tool is called. The persistent context cost falls, though skill descriptions and tool names still take up space.

Memory is a separate layer

Claude Code can save useful lessons between sessions itself. So CLAUDE.md should not become a log of every detail found: it keeps stable project conventions, while memory stores lessons about the work and the user. This is a feature of a particular product, not of every agent. For your own system, decide in advance what memory exists, who can change it, how long it is retained and when it enters context.

Source material instead of a summary

The source artefact gives the model more precise information. An HTML mock-up produces a better result than a textual design description or screenshot. Tests specify expected behaviour, while a function from another project offers a pattern to transfer. A rubric — a list of criteria for a good result — helps with a separate verification pass or a reviewing agent, if that use is approved under your system's rules.

Where the agent acts and where it stops

Newer models handle long, multistep tasks better, but it is still best to state the desired level of initiative explicitly. According to OpenAI, GPT‑6 Astra asks clarifying questions when the answer could change the outcome. For an autonomous agent, describe which gaps it should close with a reasonable assumption and where it must stop. Keep the autonomy policy in one layer and align it with the tools' actual permissions: repeating it in several places creates conflicts and unnecessary stops.

Prompt
If I ask you to answer, explain, check, diagnose or plan,
examine the available material and report the result.
Do not change anything without a request to make a change.

If I ask you to change, build or fix something, make safe
local changes within the task and perform proportionate,
non-destructive validation.

Confirmation is required before writing to external systems,
destructive actions, purchases or a material expansion of scope.

Resolve the request with the fewest useful tool calls without
sacrificing correctness. After each result, check whether you
have enough information to answer. If so, finish. If not,
identify the missing fact and take the smallest suitable next step.

Starting templates

System prompt template:

Role: the agent's function and the product it works in
Goal: the result visible to the user
Success criteria: what must be true before the final answer
Constraints: safety, data, access rights, side effects
Autonomy: what the agent does itself and where it asks for confirmation
Tools: rules for choosing tools according to the situation
Output: format and length
Stop rules: when to retry, change approach, ask or stop
Style: only the presentation requirements that are needed

Project file template, using an invoicing service as an example:

# Purpose
Invoicing service. Monorepo with three packages.

# Main commands
Verification: make verify
Migrations: make migrate

# Pitfalls
- All shared types live in src/types.ts.
- Running psql directly bypasses the migration log.
- Tests in packages/api require docker-compose to be running.

# Instruction map
Verification of changes — docs/verification.md
Release — docs/release.md

Instructions, skills and configuration examples must not contain real tokens, passwords or keys. Give the environment variable's name and the location from which its value may be obtained.

How to shorten context without breaking the work

Change one group of instructions at a time so you can link a result to a particular edit.

The context-trimming loop: record the baseline, remove one group, rerun the same set of tasks; if quality held, keep the change, if not, restore a targeted rule
If removal consistently makes things worse, trimming stops.
  1. Record the baseline: current context, tool set, model and reasoning level. Run typical tasks and save the results.
  2. Remove one group: repetition, examples, style instructions or unused tools.
  3. Run the same tasks again with the same settings.
  4. If quality holds, keep the change and move to the next group.
  5. If a failure appears, restore the smallest targeted instruction that addresses that failure.
  6. Stop when further removals consistently worsen the result.

First, examine duplicates of a rule across layers, examples that do not improve the result, detailed instructions for actions already performed reliably, full descriptions of tools that these tasks do not need, and historical notes that have become permanent rules. Preserve the visible result and success criteria, stopping conditions, constraints on safety, data and permissions, tool selection rules, output format and non-obvious project features.

In Claude Code, /doctor suggests what to shorten in CLAUDE.md and skills. Treat its output as a proposal to test on your tasks. And before raising a model's reasoning level, ensure you have specified success criteria, dependencies between steps, tool routing and verification: a setting alone cannot replace missing information.

How to measure the result. Gather 10–20 real tasks, including typical and edge cases, and write a verifiable success criterion for each. With the original context, count the proportion of tasks passed, input and output tokens, tool calls and confirmation requests. Make one change and repeat with the same model and settings. The change is useful if quality is maintained or improved while cost and complexity fall.

If you have no formal evaluations, take five recent tasks and describe the correct result in advance. Run them before and after the edit, then compare the answers pairwise against one rubric. This is rougher than an automated evaluation, but better than a feeling that “it seems better”. If quality falls, inspect a few failed runs, find the specific failure, restore the needed rule or remove a remaining conflict, and repeat the same cases.

Check your context in five minutes

  • The system prompt and project file do not contradict one another.
  • Every rule has one owner.
  • “Always” and “never” are reserved for genuine invariants.
  • Examples remain where they noticeably improve the result.
  • The project file does not retell the repository's obvious structure.
  • Long topic-specific instructions live in loadable files or skills.
  • Tool rules sit beside the tool description.
  • Full schemas for rarely used tools load when needed, if the environment supports this.
  • The result has success criteria and a stopping condition.
  • Autonomy boundaries separate safe local actions from those requiring confirmation.
  • Specifications are provided as code, tests, mock-ups or rubrics.
  • Critical prohibitions are backed by technical controls.
  • Context changes are tested against the same set of tasks.

Common mistakes mirror this list: a dumping-ground file of every team practice, one rule in three layers, “never” applied to a style preference, tool parameters explained in long prose instead of a schema, a description of a mock-up when the HTML is available, the whole tool catalogue in every request, a critical prohibition expressed only as a wish, and a complete rewrite of context without a task set for verification.

A short core, clear owners, task-based verification

Good context has a short core, layers with clear owners, details loaded when needed, and technical prohibitions where a mistake would be unacceptable. Start by finding conflicts and repetition, then test the shorter version against an unchanged set of tasks.

The article someone else's skill does not know your work explains how to turn working experience into a skill instead of another rule in a general file. For what an agent needs besides good context, see ten checks of a workflow before handing it to an agent.

If the context for your agents is growing faster than your understanding of what works in it, we can examine it together in a free 30-minute meeting with Simplit. Discuss your task

Sources

Finished reading? Mark the step — your path progress will update.

Path · Step 5 of 11I implement AI technically
0 of 11