Project Rules Files: Steering Code Assistants with Repository Rules
Prerequisites: Writing Effective Engineering Prompts.
Key Takeaway: If you find yourself typing the same instructions into your AI assistant every morning ("Use Next.js 15 App Router, do not use Axios, use Tailwind instead of CSS Modules"), you are suffering from un-codified context. Project rules files (.cursorrules,AGENTS.md) act as persistent, version-controlled system prompts that steer AI behavior across your entire engineering team.
The Problem of Generic Training Drift
Large Language Models are pre-trained on billions of lines of public GitHub code. By volume, the vast majority of that training data consists of legacy patterns:
- React 16/17 class components with
componentDidMount. - Old Next.js Pages Router patterns (
getServerSideProps). - Deprecated libraries (Axios, Moment.js, Redux thunks).
When an AI assistant works on your modern codebase, its statistical priors pull it toward these generic legacy patterns. Project rules files counteract this drift by injecting localized, authoritative ground truth into the agent's context window on every turn.
graph TD
Agent["AI Coding Assistant"] --> Read["Reads Workspace Root on Every Interaction"]
Read --> Rules["Project Rules Files: AGENTS.md / .cursorrules"]
subgraph "Injected Ground Truth"
R1["Current Tech Stack: Next.js 15 App Router, React 19, Tailwind v4"]
R2["Banned Libraries: Axios (use fetch), Moment (use date-fns)"]
R3["Folder Conventions: Components in src/components, Actions in src/app/actions"]
R4["Quality Standards: Strict TypeScript, Zero any, Zod schemas required"]
end
Rules --> R1 & R2 & R3 & R4
R1 & R2 & R3 & R4 --> CodeGen["Code Output: Perfectly Aligned with Your Architecture"]Anatomy of an Industry-Standard Rules File (AGENTS.md)
A production rules file must be concise, structured, and focused. Overloading it with 2,000 lines of prose exhausts the model's context window and leads to instruction forgetting. The ideal rules file is under 300 lines.
<!-- AGENTS.md / .cursorrules -->
# Repository Engineering Rules & Architecture Standards
## 1. Core Technology Stack
- Framework: Next.js 15 (App Router only; Pages Router is deprecated).
- React: React 19 (Server Components by default; add 'use client' only when state/effects are required).
- Language: TypeScript 5.5+ (Strict mode; NEVER use 'any'; use 'unknown' with type narrowing).
- Styling: Tailwind CSS (Utility classes; do not write custom .css files or CSS Modules).
- Validation: Zod 3.x (All API route inputs and Server Action payloads must be parsed via Zod).
## 2. Banned Libraries & Patterns
- BANNED: `axios` -> Use native `fetch()` with custom Error wrappers.
- BANNED: `moment.js` -> Use native `Intl` or `date-fns`.
- BANNED: `lodash` -> Use modern ES2024 array/object methods.
- BANNED: `dangerouslySetInnerHTML` -> Use Markdown AST with `rehype-sanitize`.
## 3. Directory Conventions
- `src/app/` -> Route Handlers, Pages, Layouts, and Server Actions.
- `src/components/ui/` -> Reusable, stateless design system primitives.
- `src/lib/` -> Pure business logic, third-party clients, database connectors.
- `src/types/` -> Shared TypeScript interface definitions.
## 4. Error Handling Standard
All Server Actions must return a typed Result union:
```typescript
export type ActionResult<T> =
| { success: true; data: T }
| { success: false; error: string; code: string };Never let uncaught server exceptions bubble to the client unformatted.
5. Testing Invariants
- Test runner: Vitest + React Testing Library.
- When creating new features, author the corresponding
.test.tsfile in the same directory. - Avoid tautological mocks; assert observable user behavior and business logic invariants.
---
### Monorepo Rules Hierarchy
In a large monorepo (e.g. Turbo, Nx), different packages have radically different requirements: a backend Node service requires different rules than a React frontend or a React Native mobile client.
Modern AI tools support **Hierarchical Rules Inheritance**:
```mermaid
graph TD
Root["Root: AGENTS.md\n(Global git rules, TypeScript strictness, commit formatting)"]
Root --> AppWeb["apps/web/AGENTS.md\n(Next.js 15, React 19, Tailwind)"]
Root --> AppMobile["apps/mobile/AGENTS.md\n(React Native, Expo, NativeWind)"]
Root --> PkgCore["packages/core/AGENTS.md\n(Pure TypeScript, zero DOM dependencies)"]The AI assistant automatically merges root rules with the nearest package-level rules file, ensuring contextually accurate code generation wherever your cursor is active.
Token Budgeting: Preventing Context Window Bloat
A common mistake is treating rules files like full employee handbooks. If your rules file consumes 4,000 tokens, every single prompt you send wastes 4,000 tokens of the context window.
Golden Rules of Rules File Conciseness:
- Bullet Points, Not Essays: Use short, imperative directives ("Use Zod for input validation" vs "It is our company philosophy that runtime validation is very important...").
- Negative Constraints First: Models follow negative constraints ("Do NOT use X") far more reliably than positive suggestions ("Consider using Y").
- Reference Canonical Files: Instead of embedding 50 lines of boilerplate, point the model to a real file: "For Server Action structure, mirror
src/app/actions/billing.ts."
Common Pitfalls & Anti-Patterns
- Letting Rules Files Go Stale: If you migrate from Next.js 14 to 15, but leave Next.js 14 rules in
.cursorrules, the AI will actively fight your codebase on every turn. Update rules files in the same PR that updates package dependencies. - Conflicting Rules: Having one rule stating "Use client-side fetch" and another stating "Use Server Components for all data" confuses the model, resulting in bizarre hybrid code.
- Committing Secrets in Rules Files: Never put private API keys, staging database URLs, or internal IP addresses in rules files. Rules files are committed to version control.
Senior Engineer Interview Angle
Staff Engineer Question: "How do you onboard 30 engineers to an AI coding tool like Cursor or Antigravity without ending up with 30 different coding styles and fragmented architecture?"
Exemplary Answer:
*"We establish Rules as Code (RaC):
- Version-Controlled Ground Truth: We author a comprehensive
AGENTS.mdand.cursorrulesfile at the root of our monorepo. It explicitly declares our framework versions, folder layout, error handling conventions, and banned libraries.- Automated Pre-Commit Lints: We configure automated linters (ESLint, Biome) that enforce the exact same rules codified in the AI rules file. If an AI generates banned code, pre-commit hooks reject the commit.
- Living Documentation: When architectural RFCs are approved, updating
AGENTS.mdis a required checklist item in the migration pull request.
This ensures that all 30 engineers—and their AI assistants—operate from a unified architectural playbook."*
Quick Self-Check
- Why do AI models naturally drift toward legacy coding patterns without rules files?
- What is the recommended maximum line count for an effective project rules file?
- How does hierarchical rules inheritance work in a monorepo?