Skip to main content

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.js or axios instead of native date-fns or fetch.
  • 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)    │
└─────────────────────────────────────────────────────────────┘
  1. Global Repository Rules (Core Repository Contract):
    • Located at the project root (CLAUDE.md for Claude Code, AGENTS.md or .cursorrules for editors).
    • Describe the critical minimum: environment versions (Node.js 22, Bun, Python 3.12), package manager (pnpm), mandatory linter, and commit structure instructions.
  2. Contextual Modular Rules (Scoped Domain Rules):
    • Files with metadata and glob patterns (e.g., .cursor/rules/database.mdc filtered for src/db/**/*.ts).
    • Loaded into the model's memory only when the agent plans to edit migration files or ORM models.
  3. Operational Guardrails:
    • Clear negative constraints: "NEVER execute git push --force", "NEVER modify .env.production", "DO NOT add new dependencies without explicit engineer consent".

3. Technical Pipeline & Internal Mechanics

The lifecycle of rules during a vibe coding session:

  1. 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.
  2. 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 for src/app/api/**/*.ts and stripe.mdc.
  3. 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.
  4. Code Generation with Enforced Invariants: The model forms a tool call or code, treating the rules as mandatory system context.
  5. 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.md mandates using pnpm, while an outdated README.md or local rule contains npm 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.
/ Frequently Asked QuestionsSchema.org FAQPage

FAQ: Agent Rules (.cursorrules / CLAUDE.md / AGENTS.md)

The monolithic file is loaded into the context of every request regardless of the task, consuming tokens. Modular MDC rules are activated dynamically only when the agent touches files matching a specified glob pattern (e.g., only for `src/components/**/*.tsx`).
/ Internal links
All terms