Field SOP
Field SOP

Context Engineering for AI Coding Agents: A Five-Step SOP for Structuring Context

A context-engineering SOP for AI coding agents (Claude Code/ZCode/Crush): structure context in five steps -- map project context, write rule files (CLAUDE.md/AGENTS.md), manage the context window, persist memory, and verify/iterate. Includes a real rule-file example, 5 pitfalls, and 5 FAQs.

Published August 11, 20268 min read
<!-- ai-coding-context-engineering-sop | sop | Context Engineering for AI Coding Agents: A Five-Step SOP for Structuring Context -->

Same Claude Code, two developers, wildly different results. One ships a legacy refactor in two weeks; the other breaks three things fixing one function. The gap is not the model -- it is the context. The project structure, coding conventions, red-line rules, and relevant code snippets you feed the agent are collectively called context. Context engineering is the practice of structuring, layering, and delivering this information on demand -- not writing a longer prompt, but making sure the agent sees what it should at every reasoning step and ignores what it should not.

This SOP gives you a repeatable flow: map project context -> write rule files -> manage the context window -> persist memory -> verify and iterate, five steps. Rule files use CLAUDE.md / AGENTS.md as examples (Claude Code reads CLAUDE.md, OpenCode/Codex reads AGENTS.md -- real conventions, not invented). Context management centers on Claude Code's @-mention / /compact / subagent mechanisms. Current as of 2026-08-11, with specific behavior subject to each tool's official docs. It pairs with the batch's ZCode 3.0 upgrade hotspot (Goals mode relies on context to decompose goals), AI coding plan comparison (how to use the plan you pick), and crush open-source coding agent resource (model-agnostic, depends on you configuring context) -- read them together.


1. Context Engineering Is Not Prompt Engineering

Let us clarify three easily confused concepts. The site's Tool Calling SOP covers how the model decides which API to call; the Computer Use SOP covers how the model sees the screen to operate a GUI. Context engineering is neither of these -- it solves "what you put into the model's context window before it reasons."

DimensionPrompt EngineeringContext Engineering
FocusHow to phrase one instructionHow to build the entire information ecosystem
ScopeOne conversationCross-session, cross-file, cross-tool
Core actionTweak wording, add examplesManage rule files, code references, memory layers
PersistenceDisposablePersisted to files, auto-loaded next time

In one sentence: prompt engineering teaches the AI how to talk; context engineering teaches the AI what to look at. For coding agents, the latter matters ten times more -- no matter how smart the model is, if it cannot see your project conventions it writes code in its default style, with the wrong architecture, stepping on traps you already solved.


2. The Five-Step SOP

Step 1: Map Project Context

Before writing any rule file, figure out what context in your project is worth structuring. Four categories are essential:

Tech stack and versions: language, framework, runtime, package manager, database. Do not let the agent guess whether you use Python 3.11 or 3.13 -- pin it. Directory structure: where core modules live, where the entry point is, where tests and configs are. Giving the agent a "map" beats letting it ls around. Coding conventions: naming style, error handling patterns, logging standards, test framework. These are "team dialects" the model cannot learn from training data. Red lines and no-go zones: files it must not touch, dependencies it must not introduce, checks it must not skip.

How to do it: run tree -L 2 -I "node_modules|.git|dist" in the project root to see the structure, run rg "TODO|FIXME|HACK" to see tech debt, skim package.json / pyproject.toml for dependencies. Distill these into a few lines of text -- that is the skeleton of your rule file.

Step 2: Write Rule Files (CLAUDE.md / AGENTS.md)

Rule files are the "constitution" of context engineering -- persisted in the project, auto-loaded every time the agent starts. Claude Code reads CLAUDE.md, OpenCode/Codex reads AGENTS.md, Cursor uses .cursor/rules/*.mdc (legacy: .cursorrules), and model-agnostic agents like Crush also depend on you configuring instruction files. The file goes in the project root with four sections:

Role definition: one or two sentences telling the agent what this project is and what its role is. Red-line rules: Never / Ask first / Always, three tiers, written as imperatives. Common commands: exact build, test, and deploy commands the agent can copy and run. Style conventions: a few hard rules on naming, formatting, and error handling.

Writing discipline: one rule per line, start with a bold keyword (Never / Always / Ask first), do not write long paragraphs -- the model follows short statements far better than prose. Keep total length under 50-80 lines; if it is too long the model ignores the latter half (see Pitfall 1 in Section 4). A real example is in Section 3.

Step 3: Manage the Context Window (@-Mentions / Pruning / Layering)

Rule files handle "persistent context," but each task also has "immediate context" -- the file being changed, relevant interface definitions, error logs. Three techniques for managing immediate context:

@-mentions: Claude Code supports @filepath syntax. Writing @src/auth/login.ts in the conversation injects that file's content into context. It is cleaner than manual copy-paste, and the agent is aware of the file path. Be precise -- @src/ pulls in the entire directory and may flood context with irrelevant files; @src/auth/login.ts pulls one file and is efficient. Layered loading: give the project structure first (so the agent sees the full picture), then task-relevant files (so it focuses), then error logs (so it corrects). Do not dump 20 files at once. Timely cleanup: use /compact in long conversations to compress history (summarizing early exchanges), use /clear to wipe entirely for a new task. Never pile three unrelated tasks into one session -- context pollution is deadlier than context scarcity.

Step 4: Memory and Persistence (Memory / Session State)

Rule files are "memory you wrote." There is also "memory the agent accumulates." Claude Code's memory has three layers:

Project-level CLAUDE.md: in the project root, shared by the team, committed to Git. User-level ~/.claude/CLAUDE.md: in your home directory, effective across projects, for personal preferences (e.g., "always reply in Chinese"). Subdirectory CLAUDE.md: placed in a subdirectory, loaded only when the agent works inside that directory -- perfect for module-specific conventions.

Subagents are another layer of isolation. Claude Code's .claude/agents/*.md defines subagents, each with an independent context window. The main agent delegates subtasks to them, and results come back without polluting the main context. ZCode 3.0's Subagents feature and Crush's multi-provider design follow the same principle: split complex tasks into domains and run them in parallel, keeping each agent's context clean. Long-running tasks that span sessions survive on this persistence layer -- idle tasks and Remote Control can run across days, but only if state and context are persisted.

Step 5: Verify and Iterate

Rule files are not write-once. After each task, check three things:

Were the rules followed?: check whether the agent's output violated your Never/Always rules. If it did, either the rule was not clear enough or the file was too long and got ignored. Are the rules outdated?: if the tech stack changed, the directory structure was reorganized, or commands changed, the rule file must follow. An outdated rule is worse than no rule -- the agent follows stale instructions, errors out, and you cannot figure out why. Should a new pitfall be added?: if you hit a new trap (e.g., a dependency version incompatibility), immediately add a rule to prevent recurrence. This site's own CLAUDE.md has an "operation log" mechanism: every completed step gets a record appended. That is iteration.

Spend 10 minutes a week reviewing your rule files -- delete the stale, add the newly discovered, trim the verbose. Rule files are like gardens: stop weeding and they grow wild.


3. Real Rule File Example

Below is a CLAUDE.md for a web project (for AGENTS.md, keep the content identical and rename the file). Feel free to adapt it.

markdown
# MyShop E-commerce Admin

Next.js 15 (App Router) + TypeScript + Prisma + PostgreSQL e-commerce admin.
Frontend components use shadcn/ui, styling uses Tailwind CSS v4.

## Red Lines

- **Never**: use `any` type; skip `npm run lint` and `npm test`; write raw SQL inside components
- **Ask first**: introduce new npm dependencies; modify prisma/schema.prisma; delete any existing API route
- **Always**: run `npm run lint && npm test` after changes; add Zod input validation to new API routes;
  write a Prisma migration before running `npx prisma migrate dev` for DB changes

## Common Commands

- Dev: `npm run dev` (port 3000)
- Build: `npm run build`
- Test: `npm test` (Vitest)
- Lint: `npm run lint`
- DB migration: `npx prisma migrate dev --name <description>`

## Style Conventions

- Component files use PascalCase (e.g., `ProductCard.tsx`), utility functions use camelCase
- API routes live under `app/api/` and return a `{ data, error }` structure
- Error handling: throw `AppError` for business errors, try/catch system errors and return 500
- All timestamps stored as UTC, converted to the user's timezone on the frontend

Corresponding context reference example (in a Claude Code conversation):

text
# Precise reference: give only the files the current task needs
Please refactor the error handling in @src/api/orders/route.ts.
The related type definitions are in @src/types/order.ts,
and AppError is implemented in @src/lib/errors.ts.
Refer to @src/api/products/route.ts for the error handling pattern to stay consistent.
Run @npm run test to verify nothing is broken.

Key points: @filepath references are precise to the file, not the directory; all relevant files are given at once (type definitions + dependency implementation + reference example); finally, the agent runs tests itself to verify. This is far more efficient than saying "fix the order endpoint" and manually pasting five files.


4. Five Pitfalls

Pitfall 1: Rule file too long, model ignores the second half Stuffing every convention, command, and historical decision into CLAUDE.md until it hits 300 lines. The model's attention is finite, and compliance with the latter half of long texts drops noticeably. Fix: keep total length under 50-80 lines, and only include rules that "must be followed every time." Move rarely needed conventions into subdirectory CLAUDE.md files for on-demand loading. Delete rules that go without saying (like "write clean code" -- the model already does that).

Pitfall 2: Context window overflow, agent "loses memory" A long conversation piles up a dozen file references and dozens of back-and-forth rounds. Once it exceeds the context window, early information gets truncated. The agent forgets your project uses TypeScript and starts writing JavaScript. Fix: use /compact periodically to compress history; start a fresh session with /clear for unrelated tasks; have subagents process large files and return only summaries to the main session. Model-agnostic agents like Crush need extra attention here -- different models have very different context window sizes, and switching models may push you over the limit.

Pitfall 3: Rule conflicts, multi-layer memory fights Project-level CLAUDE.md says "use pnpm," user-level ~/.claude/CLAUDE.md says "use npm." The two rules conflict, and the model picks one at random. Fix: user-level files should only hold personal preferences (language, reply style), while project-level files hold project conventions (tech stack, commands). Project-level takes priority on conflicts. Check both layers periodically for contradictions.

Pitfall 4: Memory goes stale, old rules pollute new tasks The project migrated from REST to GraphQL last month, but CLAUDE.md still says "new API routes go under app/api/." The agent follows the stale rule and generates REST routes that are completely out of sync with your current architecture. Fix: update rule files immediately after tech stack changes; add a "last updated" date at the top as a reminder; use the Step 5 verification mechanism to check whether rules still match the code.

Pitfall 5: Rules never iterated, become abandoned documentation The rule file was written once and never touched again. Three months later the project has changed significantly, and the rule file is dead paper. The agent does not know it is dead -- it reads the file content regardless of whether it is current. Fix: treat rule files as living documents, review them weekly; add a rule immediately after every new pitfall; keep an "operation log" in DEV.md or project docs, and record every rule file change too.


5. FAQ

Q1: What is the difference between CLAUDE.md and AGENTS.md? Which should I use? They are the same convention under two filenames. Claude Code reads CLAUDE.md, OpenCode/Codex reads AGENTS.md. If you only use Claude Code, write CLAUDE.md. If teammates use OpenCode or Codex, write both files and keep their content identical. This site's own approach is to add a note at the top of CLAUDE.md: "keep in sync with AGENTS.md."

Q2: How long should a rule file be? Is there a limit? There is no hard limit, but 50-80 lines is recommended. Rule of thumb: if a rule is not "must be followed on every task," it does not belong in the root CLAUDE.md -- put it in a subdirectory CLAUDE.md or in code comments. Compliance with the latter half of long rule files drops, so brevity wins. If you truly cannot fit everything, split into multiple files in subdirectories and load on demand.

Q3: What is the difference between @-mentions and pasting code directly? @-mentions let the agent know the real file path, so it can locate and modify the file directly afterward. Pasting code only gives the agent text -- it does not know which file it came from, and you have to sync changes back manually. Additionally, @-mentions are tagged as "file context" in Claude Code, distinguished from conversation text, and the model weights file content higher. So for any existing file in the project, prefer @-mentions.

Q4: If I switch models (e.g., from Claude to GLM), do I need to rewrite the rule file? No rewrite needed, but you may need to adjust phrasing. CLAUDE.md / AGENTS.md are plain Markdown that any instruction-reading agent can use. The difference is that models vary in how well they follow rules: Claude has high compliance with structured rules (Never/Always tiers); GLM models understand Chinese rules well but sometimes need more explicit phrasing; Crush is model-agnostic -- switching models only changes the provider config, not the rule file. Recommendation: use short sentences with bold keywords -- all models respond well to this format.

Q5: What is the relationship between context engineering and RAG (retrieval-augmented generation)? They are complementary. RAG is "on-demand retrieval of external knowledge" -- your codebase is not in the model's training data, so the agent uses semantic search to find relevant code snippets and injects them into context. Context engineering is the larger framework: rule files are "persistent context," @-mentions are "manual context injection," and RAG is "automatic context retrieval." A mature coding agent uses all three: load CLAUDE.md at startup (persistent), @-mention relevant files during conversation (manual), and use codebase indexing for semantic search in the background (RAG). ZCode 3.0's "full context awareness" bakes the RAG layer into the agent kernel.


References

This article is AI-assisted and human-edited. Last updated: 2026-08-11

FAQ

What is the difference between CLAUDE.md and AGENTS.md? Which should I use?
They are the same convention under two filenames. Claude Code reads `CLAUDE.md`, OpenCode/Codex reads `AGENTS.md`. If you only use Claude Code, write `CLAUDE.md`. If teammates use OpenCode or Codex, write both files and keep their content identical. This site's own approach is to add a note at the top of CLAUDE.md: "keep in sync with AGENTS.md."
How long should a rule file be? Is there a limit?
There is no hard limit, but 50-80 lines is recommended. Rule of thumb: if a rule is not "must be followed on every task," it does not belong in the root CLAUDE.md -- put it in a subdirectory CLAUDE.md or in code comments. Compliance with the latter half of long rule files drops, so brevity wins. If you truly cannot fit everything, split into multiple files in subdirectories and load on demand.
What is the difference between @-mentions and pasting code directly?
@-mentions let the agent know the real file path, so it can locate and modify the file directly afterward. Pasting code only gives the agent text -- it does not know which file it came from, and you have to sync changes back manually. Additionally, @-mentions are tagged as "file context" in Claude Code, distinguished from conversation text, and the model weights file content higher. So for any existing file in the project, prefer @-mentions.
If I switch models (e.g., from Claude to GLM), do I need to rewrite the rule file?
No rewrite needed, but you may need to adjust phrasing. CLAUDE.md / AGENTS.md are plain Markdown that any instruction-reading agent can use. The difference is that models vary in how well they follow rules: Claude has high compliance with structured rules (Never/Always tiers); GLM models understand Chinese rules well but sometimes need more explicit phrasing; Crush is model-agnostic -- switching models only changes the provider config, not the rule file. Recommendation: use short sentences with bold keywords -- all models respond well to this format.
What is the relationship between context engineering and RAG (retrieval-augmented generation)?
They are complementary. RAG is "on-demand retrieval of external knowledge" -- your codebase is not in the model's training data, so the agent uses semantic search to find relevant code snippets and injects them into context. Context engineering is the larger framework: rule files are "persistent context," @-mentions are "manual context injection," and RAG is "automatic context retrieval." A mature coding agent uses all three: load CLAUDE.md at startup (persistent), @-mention relevant files during conversation (manual), and use codebase indexing for semantic search in the background (RAG). ZCode 3.0's "full context awareness" bakes the RAG layer into the agent kernel.

Related

Field SOP

LLaDA-Image Local Deploy SOP: Setup, Inference, Production

A five-step SOP for running Ant's open-source 6B image model LLaDA-Image: (1) environment setup with dependencies and mirror-accelerated downloads; (2) choosing among four weight variants (Base 50-step / Turbo 4-step, each in BF16 or FP8, with ModelScope for China); (3) generating the first image with minimal Base and Turbo commands; (4) advanced work - reference-image editing, text rendering, ComfyUI integration, and degradation strategies when VRAM runs short; (5) productionizing with batch queues, concurrency sizing, cost monitoring, result storage and graceful failure modes. Includes 6 pitfalls and a 10-item launch checklist, with every command copied verbatim from the official README; note the repo license is null, so confirm rights before commercial use.

Sep 9, 202611 min read
Field SOP

Self-Hosting OpenMAIC: From Zero-Deploy to Agent Workbench

A complete SOP for getting OpenMAIC running from zero: (1) zero-deploy hosted mode with an access code from open.maic.chat; (2) standard local setup (pnpm >= 10: clone, pnpm install, .env, pnpm dev); (3) production (pnpm build && pnpm start, one-click Vercel, docker compose up --build); (4) advanced (Postgres persistence profile, ACCESS_CODE, MP4 export profile, Lemonade/FunASR local providers); (5) wiring it into agent workbenches (clawhub install openmaic or importing skills/openmaic/, generating classrooms from Feishu/Slack messages). Includes 6 pitfalls and a 10-item pre-launch checklist, with every command copied verbatim from the official README.

Sep 8, 202611 min read
Field SOP

Building a Computer Use Agent: A Practical SOP from Sandbox to Safety Guardrails

A hands-on SOP for building a Computer Use Agent: sandbox setup, wiring the Anthropic Computer Use API, the main screenshot-decide-act loop, safety guardrails, and tuning -- five steps. Includes runnable Python (ast.parse-verified), 5 pitfalls, and 5 FAQs. Since "can operate a computer" equals "can cause harm", it emphasizes sandbox isolation, action allowlists, and human confirmation for sensitive operations.

Aug 11, 20268 min read