Automating AGENTS.md Sync: How to Prevent Context Rot with PR Templates and Pre-commit Hooks
To be honest, I let this problem linger for quite a while. After introducing AI coding agents to the team and carefully crafting an AGENTS.md, I one day caught Claude Code casually generating code that imported from src/utils/legacy-api.ts — a file that had already been deleted. On closer inspection, the AGENTS.md was still describing a folder structure from before an architectural overhaul three months prior.
There's a name for this phenomenon: Context Rot — code changes every day, while AGENTS.md stubbornly clings to the reality at the time it was written. It may look like a simple documentation problem, but the more deeply AI agents are integrated into a team's workflow, a stale AGENTS.md becomes a bug factory that quietly churns out incorrect code. In practice, after putting a sync system in place, the number of PR review comments on AI-generated code dropped noticeably, and the time spent onboarding new team members also shortened considerably.
By the end of this post, you'll have a way to connect PR templates, pre-commit hooks, and the code review process organically — making AGENTS.md synchronization a natural part of your team's workflow. The first automation can be deployed to your team in 10 minutes.
Core Concepts
Why AGENTS.md Is Different from README.md
README.md is read by humans. So even if it's a bit outdated, humans use context to interpret it on their own. AGENTS.md, on the other hand, is read by AI agents. When starting a task, an agent automatically finds and reads the nearest AGENTS.md relative to the file being edited, and follows what's written there to the letter — without any judgment about whether the content might be outdated.
AGENTS.md is a Markdown file that conveys project context to AI coding agents such as Claude Code, OpenAI Codex, and GitHub Copilot. It contains build commands, code conventions, architectural constraints, forbidden patterns, and more, and is automatically read by agents as they traverse directories when starting a task. An open standardization movement is underway, with major AI coding tools like OpenAI Codex, Google Jules, and Cursor adopting the same format.
The Structural Reason Drift Occurs
Code changes happen every day, and PR reviews are busy. Missing an AGENTS.md update doesn't fail CI, and no one notices unless a colleague points it out. This is the root cause of drift.
[Typical drift occurrence pattern]
Week 1: AGENTS.md written — accurately reflects current architecture ✅
Week 4: Folder restructure PR merged — no AGENTS.md update ⚠️
Week 8: Package replaced (axios → fetch) — no AGENTS.md update ⚠️
Week 12: Agent generates import code with deleted paths 💥
Reviewer catches it, rework occursThe problem already started at Weeks 4 and 8, but the damage only becomes visible at Week 12.
Hierarchical AGENTS.md Structure — For Teams Using Monorepos
In a monorepo environment, there's a temptation to describe all domains with a single AGENTS.md at the root. Our team did this at first, but as the file grew longer, management became harder and token costs increased with every agent invocation. Because the agent reads the entire AGENTS.md as input each time it processes code, a longer file directly raises costs.
We eventually moved to the structure below, and management became much easier.
project/
├── AGENTS.md # Company-wide: commit format, security rules, CI commands
├── backend/
│ └── AGENTS.md # NestJS patterns, DB migration rules
├── frontend/
│ └── AGENTS.md # Next.js Server Component rules, Tailwind conventions
└── infra/
└── AGENTS.md # Terraform patterns, deployment proceduresWhen the root AGENTS.md starts exceeding 150–200 lines, it's time to consider splitting into subdirectories. Since agents prioritize the AGENTS.md closest to the file being edited, independent context management per team or domain becomes possible.
Practical Application
Example 1: Embedding a Checklist in PR Templates
Difficulty: Low | Automation level: Low | Initial setup time: 10 minutes
This is the lowest-cost way to get started. It adds a device to the PR template that naturally prompts team members to think about AGENTS.md whenever they open a PR. It might feel tedious at first, but after 2–3 weeks it becomes second nature.
<!-- .github/pull_request_template.md -->
## Changes
(What was changed and why)
## Testing
- [ ] Unit tests added/modified
- [ ] Integration tests verified
## AGENTS.md Sync Check
- [ ] Updated AGENTS.md if build/test commands changed
- [ ] Added to AGENTS.md if new patterns/conventions introduced
- [ ] Removed from AGENTS.md if deprecated patterns removed
- [ ] Not applicable (logic-only change)| Point | Description |
|---|---|
| Provide a "Not applicable" option | Forcing this on every PR creates checklist fatigue. It's important to allow an intentional pass. |
| Prioritize AGENTS.md changes | It helps to build a team culture where these are noted explicitly in the PR description. |
Keep the template version-controlled under .github/ |
Makes it possible to track who changed the checklist and when. |
Example 2: Auto-detection with a Pre-commit Hook
Difficulty: Medium | Automation level: High | Initial setup time: 30 minutes
PR templates rely on humans to check. If you need automation, a pre-commit hook is effective. The approach warns before committing if app code changed in a directory that has an AGENTS.md but the AGENTS.md was not updated alongside it.
First, save the script below as .githooks/check-agents-md.sh.
#!/bin/sh
# .githooks/check-agents-md.sh
#
# Soft-warning hook that checks whether AGENTS.md is in sync (exit 0 → commit allowed)
# Change the final exit 0 to exit 1 if a hard block is needed
changed_dirs=$(git diff --cached --name-only | while IFS= read -r file; do
dirname "$file"
done | sort -u)
for dir in $changed_dirs; do
if [ -f "$dir/AGENTS.md" ]; then
if ! git diff --cached --name-only | grep -qF "$dir/AGENTS.md"; then
echo ""
echo "⚠️ AGENTS.md sync check required"
echo " Code in $dir has changed, but $dir/AGENTS.md was not modified."
echo " Please verify that AGENTS.md is up to date, or"
echo " if no update is needed, run 'git add $dir/AGENTS.md' and recommit."
echo ""
fi
fi
done
exit 0To distribute this hook across the entire team, using it together with the pre-commit framework is recommended. pre-commit is an open-source tool that centrally manages scripts run before commits for all team members. Register it as a local hook in .pre-commit-config.yaml and a single pre-commit install deploys it to the whole team.
# .pre-commit-config.yaml
repos:
- repo: local
hooks:
- id: agents-md-sync-check
name: Check AGENTS.md sync
entry: .githooks/check-agents-md.sh
language: script
pass_filenames: false
always_run: trueAfter setup, each team member runs the following once.
pip install pre-commit
pre-commit installExample 3: Teams Using Multiple AI Tools — Maintaining a Single Source with Symlinks
Difficulty: Low | Automation level: Medium | Initial setup time: 15 minutes
If your team uses Claude Code, Cursor, and Codex in parallel, you probably don't want to manage CLAUDE.md, .cursorrules, and AGENTS.md separately. At first, the thought was "can't we just manage them separately?" — but if even one update is missed, each tool ends up following different rules. The symlink pattern resolves this cleanly.
From the project root directory, run the following.
# Set AGENTS.md as the single source and link the rest as symlinks
mv CLAUDE.md AGENTS.md
ln -s AGENTS.md CLAUDE.md
ln -s AGENTS.md GEMINI.md
git add AGENTS.md CLAUDE.md GEMINI.md
git commit -m "chore: consolidate into single-source AGENTS.md"Git tracks symlinks natively, so team members get the same structure on clone/pull. From then on, you only need to maintain the one AGENTS.md.
Note:
ln -screates links with relative paths based on the current directory, so this must be run from the project root. Running it from another path will result in broken links. On Windows, creating symlinks may require administrator privileges or a Git setting (core.symlinks=true).
Example 4: Using Code Review Comments as Signals for AGENTS.md Improvement
Difficulty: Low | Automation level: None | Impact: Greatest over the long term
This is the method I found most effective. At first, it wasn't obvious what code review comments had to do with improving AGENTS.md — but it turns out that recurring review comments are a precise signal pointing to rules not yet in AGENTS.md. If the same comment appears twice or more, that's a rule that needs to be added.
<!-- Example of what to add to AGENTS.md -->
## Forbidden Patterns
### Things we never do
- Do not import `axios` directly. Use the internal `src/lib/http-client.ts` wrapper.
```typescript
// ❌ Forbidden
import axios from 'axios';
// ✅ Recommended
import { httpClient } from '@/lib/http-client';- Do not use the
anytype. If the type is unknown, useunknownand then a type guard.
The HumanLayer team, who build AI agent workflow automation tools, analyzed hundreds of CLAUDE.md files and found that the best files were all ones iteratively improved over several weeks based on code review comments. Rather than trying to make it perfect in one go, the far more effective approach is to keep refining it as review comments accumulate.
Pros and Cons Analysis
Advantages
| Item | Description |
|---|---|
| Cross-tool consistency | A single AGENTS.md provides the same context to Claude Code, Codex, Cursor, and Copilot |
| Version-controllable | Git history lets you trace "when a rule was added, and why" |
| Accelerated onboarding | New team members can immediately use agents aligned with project standards |
| Improved review quality | The more context an agent has, the fewer review comments on AI-generated code |
| Knowledge documentation | Implicit team conventions become explicit, documented rules |
Disadvantages and Caveats
| Item | Description | Mitigation |
|---|---|---|
| Manual maintenance dependency | Without automation, drift risk is always present | Use pre-commit hooks + PR templates together |
| Context rot | The older the file, the more the agent is guided in the wrong direction | Schedule a Quarterly Audit on the calendar |
| Increased token costs | The agent reads the entire AGENTS.md as input each time it processes code, so costs rise with file length | Split into subdirectories beyond 150–200 lines |
| Requires team discipline | Technical solutions alone are insufficient | Must be paired with a cultural shift |
Context Rot: The phenomenon where the code is up to date but AGENTS.md describes a past state. The agent follows outdated guidance and generates code with incorrect import patterns, deprecated API usage, and code based on changed folder structures.
The Most Common Mistakes in Practice
-
Deferring with "let's update it later" — The moment an architecture overhaul PR is merged is the optimal time to update AGENTS.md. Miss that moment and the memory fades.
-
Writing duplicate content across multiple files — If the root AGENTS.md and subdirectory AGENTS.md contain the same content, drift will inevitably occur. Maintain the "one place only" principle and handle the rest via references.
-
Describing rules only in prose — One actual code example is more effective than three paragraphs describing a style. Showing the
// ❌ Forbiddenand// ✅ Recommendedpattern with real code communicates far more clearly — to agents and humans alike.
Closing Thoughts
AGENTS.md synchronization is, before being a technical problem, a problem of team workflow design. When an automated net is cast with pre-commit hooks and PR templates, and a continuous improvement cycle is maintained through code review comments — only then do agents begin to function as true teammates.
Three steps you can start right now:
-
Update the PR template today — Open
.github/pull_request_template.mdand try adding three "AGENTS.md sync check" checklist items. Ten minutes is all it takes. -
Register the pre-commit hook this week — Save the example script above as
.githooks/check-agents-md.sh, configure it withgit config core.hooksPath .githooks, or share it with the whole team via the pre-commit framework. -
Do a 5-minute check at the next sprint retrospective — The team lead or scrum master can add a single question to the agenda: "Among the AI code review comments from the past two weeks, are there any rules to add to AGENTS.md?" The accumulation becomes visible quickly.
If your team manages AGENTS.md in a different way, it would be great if you could share it in the comments. If there's a better approach, I'd love to learn from it too.
Next post: The grammar of good AGENTS.md rules — a practical context engineering guide for precisely controlling agent behavior using the "always do / ask first / never do" format
References
- AGENTS.md Official Site | agentsmd.io
- How to write a great agents.md: Lessons from over 2,500 repositories | GitHub Blog
- Custom instructions with AGENTS.md | OpenAI Codex Official Docs
- How to Build Your AGENTS.md (2026) | Augment Code
- Keep your AGENTS.md in sync — One Source of Truth | Kaushik Gopal
- A good AGENTS.md is a model upgrade | Augment Code Blog
- Writing a good CLAUDE.md | HumanLayer Blog
- Context engineering best practices for AI-powered dev teams | Packmind
- Beyond Prompts: How Git Hooks Steer AI Coding Agents in Production | DEV Community
- AI Coding Tip 014 - Use Nested AGENTS.md Files | DEV Community
- Do you symlink your AGENTS.md and skills to .claude? | SSW Rules
- Quality Gates in the Age of Agentic Coding | Helio