Nested Agent Instruction Files in a Monorepo: Nearest One Wins

How to scope AGENTS.md and path-specific Copilot instruction files per package so coding agents read the rules closest to the code they are editing.

Connectory team|13 min

It starts with a pull request that looks fine. An agent was asked to add a retry to an outbound call in services/billing, and it did, except it also swapped the HTTP client back to the one your platform team banned after a connection-pool incident. The reasoning for that ban lives in a closed pull request comment and a Slack thread from a team that has since reorganized. The agent had no way to know, so it re-litigated a decision that was already settled.

The fix in a monorepo is scoping, not volume. Put an instruction file inside each package so the file nearest the code being edited governs that path, keep the repository root for invariants that genuinely apply everywhere, and link each rule to the Architecture Decision Record that explains why it exists. The AGENTS.md convention defines exactly this kind of agent-readable Markdown file for build, test, and convention guidance, and describes nested files where the one closest to the edited code takes precedence [1]. GitHub documents repository custom instructions that Copilot applies automatically to requests scoped to the repository, including path-specific instruction files matched by glob [2].

This article covers how to lay out those files across packages, how to rewrite prose rationale into rules an agent will follow, how to put the files under code owner review so they cannot be quietly rewritten, and how to verify a rule actually changed agent output instead of just making you feel organized.

The Decision Agents Keep Re-Litigating

Chat threads and pull request history are not surfaces agents read reliably. They are surfaces humans remember reading. When the people who remember leave or move teams, the constraint stops existing in any form an agent can act on, and the next agent-authored change reintroduces the rejected pattern with confident commit messages.

Version-controlled files behave differently. They travel with the code, they show up in diffs, and they get reviewed. That is the practical case for writing conventions into the repository: the AGENTS.md convention covers build commands, directory conventions, and the invariants agents should not change [1], and Copilot's repository custom instructions apply repository context to requests without a human re-typing it every prompt [2].

The monorepo failure mode is specific, though. Teams discover instruction files, write one at the root, and then watch it grow. Eventually the root file is a sprawling prompt that nobody owns, parts of it contradict each other, and every request about the Python data pipeline pays the context cost of TypeScript lint rules. We have written before about the organizational context gap in coding assistants; a bloated root file is what happens when a team tries to close that gap with one file.

Why One Root Instruction File Breaks in a Monorepo

Unrelated constraints dilute the rules that matter. An agent editing packages/web-ui does not need your migration-ordering policy, and including it crowds out the three rules that actually govern that directory. Context budget is finite, and relevance decays as you add scope.

Package conventions genuinely conflict. Your Python data service uses structured logging with a correlation ID injected by a decorator. Your TypeScript web app logs through a thin wrapper that strips PII before it leaves the browser. Written as one global rule, either both are wrong or one is silently ignored.

Ownership collapses when everyone edits the same file. A file touched by nine teams is reviewed carefully by none. The CODEOWNERS entry, if it exists at all, points at a platform group that cannot judge whether a rule about payment idempotency is still correct.

Drift becomes invisible. A change made to help one package silently changes agent behavior in a dozen others, and nothing in the pull request diff tells you that.

The scoping principle that resolves all four: the file nearest the working path wins, and the root holds only org-wide invariants that no package is allowed to override.

Scoping Rules So the Nearest File Governs

Use three tiers. The root file carries invariants. Package-level files carry stack and convention rules. Path-specific instruction files, matched by glob, carry narrow rules for high-risk directories such as auth, payments, and migrations.

ScopeFile locationWhat belongs hereWhat must never go hereOwner
Organization invariants/AGENTS.mdSecret handling, licence policy, branch and commit rules, "never edit generated code"Any language-specific style rule, any single team's dependency preferencePlatform or architecture group
Service or package/services/billing/AGENTS.mdApproved HTTP client, error-handling pattern, logging shape, test command, module boundariesRules for sibling packages, duplicated root invariantsService owning team
Shared library/packages/ui-kit/AGENTS.mdPublic API stability rules, breaking-change process, accessibility requirementsConsumer-specific layout opinionsLibrary maintainers
High-risk path.github/instructions/migrations.instructions.mdMigration ordering, backfill pattern, required owner approval noteGeneral coding style, anything that applies outside the globNamed owner from CODEOWNERS

Two practices make this hold up. First, state the precedence rule inside each file, in one line, so an agent reading only that file knows it is not the whole picture: "Rules in this file apply to services/billing/** and override the repository root file. Root invariants in /AGENTS.md still apply." Second, keep package files short enough that a reviewer reads the entire file during a pull request. If it does not fit on one screen, the rules at the bottom are decoration.

Where globs overlap, write the precedence down. Path-specific Copilot instruction files apply by applyTo glob [2], and two globs matching the same directory is a question your team should answer in a comment rather than discover through inconsistent agent output.

Turning Prose Rationale Into Imperative Rules

Instruction files are directives, not essays. Agents follow verbs. Narrative background about a past incident gives an agent something to summarize, not something to obey.

The conversion is mechanical: extract the constraint, write it as MUST or MUST NOT, and link the reasoning.

Original proseImperative ruleWhere the reasoning livesFailure it prevents
"We moved off the old HTTP client after pool exhaustion issues"MUST use internal/httpclient for all outbound calls. MUST NOT import requests directly.docs/adr/0042-http-client.mdReintroducing the banned client under load
"The domain layer should ideally not know about persistence"MUST NOT import from ./repo inside ./domain.docs/adr/0017-module-boundaries.mdCircular dependencies and untestable domain logic
"Migrations have bitten us when they were not backwards compatible"MUST ship schema changes as expand, backfill, contract, in separate pull requests.docs/adr/0031-migrations.mdDeploy-order coupling and failed rollbacks
"Logging is a bit inconsistent across the service"MUST emit logs via log.with_context(). MUST NOT call print or bare logger.info.docs/adr/0023-logging.mdUnqueryable logs during incidents
"Try to avoid adding new dependencies without talking to us"MUST open an ADR before adding a direct dependency to pyproject.toml.docs/adr/0008-dependency-policy.mdSilent licence and supply-chain surface growth

Here is the before and after in file form.

text
# Before: services/billing/AGENTS.md (prose)

Historically this service used the requests library, but during the
load event last year we saw connection pool exhaustion and had to roll
back. The platform team then built an internal client with sane pooling
and timeout defaults, and we would generally prefer new code uses that.
Logging has also been inconsistent, so please try to be consistent.
text
# After: services/billing/AGENTS.md (directives)

Scope: services/billing/**. Overrides /AGENTS.md. Root invariants still apply.

1. MUST use internal/httpclient for outbound HTTP.
   MUST NOT import `requests` directly. See docs/adr/0042-http-client.md
2. MUST emit logs via log.with_context(correlation_id=...).
   MUST NOT call print() or logger.info() directly. See docs/adr/0023-logging.md
3. MUST NOT import services/billing/repo from services/billing/domain.
   See docs/adr/0017-module-boundaries.md

Keep the long-form reasoning in Architecture Decision Records, which capture context, decision, and consequences, and retain superseded decisions so rejected options stay visible instead of being deleted [3]. That last property matters more than people expect: an agent proposing the banned client is behaving reasonably if nothing in the repository records that the option was considered and rejected. Our piece on making architecture decisions reviewable as agent constraints goes further into that linkage.

Link out rather than duplicate. Rationale copied into two files guarantees that one of them becomes wrong.

Instruction Files Belong Under Code Owner Review

A convention file that any feature branch can rewrite is not a convention. It is a suggestion with extra steps.

CODEOWNERS automatically requests the named owner for review on matching paths [4]. On its own that is advisory. Paired with a repository or organization ruleset that requires pull requests and review before merge, owner approval becomes blocking rather than polite [5]. Add explicit entries for every instruction file path, per package, with the team that actually owns the decision.

text
# .github/CODEOWNERS

/AGENTS.md                                   @org/architecture
/docs/adr/                                   @org/architecture

/services/billing/AGENTS.md                  @org/billing-team @org/architecture
/services/data-pipeline/AGENTS.md            @org/data-platform
/packages/ui-kit/AGENTS.md                   @org/design-systems

/.github/instructions/                       @org/architecture
/.github/instructions/migrations.*           @org/dba @org/architecture

Two review rules are worth making explicit in your contributing guide. A pull request that changes an enforced pattern must update the ADR and the instruction file in the same commit, so code and recorded decision cannot separate. And a pull request that changes an instruction file must say, in the description, which agent behavior it is intended to change.

Give each agent its own identity with least-privilege permissions. GitHub's organization audit log records actions taken by members [6], which only helps if agent commits and merges are attributable rather than blended into a shared service account. If you are mapping this to merge enforcement more broadly, risk-weighted merge gates covers how to scale gate strictness to blast radius.

Verify the Change Actually Changed the Output

The most common mistake with instruction files is writing a rule, feeling organized, and never checking whether an agent behaves differently. Instructions are code that runs inside a model's context. Untested code.

Build a small verification loop per package. Pick a representative task, run it against an agent before the instruction change, run the same task after, and compare the two diffs. If the output is identical, your rule did nothing: either it was already implicit in the codebase, or it is being outranked by a nearer file, or it is phrased as narrative the model treated as background.

Scope boundary
Record which directories each instruction file governs and which root invariants still apply [1]
Representative task
Keep one fixture task per package, such as add an endpoint, add a migration, add an outbound client call
Evidence record
Store the before and after agent diffs alongside the instruction pull request
Revisit cadence
Re-run fixture tasks when you change models, agents, or the instruction file itself

Keep the fixture set small and boring. A handful of tasks per package is enough to catch the common regressions: a new route that should use the approved error handler, a schema change that should follow expand-backfill-contract, and a call that should route through the internal HTTP client.

Tune from observed noise. GitHub documents Copilot code review as a feature that reviews pull requests and leaves comments and suggested changes [7]; if reviewers routinely dismiss a category of comment, the instruction producing it is costing attention without buying safety. Delete it. Add rules for defects that actually reached main.

An Unreviewed Instruction File Is an Injection Path
Every agent run on a path reads the instruction file nearest that path. A pull request from a fork that adds services/payments/AGENTS.md is therefore proposing a change to the prompt of every future agent run in that directory. Require code owner approval on instruction file paths, and scope agent tokens so a successful injection cannot push to protected branches or edit workflow files.

Treat Instruction Files as Untrusted-Context Surface

Anything an agent reads is prompt input. That includes issues, pull request comments, dependency metadata, fetched pages, and the instruction files themselves. The OWASP Top 10 for Large Language Model Applications catalogues prompt injection and insecure output handling among the failure modes that apply directly to agents reading repository content [8].

On the process side, NIST SP 800-218A extends the Secure Software Development Framework with a community profile of secure development practices for generative AI and dual-use foundation models [9], and SP 800-218 defines the baseline practice groups that profile builds on [10]. The useful framing for a security review: instruction files are configuration that influences automated code generation, so they belong under the same change control as any other build-affecting configuration.

Practical controls, in order of payoff: require owner approval on instruction file paths, scope agent credentials narrowly so injection cannot reach protected branches or workflows, and keep agent-authored changes inside the same scanning, dependency review, and test gates as human changes rather than creating a fast lane.

Auditing Instruction Coverage Directory by Directory

Coverage is a per-directory property, not a repository checkbox. "We have AGENTS.md" is not an answer in a monorepo with dozens of packages. List your top-level packages and mark each one.

DirectoryInstruction fileADR linkedCode ownerNext action
services/billingYesYes@billing-teamRe-run fixture tasks after model upgrade
services/data-pipelineYesNo@data-platformAdd ADR links to the dependency rules
packages/ui-kitNon/a@design-systemsWrite file: highest agent PR volume in repo
infra/terraformYesYesunsetAdd CODEOWNERS entry, owner approval not blocking
services/legacy-reportsYesYes@archiveReconcile: contradicts root logging invariant

Watch for the inverse risk in that last row. A package file that contradicts the root file and has never been reconciled is worse than no file, because it teaches agents that root invariants are negotiable.

This is where a decision graph beats a pile of Markdown. Connectory's institutional memory layer holds policies, decisions, ownership, and constraints as typed records, so the rationale your instruction files link to is queryable rather than scattered across directories, and you can answer "which packages still reference the superseded HTTP client decision" without grepping. Guardian handles the enforcement half, keeping instruction file and ADR changes behind owner approval with a recorded exception trail.

Frequently Asked Questions

Does a nested AGENTS.md replace the root file or merge with it?

The convention describes the file closest to the edited code taking precedence [1]. Treat that as override for conflicting rules, not as a replacement for the whole root file, and write one line in each nested file stating which root invariants still apply.

Should I use AGENTS.md or GitHub's custom instructions files?

Use both if you use multiple agents. AGENTS.md is the open convention read by coding agents [1]; GitHub's repository and path-specific custom instructions are what Copilot applies to requests scoped to the repository [2]. Keep one canonical source per package and have the other reference it so you are not maintaining two divergent rule sets.

How long should a package instruction file be?

Short enough that a reviewer reads all of it during a pull request. If a rule cannot earn its place against that constraint, it belongs in an ADR, not an instruction file.

What goes in the root file in a monorepo?

Only invariants that no package may override: secret handling, licence policy, commit and branch rules, and a map pointing agents to the package-level files.

How do I know a rule is working?

Run a representative task before and after the change and compare diffs. A rule with no observable effect on agent output is noise.

What to Do Next

Pick the package that produces the most agent-authored pull requests. Not the most important package, the busiest one. Write its AGENTS.md with a short list of imperative rules, each linked to an ADR, with the precedence line at the top. Add a CODEOWNERS entry for that file path. That is an afternoon of work, and most of it is deciding which rules are real.

Then run your fixture task twice, once before the file existed and once after, and read both diffs side by side. That comparison is the only evidence that the file does anything.

The signal to start tracking this week: agent pull requests that reintroduce a pattern your team already rejected. Count them per package. That count tells you where the nearest instruction file is missing, and the billing service that quietly swapped its HTTP client back is usually first on the list.

References

[1] AGENTS.md, "AGENTS.md: an open format for guiding coding agents," 2025. https://agents.md/

[2] GitHub Docs, "Adding repository custom instructions for GitHub Copilot," 2025. https://docs.github.com/en/copilot/customizing-copilot/adding-repository-custom-instructions-for-github-copilot

[3] Architecture Decision Records, "ADR: Architecture Decision Records," 2025. https://adr.github.io/

[4] GitHub Docs, "About code owners," 2025. https://docs.github.com/en/repositories/managing-your-repositorys-settings-and-features/customizing-your-repository/about-code-owners

[5] GitHub Docs, "About rulesets," 2025. https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/managing-rulesets/about-rulesets

[6] GitHub Docs, "Reviewing the audit log for your organization," 2025. https://docs.github.com/en/organizations/keeping-your-organization-secure/reviewing-audit-logs-for-your-organization/reviewing-the-audit-log-for-your-organization

[7] GitHub Docs, "Using GitHub Copilot code review," 2025. https://docs.github.com/en/copilot/using-github-copilot/code-review/using-copilot-code-review

[8] OWASP, "OWASP Top 10 for Large Language Model Applications," 2025. https://owasp.org/www-project-top-10-for-large-language-model-applications/

[9] NIST, "SP 800-218A: Secure Software Development Practices for Generative AI and Dual-Use Foundation Models," 2024. https://csrc.nist.gov/pubs/sp/800/218/a/final

[10] NIST, "SP 800-218: Secure Software Development Framework (SSDF)," 2022. https://csrc.nist.gov/pubs/sp/800/218/final