Designing coding agent context in large repos as a layered, file-based contract
Design AGENTS.md, scoped instructions and search so coding agents handle large monorepos safely without exploding token cost.
What you are actually building
This guide shows how to design context for coding agents in a large mono-/multi-repo so they can make real changes without corrupting architecture or exploding token bills. If you are already running Claude Code, Cursor or Copilot in production, think of this as the repo-level contract that lets those tools operate more like the AI development workflow you actually want, not a demo toy.
GitHub’s status checks documentation includes a PR checks screenshot that makes the article’s validation loop concrete, showing how tests and CI gates appear in a familiar review interface for agent-authored changes.
The core pattern is a layered, file-based contract:
- a small root
AGENTS.md / CLAUDE.md that maps the repo and global rules
- scoped instruction files in key directories (frontend, backend, infra, generated)
- explicit dependency boundaries that agents are told not to cross
- a deterministic search strategy that prefers tools and graphs over raw long context
- a validation loop (tests, CI, ownership) that catches violations
According to reports summarized in the AGENTS.md standard, naive use of large, full‑repo context files can materially increase inference cost in large projects by driving extra exploration. The design below keeps your root map within a few hundred lines, pushes detail to where it is used, and combines tool-native navigation, Repository Intelligence Graph–style maps and CI so Claude Code, Cursor, Copilot or similar tools can work safely at scale. It also lines up cleanly with production recipes in guides like safe Claude Code permissions for production repos and production-ready Cursor rules for real projects.
Why coding agents struggle in large repositories
Coding agents demo well in tiny sandboxes. In a 200k+ LOC monorepo they usually fail for three reasons:
- Navigation entropy: without a map, the agent does brute-force searches, reading many irrelevant files. Research on long-context coding agents shows they can process large corpora via tools and filesystem navigation, but they need structure to decide where to look first ("Coding Agents are Effective Long-Context Processors").
- Implicit boundaries: layers, ownership and dependency rules live in team lore or ADRs, not where the agent looks. It may wire
apps/web straight to infra/, or edit generated code, if those boundaries are not made explicit.
- No validation contract: without an agreed change budget, test strategy and ownership, the agent tends to over-edit, under-test, and produce diffs that are hard for reviewers to assess.
Context engineering work argues that the difference between impressive demos and production-safe agents is explicit operating contracts and maps, plus review context driven by diff, tests and ownership rather than full-repo dumps (Agitech context engineering article). If you want agents to open pull requests that you can actually ship, you need the same discipline you would use for a safe AI coding agent PR workflow.
Token and cost impact of naive context
AgentPatterns’ AGENTS.md standard references evaluations where adding repo-level context files noticeably increased inference cost, largely because agents followed broad instructions into extra exploration.
Combined with token accounting work on tool-using agents (context-engineering repo), there are two main cost levers:
- Repeated fixed context: every time Claude Code, Cursor or Copilot reads a large
AGENTS.md, those tokens are re-billed.
- Navigation chatter: every search, file-open and tool response consumes tokens; in large repos this often dominates the human prompt and edit itself.
The aim is not zero overhead, but structured overhead that pays for itself in higher success rates, while keeping the increase closer to a modest uplift rather than a large percentage jump. This is also how you keep your actual monthly developer seat costs close to the envelopes in stacks like Cursor + Codex + Claude Code, instead of drifting because agents are wandering the repo.
Core concepts used in this guide
- Context map: a compact, deterministic description of repo topology and rules.
- Scoped instructions: local contracts in directories or packages that override or refine the root where necessary.
- Dependency boundaries: explicit allowed directions between modules, plus forbidden edges.
- Search strategy: the order in which the agent is allowed to explore (which directories, which tools, when to expand scope).
- Validation loop: automated checks (tests, lint, CI, ownership) that enforce rules regardless of the agent’s behaviour.
Designing a context map for a large monorepo
AGENTS.md defines a project-level instruction file at the repo root that gives coding agents maps, rules and boundaries. The key is to treat it as a thin, stable index, not a full manual. This mirrors how Claude Code expects a concise CLAUDE.md at the root, as covered in the dedicated CLAUDE.md structure guide.
The Claude Code onboarding guide shows that the tool generates a CLAUDE.md at the repository root, reinforcing the article’s pattern of treating AGENTS.md or CLAUDE.md as a thin, stable index for the whole monorepo.
What a context map should contain
Guides on sharing repo context across agents recommend a small set of stable elements: architecture/package map, dependency directions, entry points, build/test commands, ownership paths, and non-goals (Graphify guide). Context engineering work further suggests keeping the global map short and pushing procedures closer to use (Context Wire article).
For a TypeScript/Node monorepo, that usually means sections like:
- Purpose: one paragraph on what the repo is and is not.
- Directory map: 10–20 bullet points mapping
apps/, packages/, infra/, tools/ to responsibilities.
- Package/dependency rules: allowed import directions (e.g.
packages/core → apps/*, never the other way).
- Entry points: where HTTP APIs, CLIs and queues start (
apps/api/src/main.ts, apps/worker/src/index.ts, etc.).
- Build/test commands: canonical commands per surface (
pnpm test:api, pnpm test:web).
- Ownership: directory-to-team mapping and approval rules.
- Non-goals / hazards: generated folders, vendor code, experimental areas, what not to touch.
Line budget: how big should AGENTS.md be?
The AGENTS.md knowledge base describes a practical upper bound of around 371 lines for a single file before maintenance and navigation break down (Codex KB article). Beyond that, agents and humans both struggle to extract the relevant rules.
That suggests a conservative design:
- Target 250–300 lines for the root file as a soft budget.
- Hard cap at 350–400 lines: if you exceed this, split into scoped instruction files.
In token terms, a 300-line Markdown file will typically be on the order of a few thousand tokens (for many English code-documentation mixes, roughly 1.8k–3k tokens), depending on the tokenizer and how dense each line is. On Claude models that are priced per million tokens in Anthropic’s list-pricing tables, that context size is non-trivial if reloaded on every request, especially once both input and output tokens for each call are considered.
Worked schema: TypeScript/Node monorepo
Assume a Turborepo/Nx-style structure:
apps/web – Next.js frontend
apps/api – REST/GraphQL backend
apps/worker – background jobs
packages/core – domain logic
packages/ui – shared components
packages/config – ESLint, TSConfig, Tailwind, etc.
infra/ – IaC, migrations, pipelines
tools/ – scripts, generators
A root AGENTS.md might be structured as:
- (≈20 lines) Purpose & constraints: what the product does, supported regions, main languages; explicit non-goals (e.g. no multi-tenancy refactors yet).
- (≈40 lines) Directory map: bulleted list explaining each root directory and its key subfolders.
- (≈60 lines) Dependency rules:
- One table or bullets listing allowed import directions (apps → packages, never apps → infra).
- Explicitly forbidden edges (apps must not import from each other, only via packages).
- (≈40 lines) Entry points & commands: start files and commands for web, api, worker, migrations, e2e tests.
- (≈40 lines) Ownership & approval: per-directory owners and required approvals for risky paths.
- (≈40 lines) Global editing rules: never edit
generated/, vendor/, lockfiles directly; how to regenerate; maximum change budget default (e.g. 10 files unless explicitly agreed).
- (≈30 lines) Validation rules: what tests to run for typical changes (API, web, shared package), plus a note that tests and CI gates are the source of truth.
Total: around 270 lines, leaving headroom for evolution before hitting the 350–400 line cap.
Deriving the map from real signals
To keep this maintainable, derive information from existing sources instead of inventing a new taxonomy:
- Architecture: read from Turborepo/Nx config and package manifests.
- Dependencies: use the workspace graph (e.g. Nx graph, Turborepo pipeline) or a RIG-like tool to list edges.
- Commands: copy from
package.json scripts, CI workflows and Makefiles.
- Ownership: reuse
CODEOWNERS, .github/ config or internal ownership files.
Repository Intelligence Graph work describes file-based layers representing components, runners, tests and dependencies (RIG paper). The root context map is a human-readable slice of that graph, optimised for agents.
What does not belong in the root map
To keep the file short and stable, avoid:
- Detailed API docs or business logic; keep that in code and separate docs.
- Step-by-step procedures for specific features (move those to scoped instructions near the code).
- Tool-specific prompts or examples that belong in per-task instructions.
- Security or compliance rules that must be enforced; those belong in code, checks and external systems, as noted in guidance on AGENTS.md-style files (Dev Fieldnotes guide).
Scoped instructions: from AGENTS.md to directory-level rules
Root context alone is not enough in a large repo. AGENTS.md and equivalents such as CLAUDE.md, Copilot configs and Cursor Project Rules give a hook for scoped instructions (DevAgentStack workflow guide).
Claude Code’s official CLAUDE.md guidance shows how project-level instruction files live alongside your codebase and drive agent behaviour, grounding the article’s discussion of root AGENTS.md and scoped instructions.
Cursor’s project rules documentation provides concrete evidence that modern coding tools support repo-scoped instructions, aligning with the guide’s recommendation to keep global contracts thin and push detail into scoped files.
How tools interpret scoped instructions
Products differ in how they merge global and local instructions. Context engineering work notes that some tools use nearest-directory precedence, others simply concatenate everything, and public API documentation generally describes a precedence ladder where system, developer and user messages outrank repo-embedded content (Context Wire article).
Implications:
- Do not rely on conflicts being resolved sensibly. Avoid drafting contradictory rules between root and subdirectories.
- Assume concatenation unless documented otherwise. Phrase local rules as refinements (“In addition to the root rules, when editing apps/web...”).
Design principle: global contract + local refinements
A workable pattern follows the best practices described for AGENTS.md and scoped files (Context Wire):
- Root file: global contract and repo map. No technology-specific minutiae beyond what all surfaces share.
- Scoped files: only where necessary, and only with rules that truly differ from the global contract.
- No duplication: if a rule applies across the repo, keep it only in root.
Example splits in a monorepo
Using the TypeScript/Node monorepo example:
AGENTS.md (root): as designed above.
apps/web/AGENTS.md:
- Next.js/React coding style and routing conventions.
- State management patterns (e.g. React Query, Redux Toolkit).
- Where to put feature modules (
app/(feature)/ etc.).
- How to extend design tokens from
packages/ui.
apps/api/AGENTS.md:
- HTTP/GraphQL API patterns, DTO and validation conventions.
- How to add a new endpoint (files to touch, tests to update).
- How to use
packages/core for domain logic.
packages/core/AGENTS.md:
- Domain modelling rules and invariants.
- Where to put new entities and aggregates.
- How not to leak infrastructure concerns.
infra/AGENTS.md:
- Safe changes in IaC vs what requires manual review.
- How to add a new environment variable.
- Prohibition on editing Terraform state or migration history directly.
generated/AGENTS.md (if applicable):
- Explicit instruction: never edit anything here; instead, adjust the source schema or config and run the generator.
Scoped instruction size guidance
Local files can be tighter because they sit closer to the code they govern. A reasonable pattern:
- Per-scope budget: 80–150 lines per
AGENTS.md in app/package directories.
- Content focus: specific procedures, patterns and pitfalls for that directory.
- Link back: short pointer to root rules (e.g. “Follow dependency and validation rules in /AGENTS.md in addition to the below.”).
If a scoped file grows beyond ~200 lines, split again by feature or sub-package and keep local files close to the leaf directories where agents will operate.
Screenshot: where the root file actually lives
Screenshot idea: repository root in a typical monorepo showing AGENTS.md, CLAUDE.md or similar alongside apps/, packages/, infra/, tools/. Caption: “Root-level AGENTS.md/CLAUDE.md sits next to top-level directories so all tools can discover it.”
Encoding dependency boundaries for coding agents
Context maps are only useful if they include the repo’s actual seams. Work on Repository Intelligence Graphs describes deterministic maps of modules, runners, tests and dependencies (RIG paper). For a monorepo, most of the safety comes from clearly encoding dependency directions and non-goals.
What dependency boundaries should include
From sources covering context maps and repo-sharing (Graphify):
- Allowed imports: package graph edges (apps → packages), libraries that may depend on others.
- Forbidden imports: layers that must not cross (apps ↔ infra, infra → apps, UI → database).
- Shared abstractions: the one true place for cross-cutting concepts (e.g. auth types in
packages/core).
How to expose boundaries to agents
- Root AGENTS.md:
- Include a short table listing modules and allowed dependents.
- Explicitly call out “do not” edges (e.g. “apps/* must not import from infra/**”).
- Scoped files:
- Reiterate any special cases (“In apps/web, all domain logic comes from packages/core; do not call data access directly.”).
- Static enforcement:
- Use lint rules or dependency-checking tools to enforce imports; context guidelines emphasise that instructions are not enforcement (Dev Fieldnotes guide).
Quantitative recipe: boundaries in a Node monorepo
For the TypeScript/Node example, a minimal dependency section might contain:
- 6–10 bullet points for major modules (apps, core, ui, infra, tools).
- Each bullet: 1 line allowed imports, 1 line forbidden imports.
- Total: ~20 lines in root
AGENTS.md, reused by all scoped instructions via reference.
This keeps the boundary rules within roughly a few hundred tokens, a small fraction of a typical agent session, but critical for preventing cross-layer mistakes.
Search strategies for coding agents in big codebases
Large-context agents can use filesystem tools to reason over big repos (long-context coding agents paper), but naive search is expensive. The aim is a deterministic pattern that limits exploration while still finding the right files.
Brute-force vs tool-native vs graph-backed search
- Brute-force search: “search the whole repo for X”. Simple but token-heavy and prone to spurious matches.
- Tool-native search: structured commands like “search in apps/web/src for <component>”, leaning on Cursor/Claude tools.
- Graph-backed search: use a Repository Intelligence Graph or persistent memory such as Kairo to narrow scope first, then open only the most relevant files (Kairo repository).
Layered search strategy for a monorepo
A practical algorithm the agent can be instructed to follow:
- Step 1: Read the map. Always start by summarising the relevant sections of
AGENTS.md and any scoped file in the directory of the current task.
- Step 2: Constrain by directory. Limit initial search to the directory families indicated by the map (e.g.
apps/web for frontend, apps/api for API, packages/core for shared domain).
- Step 3: Use tool-native search. Use the IDE’s search tools (Claude Code’s file search, Cursor’s workspace search) to find symbol names or routes within those directories first.
- Step 4: Expand via graph if needed. If local search fails, consult a RIG-like graph or persistent memory to see which modules actually call or depend on the concept (RIG, Kairo).
- Step 5: Only then broaden search. As a last resort, run a repo-wide search with a clear plan for ignoring noise (e.g. avoid
node_modules, generated).
Tool-specific hooks
- Claude Code: uses
CLAUDE.md (or similar) for repo rules (AGENTS.md standard) and exposes file search via its tools.
- Cursor: provides project-level rules and workspace context (DevAgentStack guide), and has built-in search operators.
- GitHub Copilot: relies more on inline suggestions and IDE search, but also supports repo-level configuration via settings.
- Gemini-based tools and similar APIs: follow documented system/developer/user message precedence and can be given explicit search procedures alongside any repo-level configuration they support.
Screenshot ideas for search and rules
- Cursor: project rules/settings panel showing repo-specific rules. Caption: “Cursor project rules hold the same root contract as AGENTS.md.”
- Claude Code: file tree view showing detection of
CLAUDE.md. Caption: “Claude Code reads CLAUDE.md to guide navigation before searching the repo.”
Validation workflows for agent changes
Context is guidance, not enforcement. Best-practice guides emphasise that critical rules must be encoded in code and checks (Dev Fieldnotes guide). Work on AGENTS.md and context maps recommends explicit phases: scope, context selection, bounded edits, validation (Codex KB article).
Four-phase validation loop
- Scope the change:
- Define the user story and maximum allowed files/lines to change.
- Communicate the budget in the initial prompt; root
AGENTS.md can define defaults (e.g. 10 files, 300 LOC).
- Select and constrain context:
- Ensure the agent reads only relevant parts of the map and scoped files.
- Instruct it not to edit outside the directories identified during search without explicit permission.
- Execute bounded edits:
- Prefer changes in small steps: implement, run tests, then expand if needed.
- For multi-step tasks, ensure the agent describes what it changed after each phase.
- Validate via tests and review:
- Run relevant unit/integration tests and linters based on the changed paths.
- Use ownership rules to route reviews; reviewers see diff plus test status, not full-repo context.
Context engineering work recommends deriving review context from the diff, tests and ownership map instead of dumping the entire repository (Agitech article).
CI/CD as the enforcement layer
- Static checks: enforce dependency rules (e.g. lint rules preventing forbidden imports), formatting, type safety.
- Tests: run fine-grained test suites (e.g. per-package scripts) for changed areas.
- Ownership: require approvals from relevant teams based on path-based ownership rules.
- Policy: any security or compliance requirement should be encoded in scripts or CI pipelines, not only in AGENTS.md-style files (Dev Fieldnotes guide).
Screenshot: diff and CI status
Screenshot idea: a GitHub pull request authored by a coding agent, showing a small, focused diff with green checks for tests and static checks, plus ownership review requested. Caption: “Diff, tests and ownership review form the final safety net for agent-authored changes.”
Quantitative recipe: context architecture for a large TS/Node monorepo
Bringing the elements together, here is a concrete, quantitative design for a 200k LOC TypeScript/Node monorepo.
1. Root context map
- Size: 250–300 lines.
- Sections and budgets:
- Purpose & non-goals: 20–30 lines.
- Directory/architecture map: 40–60 lines.
- Dependency rules: 20–30 lines.
- Entry points & commands: 30–40 lines.
- Ownership: 30–40 lines.
- Global editing constraints & validation: 40–60 lines.
- Update frequency: only when topology or global rules change, not for day-to-day feature work.
2. Scoped instructions
- Files: 4–8 key scoped files (e.g.
apps/web/AGENTS.md, apps/api/AGENTS.md, packages/core/AGENTS.md, infra/AGENTS.md, generated/AGENTS.md).
- Size per file: 80–150 lines.
- Total scoped footprint: for example, 6 files at 120 lines ≈ 720 lines, but only 1–2 of these are typically relevant for any given task.
3. Per-task prompts
- Size: 15–30 lines describing the task, constraints and success criteria.
- Tokens: typically a few hundred tokens.
- Content:
- User story or bug description.
- Explicit file/area focus (e.g. “only change apps/web/components/profile”).
- Change budget (files/LOC).
- Any test strategy beyond defaults (e.g. “run e2e tests too”).
4. Search and navigation budget
Assuming a task touches one surface (e.g. apps/web):
- Root + scoped instructions: on the order of a few thousand tokens combined.
- Task prompt: a few hundred tokens.
- Navigation (search commands and tool responses):
- If limited to 5–8 focused searches and 10–15 file opens, and each tool call averages 100–150 tokens, that is another roughly 1.5k–3k tokens.
- Total navigation + context per task: commonly in the mid–single-digit thousands of tokens.
Compared to a naive approach where a single 500–700 line AGENTS.md and broad searches might add thousands of tokens of unnecessary exploration each time, this layered design keeps the overhead bounded and relevant.
5. Expected impact on failure modes and cost
Using the cost scenarios from the decision brief and the overhead patterns described in work referenced by the AGENTS.md standard (AGENTS.md standard):
- Naive single AGENTS.md: a long, unstructured file plus broad exploration can materially increase token usage for coding tasks versus a minimal baseline, with limited improvement in success, because the agent still has to infer structure.
- Layered context: a compact root map plus one scoped file and constrained searches yields a predictable, task-focused context budget. This still adds overhead relative to a bare prompt, but with structured navigation the increase can be kept moderate while improving task completion.
- Persistent memory (Kairo/RIG-style): a one-time full scan of the repo builds an atlas, then each subsequent task uses a small continuation brief rather than rescanning large swathes of code (Kairo repository). Over time, per-task token usage can drop relative to approaches that repeatedly rediscover the same structure.
Qualitatively, this architecture also reduces failure modes:
- Boundary violations: explicit dependencies + lint rules + scoped instructions make forbidden imports less likely and easier to catch.
- Irrelevant edits: change budgets and directory-focused search limit how much unrelated code the agent touches.
- Review overload: diff- and test-driven review context keeps reviewers focused on what changed, not on re-understanding the whole repo.
When this architecture is not the right choice
The decision can flip based on repo size, fragmentation, validation maturity and cost constraints.
Small single-service repos (<20k LOC)
For a small, simple repo with one app and straightforward dependencies, the overhead of multi-level context maps and dependency graphs is often unnecessary. A concise single AGENTS.md or CLAUDE.md plus ad-hoc prompts and tool-native navigation is usually enough.
Teams without tests or CI discipline
If there are no automated tests, linting, ownership rules or reliable code review, giving agents richer context does not make them safe. Best practice is to keep agents in read-only exploration or suggestion modes until basic engineering hygiene is in place.
Highly fragmented polyrepo estates
In true polyrepo environments with many small, mostly independent services, encoding all cross-repo context into AGENTS.md-style files becomes brittle. A better choice is:
- Minimal per-repo context maps.
- An external RIG or persistent memory system (e.g. Kairo) to represent cross-repo relationships (RIG, Kairo).
Strict cost constraints
Recent work on LLM pricing describes how many API and product plans are effectively token-budget-based, with usage cost determined by the volume of input and output tokens consumed rather than a fixed request count (LLM pricing analysis). When costs must be tightly controlled, one of the best levers is to invest more up front in one-time scans and persistent memory so subsequent tasks can use very lean instructions.
Security- and policy-critical environments
For regulated industries, guidance on AGENTS.md emphasises that instruction files are soft context, not enforcement (Dev Fieldnotes guide). Any non-negotiable rule must live in code, static checks, CI/CD and external policy engines. In such environments, AGENTS.md and scoped instructions are advisory only; the real guarantees come from the validation pipeline.
How to choose between plain maps, layered instructions and RIG/persistent memory
The decision can be approximated by a simple tree:
- Step 1: LOC and structure
- If <20k LOC and single app → single
AGENTS.md + ad-hoc prompts.
- If 20–300k LOC monorepo → layered
AGENTS.md + scoped instructions (this article’s recipe).
- If >300k LOC or dozens of services → add RIG/persistent memory.
- Step 2: Validation maturity
- If tests + CI + ownership exist → agents can make changes with guardrails.
- If not → keep agents read-only, focus on navigation and diagnostics.
- Step 3: Cost sensitivity
- If cost is primary constraint → prioritise lean root instructions, strict search budgets and potentially a one-time RIG/persistent memory scan to amortise navigation.
What changes the decision
A few conditions justify a different approach than the full layered context architecture:
- Small, simple single-service repos: adopt a single, concise
AGENTS.md or CLAUDE.md and rely more on tool-native search and ad-hoc prompts.
- No enforceable validation: limit agents to exploration and suggestions until tests, linting and CI are in place.
- Highly fragmented polyrepo: switch to per-repo minimal maps plus an external RIG/persistent memory layer that encodes cross-service relationships.
- Strict cost caps: favour one-time repository scans, persistent memory and very lean root instructions over complex multi-level context that is reloaded often.
- Hard security/compliance needs: focus on encoding rules in code, static checks and CI/CD, and treat AGENTS.md-style context as guidance only.
For large TypeScript/Node monorepos with established CI and a goal of using Claude Code, Cursor, Copilot or comparable tools for meaningful changes, the layered, file-based context contract described here is a predictable way to make agents safer in production without letting costs drift. Combined with tool-specific practices from pieces like Claude Code as a terminal-first coding agent and a safe repository setup for Codex, you get an end-to-end stack where agents can ship real work instead of just impressive demos.