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

Five Open Speech Models in One Drop: Ant's MIT-Licensed Ming-3.0

Ant Group's inclusionAI open-sourced the five-model Ming-3.0 speech family under MIT on 2026-10-19/20 (multi-source confirmed; self-host, fine-tune, and commercial use all allowed), covering synthesis, audio understanding and dialogue, and recognition: Ming-3.0-tts-0.5B (0.5B dense, the lightest, deployable on four cards), Ming-3.0-tts-tiny (7.9B total / 1.3B active MoE, long-form multi-speaker podcasts), Ming-3.0-audio-flash (126B total / 6.5B active MoE, audio understanding and dialogue, answering in text or speech), Ming-3.0-audio-tiny (9.3B / 2.7B, efficiency-oriented), and Ming-3.0-asr-tiny (8.6B / 2B, context-aware transcription). Capabilities: TTS with text-described voices, a director mode that controls emotion, stress, and pacing in natural language, voice cloning, seven languages plus two dialects; audio understanding takes long recordings directly with structured output, preserving emotion and speaker identity, plus tool-call generation; ASR adds dialect recognition, hotword injection, and context awareness. Setup (verified against kie.ai and the README): TTS route - git clone github.com/inclusionAI/Ming-3.0-tts, conda env (0.5B: python 3.10, pip install -r requirements.txt, conda install -c conda-forge pynini==2.1.6), run per README; tts-tiny needs its own env with Python 3.10.15, PyTorch/Torchaudio 2.7.1 (cu118), Transformers 4.46.3; audio-flash via downloaded weights or Ling Studio Chat (ling.tbox.cn), 128K context, speech output through the Chat Completions audio.voice field with modalities=["text","audio"]. Hardware: officially tested mainly on datacenter cards - recommended NVIDIA H800 (80GB) or H20 (96GB); 0.5B on four cards is the floor; consumer-GPU feasibility unverified. Day-0 ecosystem: vLLM-Omni and SGLang-Omni adapted. Internal Ant usage (official): asr-tiny in the Afu doctor assistant, Alipay Search, Yixiaobao realtime voice, and security verification. Four limitations stated as-is: no quantized files (no GGUF/AWQ/EXL2), streaming in doubt (SGLang-Omni returns a full waveform even with stream=true, so true first-audio latency is unestablished), mutually exclusive control modes (voice design, emotion, and dialect cannot combine in one call), and unpublished training data. Leaderboard backing (secondary): Artificial Analysis TTS leaderboard (Provider Voices) puts Ming-3.0-tts at 1244, near the top. Division note: voice-cloning-toolkit-comparison-review (2026-10-15) is the review-lane selection piece; this SOP lane covers hands-on setup of the five-model stack - different lanes, different angles.

Oct 21, 20269 min read
Field SOP

AI Cross-Session Memory in 10 Minutes: MemHub Hands-On Guide

A hands-on SOP for wiring Tencent Hunyuan's ready-made memory stack into your AI agent, with every command taken from the MemHub README and verified against PyPI. Three install layers: the SDK via pip install hy-memory==2.0.3 (latest at writing time); the CLI via the npm memhub-cli bootstrapper (about 384KB) followed by memhub install to fetch the Runtime; data lives in ~/.one-memory. Platform support at v1.0.3: Linux x64/arm64 Runtime, macOS arm64/x64 App - Windows is not supported (explicit in the README; bolded in the body plus an FAQ, since many of our readers run Windows). Ten CLI commands walked through one by one: serve/start/stop/restart/status/doctor/install/upgrade/uninstall/delete-data, with a first-run flow example (install, then status to verify, doctor for a health check, serve, then connect your agent). Privacy boundary stated as-is: no screen capture, no OCR, no keyboard/mouse event collection, no clipboard reading, no audio recording. Tool count in two versions: the MemHub README lists 5 tools while Tencent's official WeChat article says 10 - the body picks neither and defers to actual CLI output. A standalone preview warning: both Hy Memory 2.0 and MemHub are preview-stage; commands and APIs may change, use with care in production. Pitfalls covered: a fallback route for Windows readers (WSL2 or wait for official support), pinning ==2.0.3 for reproducibility, and backing up ~/.one-memory by copying the directory. Division note: ai-agent-long-term-memory-sop (2026-08-08) covers the build-your-own mem0/Letta route (vector store plus files); this piece is Tencent's ready-made stack for readers who want it running today. Primary search phrase "AI cross-session memory" (S1=2/S2=1/S3=2/S4=3, about 8 points) lives in the title and this summary only, never in the article body.

Oct 20, 20269 min read
Field SOP

Claude Code DeepSeek Setup: Nine Env Vars, No Old Tutorials

A hands-on SOP for wiring Claude Code straight into DeepSeek, with every command and variable taken from the official guide (api-docs.deepseek.com/quick_start/agent_integrations/claude_code), reflecting the current configuration after the 1017 checkpoint. Primary search phrase: "Claude Code DeepSeek setup" (S1=3/S2=1/S3=2/S4=3). Migration path with nine environment variables: ANTHROPIC_BASE_URL to https://api.deepseek.com/anthropic, ANTHROPIC_AUTH_TOKEN with your DeepSeek API key, ANTHROPIC_MODEL=deepseek-flash[1m], DEFAULT_OPUS and DEFAULT_SONNET also deepseek-flash[1m], DEFAULT_HAIKU=deepseek-flash, CLAUDE_CODE_SUBAGENT_MODEL=deepseek-flash, CLAUDE_CODE_EFFORT_LEVEL=max, CLAUDE_CODE_AUTO_COMPACT_WINDOW=786432; both PowerShell and Linux/Mac variants are given. Install from scratch in four steps: Node.js 18+ (plus Git for Windows on Windows), npm install -g @anthropic-ai/claude-code, verify with claude --version, set the variables and run claude in your project directory. Model mapping: requests starting with claude-opus route to deepseek-v4-pro (billed at V4 Pro prices, pricier than Flash - a must-read reminder), claude-haiku and claude-sonnet route to deepseek-flash. Web Search works natively but bills on two lines: search requests per the Search API plus extra token costs for summarizing retrieved content. Pricing (official rate page): off-peak 0.15 dollars per million input tokens on cache miss, 0.003 on a hit (one fiftieth of the miss price), 0.60 output; peak (weekdays 01:00-04:00 and 06:00-10:00 UTC) doubles everything; weekends and Chinese public holidays count as off-peak. Five pitfalls: AUTH_TOKEN and API_KEY are not the same thing (mixing them equals no config), old and new variables coexisting can cause auth conflicts (keep only the new ones, per community guides), never commit keys via settings.json (persist them in ~/.bashrc, ~/.zshrc or system environment variables), validate the tool-calling chain with a minimal read-one-file-then-edit-one-file task before real work, and check the live model with /status. Older tutorials still reference retired names like deepseek-chat. Division of labor: deepseek-v4-pro-claude-code-sop is the V4-Pro-0813-era two-variable minimal setup (2026-09), while this piece is the full current official configuration after 1017; for the Harness itself see deepseek-harness-quickstart-sop.

Oct 19, 202610 min read