Agent Rules (.cursorrules / CLAUDE.md / AGENTS.md)
Machine-readable files of architectural regulations and constraints in the repository that are automatically mounted into the system context of AI agents to prevent codebase degradation.
1. Concept Overview & Systemic Problem
Modern LLMs are trained on gigabytes of open-source code from GitHub, leading them to generate "averaged" code by default: outdated major versions of libraries, chaotic import patterns, any in TypeScript, or inefficient error handling approaches. When an engineer operates within a vibe coding paradigm without fixed rules, each new prompt turns into a lottery:
- The agent installs outdated
moment.jsoraxiosinstead of nativedate-fnsorfetch. - The agent mixes architectural layers (e.g., directly accessing the database from a client-side React component).
- The agent invents its own compilation or testing commands instead of using existing project scripts.
Agent Rules (files .cursorrules, CLAUDE.md, AGENTS.md, .cursor/rules/*.mdc) address the issue of codebase drift. They transform the team's internal conventions into a system contract that is read by the development environment or terminal agent before any code generation begins.
2. Architectural Taxonomy & Mental Model
Repository rules are divided into three levels of isolation and activation:
┌─────────────────────────────────────────────────────────────┐
│ AGENT RULE LEVELS │
├─────────────────────────────────────────────────────────────┤
│ 1. Global / Machine Layer (~/.cursorrules, ~/.claude.json) │
│ Preferences of a specific developer (language, response style)│
├─────────────────────────────────────────────────────────────┤
│ 2. Repository Core Layer (CLAUDE.md, AGENTS.md, root rules) │
│ Global stack, forbidden libs, lint/test commands │
├─────────────────────────────────────────────────────────────┤
│ 3. Scoped / Event-Driven Rules (.cursor/rules/*.mdc) │
│ Activation via glob pattern (e.g., API routes, UI, DB) │
└─────────────────────────────────────────────────────────────┘
- Global Repository Rules (Core Repository Contract):
- Located at the project root (
CLAUDE.mdfor Claude Code,AGENTS.mdor.cursorrulesfor editors). - Describe the critical minimum: environment versions (Node.js 22, Bun, Python 3.12), package manager (
pnpm), mandatory linter, and commit structure instructions.
- Located at the project root (
- Contextual Modular Rules (Scoped Domain Rules):
- Files with metadata and glob patterns (e.g.,
.cursor/rules/database.mdcfiltered forsrc/db/**/*.ts). - Loaded into the model's memory only when the agent plans to edit migration files or ORM models.
- Files with metadata and glob patterns (e.g.,
- Operational Guardrails:
- Clear negative constraints: "NEVER execute
git push --force", "NEVER modify.env.production", "DO NOT add new dependencies without explicit engineer consent".
- Clear negative constraints: "NEVER execute
3. Technical Pipeline & Internal Mechanics
The lifecycle of rules during a vibe coding session:
- Session Initialization and Repository Scanning:
The IDE or CLI agent scans the root folder and the service directory
.cursor/rules/or.agents/rules/at startup. - Intent Analysis and Glob Matching:
The user submits a request ("Create a new endpoint for subscription payment"). The agent predicts file changes in
src/app/api/stripe/route.ts. The rules engine activates rules forsrc/app/api/**/*.tsandstripe.mdc. - Building the Extended System Prompt:
The engine concatenates:
- The base System Prompt of the model;
- The content of the global contract file;
- Found modular rules;
- The current tree of open files and the user's request.
- Code Generation with Enforced Invariants: The model forms a tool call or code, treating the rules as mandatory system context.
- Post-Generation Validation:
If the agent has terminal access, it runs a validation command specified in the rules (e.g.,
pnpm typecheck) before returning the final report to the engineer.
4. Production Engineering Scenarios
01. Architectural Boundaries in Next.js 15+ App Router
The file .cursor/rules/nextjs.mdc with the glob src/app/**/*.tsx prevents classic mistakes in using server and client components:
---
description: Architectural Standards for Next.js App Router
globs: src/app/**/*.tsx, src/components/**/*.tsx
---
- By default, all components are Server Components.
- Add the 'use client' directive ONLY when using useState, useEffect, or event handlers onClick/onChange.
- FORBIDDEN to import server utilities (db, auth secret) into files with 'use client'.
- All data mutations must be performed exclusively through Server Actions in the `src/actions/` directory.
02. Deterministic Test Execution for Claude Code
The configuration in CLAUDE.md ensures that the terminal agent uses only the correct testing scripts without attempting to run an incompatible global jest:
# Repository Guidelines for Claude Code
## Commands
- Build: `pnpm build`
- Typecheck: `pnpm tsc --noEmit`
- Unit Tests: `pnpm test:unit`
- E2E Tests: `pnpm test:e2e`
## Workflow Discipline
Before notifying about successful task completion:
1. Run `pnpm tsc --noEmit`. If there are type errors — fix them.
2. Run `pnpm test:unit` for modified modules.
3. Do not create new files without prior checking for existing utilities in `src/lib/`.
03. Enforced Type Safety and Zod Validation in API
The rule for the backend prevents the use of untyped JSON payloads in controllers:
---
description: Standardization of Backend Endpoints
globs: src/server/api/**/*.ts
---
- All incoming request arguments must be parsed through Zod schemas (`schema.parseAsync(req.body)`).
- The type `any` is strictly forbidden; when working with unknown data, use `unknown` followed by type narrowing.
- In case of business errors, throw a typed `TRPCError` or `HttpError` with a status code.
5. Pitfalls, Common Mistakes & Security
- Rule Bloat & Attention Saturation: Attempting to document the entire project in a rules file leads to files exceeding 500 lines. This overwhelms the model's attention ("Lost in the Middle") and causes it to ignore key directives. Break rules into modular scopes.
- Conflicting or Contradictory Rules: If the global
CLAUDE.mdmandates usingpnpm, while an outdatedREADME.mdor local rule containsnpm install, the model may get stuck in package manager hallucinations. - Risk of Sensitive Data Leakage: Never specify access tokens, test database passwords, or personal API keys in repository rules. All environment variables should be described only as abstract names (e.g.,
DATABASE_URL is required in .env.local). - Lack of Versioning: Agent rules must evolve alongside the codebase in the Git version control system. Changes in the tech stack should be accompanied by atomic updates to the corresponding rules files in the same commit.
FAQ: Agent Rules (.cursorrules / CLAUDE.md / AGENTS.md)
Related terms
System Prompt (System Instructions & Metaprompting)
The primary metacontext block of instructions passed at the zero position of the context window, defining the agent's role, safety rules, available tools, and behavioral boundaries.
Spec-Driven Development (SDD)
A leading software engineering methodology of the AI era, where the creation, alignment, and formalization of a structured machine-readable specification must precede code generation.
Cursor IDE
Leading AI-first development environment based on the VS Code core, integrating a multi-file generator Composer, predictive autocomplete Cursor Tab, and vector indexing of the codebase.
Claude Code
The official terminal agent from Anthropic, operating directly in the command line via Claude 3.7 Sonnet with native support for Bash, Git, file systems, and the MCP protocol.