Context Engineering for Coding Agents: A Practical Repository Guide
Context engineering for coding agents makes local knowledge discoverable, scoped, authoritative, and verifiable across tasks. Build a repository context system that survives fresh sessions.
Context Engineering for Coding Agents: A Practical Repository Guide
Context engineering for coding agents is the design of repository information, instructions, tools, and feedback so an agent can discover the right local evidence before it changes code and prove the result afterward.
It is not a longer prompt. It is not a larger context window. It is not a folder full of documentation.
A repository has a working context system when a fresh coding-agent session can answer four questions without private chat history:
- What outcome is authorized?
- Which local sources control this decision?
- What may change, and what must not change?
- Which evidence proves the result?
If the agent must guess, the repository has a context gap.
The short answer
Build repository context in this order:
- Define task authority. State the requested outcome, acceptance criteria, and whether the agent may edit.
- Create one operating entry point. Use a root
AGENTS.mdor the tool’s documented equivalent to route the agent to local sources of truth. - Map the repository. Name entry points, package ownership, generated surfaces, and architecture boundaries.
- Make proof executable. Map change types to exact validation commands.
- Record surprising decisions. Preserve why local choices differ from generic conventions and what would reopen them.
- Scope context near the decision. Put package-specific rules beside the package instead of loading them globally.
- Test in a clean session. Verify discovery, action selection, validation, and handoff without replaying the corrective prompt.
A practical starting tree can be small:
repository/
├── AGENTS.md # operating router and global boundaries
├── docs/
│ ├── ARCHITECTURE.md # map and dependency boundaries
│ ├── VALIDATION.md # change type -> proof command
│ └── decisions/ # accepted tradeoffs and reopening conditions
├── packages/
│ └── billing/
│ └── AGENTS.md # scoped instructions, if the tool supports them
└── scripts/
└── verify.sh # executable aggregate proof
The filenames are examples. The properties matter more: clear authority, narrow scope, one source of truth, executable proof, and a feedback loop.
Context is a decision system, not a text collection
A weak definition says context is everything the model can see. That is true but not useful.
For repository work, context matters only when it changes a decision:
- which file is authoritative;
- whether the request permits mutation;
- which boundary must remain intact;
- which command proves a change;
- whether a failure should stop the task;
- what evidence must survive into review.
This gives a practical quality test for every instruction or document:
Which agent decision does this information control, and how will we know the agent used it correctly?
If there is no answer, the material may be background reading rather than operating context. Do not automatically load it into every session.
The five context layers
Coding-agent context comes from five different layers. They have different lifetimes and should not be treated as one undifferentiated prompt.
| Layer | What it owns | Lifetime | Typical location |
|---|---|---|---|
| Task | Requested outcome, acceptance criteria, mutation authority | One work item | Issue, prompt, story packet |
| Session | Current discoveries, hypotheses, command results, unfinished state | One run unless promoted | Plan, checkpoint, handoff |
| Repository instructions | Durable workflows, boundaries, maps, proof commands | Many tasks and tools | AGENTS.md, scoped rules, workflow docs |
| Decision history | Why local choices exist and when they may change | Long-lived | ADRs, compatibility contracts |
| Model knowledge | General patterns learned outside the repository | External and uncertain | Model prior, verified against local evidence |
The five layers of coding-agent context guide provides the full diagnostic framework. The central authority rule is simple:
Generic model knowledge can propose a possibility, but it cannot overrule explicit task authority or current local evidence.
Task context tells the agent what success means now. Repository context tells it how work happens here. Decision history explains why local practice may look unusual. Session context preserves current work. Model knowledge fills gaps only after local sources have been checked.
Context engineering versus prompt engineering
Prompt engineering and context engineering solve different problems.
| Question | Prompt engineering | Repository context engineering |
|---|---|---|
| Primary job | Define the current outcome | Define repeatable local operation |
| Lifetime | One task | Many tasks and sessions |
| Contents | Scope, acceptance criteria, temporary constraints, authority | Maps, commands, boundaries, contracts, decisions |
| Review surface | Task discussion | Version-controlled diff |
| Failure signal | Agent solves the wrong task | Fresh sessions repeat the same local mistake |
| Verification | Did this task meet its criteria? | Can a clean session discover and follow the rule? |
A good task prompt can be short when the repository carries its own operating knowledge:
Add CSV export to the reports endpoint.
Acceptance criteria:
- preserve the existing JSON response;
- stream large exports;
- add authorization and content-type contract tests.
Follow the repository's scoped instructions and validation map.
The prompt should not restate package ownership, generated-client rules, test commands, and architecture history if those facts are already current and discoverable in the repository.
The deeper failure pattern is covered in why coding-agent prompts fail when context lives only in prompts.
The four properties of useful repository context
1. Discoverable
The right information must appear before the expensive decision.
A correct validation document that no agent finds is operationally missing. A decision record linked only from an old pull request is not durable context. A package rule hidden in a global wiki will lose to nearby code and generic model expectations.
Use entry points as routers:
# AGENTS.md
## Read first
- Architecture map: `docs/ARCHITECTURE.md`
- Validation by change type: `docs/VALIDATION.md`
- Accepted decisions: `docs/decisions/`
- Package-specific instructions: the nearest applicable `AGENTS.md`
2. Scoped
Context should be available where it governs a decision and absent where it does not.
A migration rollback rule belongs near database work. Frontend accessibility checks belong near the UI package. A repository-wide prohibition on editing generated artifacts may belong at the root if it applies everywhere.
Scope reduces noise and conflict. For tools that support nested instruction files, place local guidance near the governed subtree and verify the tool’s discovery and precedence behavior. Tool support is not identical, so keep the canonical shared contract portable and use thin tool-specific adapters where necessary.
See coding-agent context file formats for current discovery and precedence differences across AGENTS.md, CLAUDE.md, Cursor Rules, Copilot instructions, and other formats.
3. Authoritative
Every important question needs one controlling source.
Bad context systems contain three plausible test commands, two conflicting architecture diagrams, and a generated file that looks handwritten. More text makes the decision harder because authority is ambiguous.
For each durable fact, identify:
- the source of truth;
- its scope;
- its owner or update trigger;
- the evidence that detects drift.
The root instructions should link to the source, not copy it into another location.
4. Verifiable
Prose should connect to observable proof.
“Run the relevant tests” is not a validation contract. A useful instruction names the command, when it applies, and what a failure means.
## Validation
- Documentation-only change: `npm run lint:docs`
- API behavior change: `npm run test:contract && npm run typecheck`
- Generated client change: edit `api/openapi.yaml`, run `npm run generate`, then `git diff --exit-code -- src/generated`
- Database migration: `npm run migration:validate`, then stop for human review
The command is not merely convenient. It converts repository knowledge into evidence another person or agent can reproduce.
Build the repository context architecture
Step 1: Start from a real failure
Do not begin by inventing a documentation taxonomy. Begin with a repeated wrong decision:
- the agent edited generated output;
- it changed code during a review-only task;
- it skipped an integration check;
- it crossed a package boundary;
- it reopened a settled compatibility choice;
- it claimed success without running the required proof.
Capture the first wrong decision, not every later symptom. One early context failure can create a long chain of bad edits.
The coding-agent failure-mode taxonomy helps distinguish missing routing, authority, validation, state, and recovery controls.
Step 2: Put the correction in the right layer
Use this placement matrix:
| Information | Correct home | Avoid |
|---|---|---|
| Acceptance criteria for one issue | Task or story packet | Permanent root instructions |
| Read-only versus edit authority | Task | Assuming “help” implies mutation |
| Current failed command and hypothesis | Session plan or checkpoint | Publishing an unverified guess as policy |
| Canonical setup and validation commands | Repository instructions or linked validation doc | Repeating commands in personal prompts |
| Generated-file rule | Scoped instructions plus a mechanical check | Relying on file names alone |
| Package ownership boundary | Architecture map or local instructions | A global paragraph with no path scope |
| Why a surprising design exists | Decision record | An inaccessible old conversation |
| Multi-session migration state | Versioned active plan with recovery steps | Leaving state only in chat history |
| Generic framework convention | Model knowledge, checked against local code | Treating popularity as local proof |
Two questions resolve most placement disputes:
- If the information changes per task, why should every future session load it?
- If every fresh session needs it, why is it still trapped in a prompt or maintainer memory?
Step 3: Make the root instruction file a router
A root AGENTS.md should orient and route. It should not become a second README, an architecture book, and a copy of CI configuration.
A strong root file usually covers:
# Repository operating guide
## Purpose
One sentence naming the system boundary.
## Authority
Distinguish answer, review, bounded change, and durable multi-session work.
## Read first
Link the repository map, workflow, validation matrix, and decisions.
## Boundaries
Name generated, vendored, sensitive, irreversible, or approval-gated surfaces.
## Validation
Map common change types to exact commands or to one canonical table.
## Handoff
Require files changed, commands and results, omissions, assumptions, and residual risks.
The guide to writing an AGENTS.md that actually works includes a complete implementation pattern. The AGENTS.md template provides a copyable starting point.
Step 4: Create a repository map
A coding agent needs more than a directory tree. It needs to know where decisions begin and which boundaries matter.
# Repository map
- `src/http/`: request parsing and authentication adapters
- `src/billing/`: billing decisions; must not import HTTP types
- `src/ledger/`: immutable ledger writes
- `api/openapi.yaml`: API source of truth
- `src/generated/`: generated output; never edit directly
- `docs/decisions/`: accepted architecture and compatibility decisions
A useful map identifies entry points, sources of truth, dependency direction, generated surfaces, and high-risk areas. It does not narrate every directory.
Step 5: Build a validation contract
Map change types to proof before the agent starts editing.
| Change type | Required proof | Stop condition |
|---|---|---|
| Documentation only | docs lint + link check + site build | Broken public route or schema |
| UI component | focused tests + accessibility checks + production build | Keyboard or build regression |
| API behavior | unit + contract + type checks | Public contract changed outside scope |
| Generated client | source edit + regeneration + clean generated diff | Generator or schema mismatch |
| Database migration | migration validation + rollback rehearsal | No safe rollback or human approval |
| Release workflow | build, identity, checksum, disposable install smoke | Artifact identity or recovery gap |
The validation matrix should match CI, scripts, and current package configuration. If the documented command stops working, update the context in the same change that updates the toolchain.
Step 6: Record decisions that surprise a capable outsider
Do not document every choice. Record choices an agent is likely to “correct” using a generic best practice.
A short decision record needs:
# Decision: Preserve the local billing adapter
Status: accepted
Context:
The public billing contract must remain stable across provider upgrades.
Decision:
All provider access goes through `src/billing/provider-adapter.ts`.
Rejected alternative:
Direct provider SDK imports inside domain modules.
Why:
The adapter isolates version churn and normalizes retry semantics.
Reopen when:
The provider contract becomes stable or the adapter blocks a measured requirement.
The important field is not the date. It is the reopening condition. It tells an agent whether the choice is permanent, provisional, or evidence-dependent.
Step 7: Preserve state only when work must survive the session
Not every task needs a durable plan. Multi-package migrations, release recovery, and producer-consumer changes often do.
A useful checkpoint names:
- the exact baseline commit;
- completed and remaining outcomes;
- commands already run;
- failures and hypotheses;
- changed contracts;
- rollback or recovery state;
- the next verifiable action.
This is context engineering because it prevents the next session from reconstructing state through guesswork. The coding-agent handoff template provides a reusable format.
Three examples: from context gap to durable control
Example 1: Generated code is edited directly
Failure: An agent modifies src/generated/client.ts because it is the visible implementation.
First wrong decision: It selected the wrong editable source.
Durable repair: Add a scoped rule naming api/openapi.yaml as authoritative, the generation command, the required contract test, and the expected generated diff. Add CI that fails when generation is dirty.
Clean-session test: Ask for a response-shape change. Verify the agent edits the schema, regenerates, runs the contract test, and reports both diffs.
Example 2: A review request turns into a code change
Failure: The task asks for risk analysis, but the agent starts fixing the files it reviews.
First wrong decision: It inferred mutation authority from the verb “help.”
Durable repair: Make the task outcome explicit. If the pattern recurs, add a repository-wide rule distinguishing answer, review, and change outcomes.
Clean-session test: Submit another review-only task and confirm the worktree remains clean.
Example 3: A migration appears successful but cannot resume
Failure: The agent updates external state, crashes before recording the checkpoint, and repeats the mutation after restart.
First wrong decision: The workflow treated forward progress as proof of recoverability.
Durable repair: Document the mutation-to-journal ordering, add idempotency or reconciliation identifiers, and create failure-injection tests at every mutation/checkpoint boundary.
Clean-session test: Kill the process after each boundary, reload persisted state, rerun recovery, and verify that the operation converges without duplicate effects.
This is the boundary between explanatory context and a real harness: critical rules become executable controls.
Anti-patterns that make context worse
Context dumping
Loading every design note, issue, and transcript does not guarantee the right fact is visible when needed. It increases irrelevant material and hides authority.
Repair: route from small entry points to scoped sources.
Copying the same rule into multiple files
Copies drift. The most detailed copy often looks authoritative even after it becomes wrong.
Repair: keep one source of truth and link to it.
Using prose as a security boundary
An instruction can influence behavior, but it does not enforce permissions, protect secrets, or make destructive operations safe.
Repair: use permissions, hooks, CI, isolation, and human approval for hard boundaries. Let prose explain the policy; let controls enforce it.
Treating all failures as instruction failures
Some failures come from ambiguous tasks, broken tools, missing tests, stale decisions, or recovery design—not from missing prompt text.
Repair: diagnose the earliest failed layer before adding documentation.
Keeping context after it stops changing decisions
Stale context remains plausible and therefore dangerous.
Repair: define update triggers and delete obsolete instructions when the code, workflow, or policy changes.
Test the context system in a clean session
Do not validate repository instructions inside the session that wrote them. That session already has the missing information.
Use this clean-session gate:
- Start from the repository root with no copied corrective prompt.
- Ask the agent to summarize the requested outcome and whether editing is authorized.
- Ask it to identify the controlling instruction, editable source, and relevant boundary.
- Ask which commands would prove the change before editing.
- Give it one representative bounded task.
- Independently rerun the required checks.
- Review whether the handoff reports commands, results, omissions, assumptions, and residual risks.
The context repair passes only if the fresh session finds and applies it before the old mistake recurs.
A 30-minute repository context audit
Pick one recent agent task and score these questions:
Discovery
- Is there a clear operating entry point?
- Can the agent find the repository map and sources of truth?
- Are scoped instructions discoverable before local edits?
Authority
- Does the task distinguish analysis from permission to mutate?
- Is each important rule owned by one authoritative source?
- Do local code, tests, and decisions outrank generic model assumptions?
Boundaries
- Are generated, vendored, sensitive, and irreversible surfaces explicit?
- Are package and architecture boundaries named?
- Do hard boundaries use enforcement instead of prose alone?
Validation
- Does every common change type have an exact proof command?
- Do documented commands match current CI and package scripts?
- Does the handoff expose checks not run and residual risks?
Learning
- Can a repeated failure be traced to its first wrong decision?
- Are surprising choices preserved with reopening conditions?
- Is obsolete context deleted when behavior changes?
For a complete scoring model, use the repository agent-readiness audit.
Start with one expensive repeated mistake
Do not redesign the whole repository at once.
Choose one repeated failure that costs review time or creates risk. Identify the first wrong decision. Put the missing information in the narrowest authoritative location. Connect it to executable proof. Then rerun the scenario in a clean session.
That loop is context engineering:
observe → diagnose → place → enforce → verify → maintain
repository-harness provides an open-source starting system for repository instructions, context routing, validation, decision memory, planning, and evidence-based handoffs across Claude Code, Codex, Cursor, and other coding agents.
Related pages
- The Five Layers of Coding-Agent Context — diagnose which layer failed
- Why Coding-Agent Prompts Fail — move repeated corrections into durable sources
- Coding-Agent Failure Modes — identify the first wrong decision and missing controller
- How to Write an AGENTS.md That Actually Works — build the operating router
- AGENTS.md Template — copyable starting structure
- How to Audit a Repository for Agent-Readiness — complete 100-point audit
- Harness Engineering for Coding Agents — extend context into the operational workflow
- repository-harness on GitHub — open-source implementation
FAQ
What is context engineering for coding agents?
Context engineering for coding agents is the design of repository information, instructions, tools, and feedback so an agent can discover the right local evidence before it changes code and prove the result afterward.
How is context engineering different from prompt engineering?
Prompt engineering defines the outcome, constraints, and authority for one task. Repository context engineering encodes durable local knowledge and proof paths that many tasks, sessions, people, and tools need.
What should go in AGENTS.md?
Use AGENTS.md as a concise operating router: identify the repository, name controlling sources, state boundaries and exact validation commands, and link to deeper architecture, workflow, and decision documents. Keep task-specific details in the task.
Can too much context make a coding agent worse?
Yes. Duplicated, stale, conflicting, or irrelevant context hides authority and consumes attention. Place each rule at the narrowest useful scope, link instead of copying, and remove information that no longer changes decisions.
How do you test repository context?
Start a clean session with a representative task. Verify that the agent finds the controlling instructions, chooses the correct editable surface, names the required checks before editing, runs them, and reports evidence and omissions at handoff.
Is repository context the same as RAG?
No. RAG retrieves material at runtime. Repository context engineering also covers authority, scope, executable validation, decision history, safety boundaries, and feedback loops. Retrieval can be one component, but retrieval alone does not define what controls or how correctness is proved.
What is the minimum viable context system for a repository?
A useful minimum is a root instruction router, a repository map, exact setup and validation commands, explicit safety and generated-file boundaries, and a handoff format that reports evidence. Add scoped instructions and decision records only where repeated failures justify them.