Cursor rules authoring

From repo layout, stack, and team conventions, draft or extend .cursor/rules to cut repeated session instructions; this page orders rollout and explains layering vs overrides.

The skill can guide agents to scan entry dirs, test layout, and existing policy files, then emit actionable rule chunks with priority and scope (e.g. only frontend/).

If the repo has no rules yet, start minimal: language version, formatting, commit messages, and forbidden patterns.

From scan to effect (skill-flow)

  [ Scan: root config, packages, tests, docs ]
              │
              ▼
       ┌──────────────→    Align: ESLint / Prettier / commit conventions
       →Capture       │──── “Configs are source of truth”—avoid contradicting tools
       →constraints   →
       └──────────────┘
              │
              ▼
       ┌──────────────→    Split by path or subproject; document globs
       →Draft rules   │──── Match layering: don’t repeat what higher layers state
       └──────────────┘
              │
              ▼
       ┌──────────────→    PR: describe blast radius; merge after review
       →Review & merge│──── In sessions, @-mention rules or paste snippets to verify
       └──────────────┘
              │
              ▼
         [ Humans / agents read by layer ]

Before merge, align rules with real directories, CI, and docs; avoid duplicating stale CLI prose—link README or script entrypoints instead.

Layering and precedence

Typical Cursor stacking: editor user rules →workspace (repo) rules →files under .cursor/rules (narrower globs win). Upper layers state global principles; lower layers add directory-specific exceptions; document resolution order and state that sub-rules add detail without overturning security/compliance baselines.

  ┌─────────────────────────────────────┐
  →User rules (personal, cross-project) → →habits and portable prefs
  └─────────────────────────────────────┘
              →narrower layers add detail
              ▼
  ┌─────────────────────────────────────┐
  →Project / AGENTS.md / team baseline  → →language, workflow, bans
  └─────────────────────────────────────┘
              │
              ▼
  ┌─────────────────────────────────────┐
  →.cursor/rules (+ globs narrow scope) → →package stacks, tests, dir norms
  └─────────────────────────────────────┘
              │
              ▼
         [ Current file context + session notes ]
  • Monorepos: root explains precedence and conflicts; subtree rules only state deltas.
  • With ESLint/Prettier: “machine checks follow config files; rules capture AI behavior and review focus.”

.cursor/rules directory structure and three trigger types:

# .cursor/rules/ directory structure example
.cursor/
  rules/
    project.mdc          # always — project baseline, active every session
    typescript.mdc       # auto_attached — *.ts / *.tsx files auto-attached
    react-components.mdc # auto_attached — src/components/**
    testing.mdc          # auto_attached — **/*.test.ts, **/*.spec.ts
    security-review.mdc  # agent_requested — only when @security-review is used

# Three trigger types explained
# always        — attached in every Agent session; use for global principles and bans
# auto_attached — auto-attached when globs match; use for file/directory conventions
# agent_requested — only attached when Agent needs it or user @-mentions; for specialist checks

# typescript.mdc full example
---
description: TypeScript project coding conventions
globs: ["**/*.ts", "**/*.tsx"]
alwaysApply: false
---

# TypeScript Conventions

## Tech stack
- TypeScript 5.x, strict mode enabled
- Package manager: pnpm, runtime: Node.js 20 LTS
- Testing: Vitest + Testing Library

## Code style
- Prefer `const` over `let`, ban `var`
- Function return types must be explicitly declared (unless obvious)
- Use `interface` for interfaces, `type` for composition/union types
- Async functions return `Promise<T>`, ban bare `any`

## Forbidden
- Ban `@ts-ignore` (use `@ts-expect-error` with comment instead)
- Ban `as any` (try type narrowing or generic constraints first)
- Ban direct `process.env` access (wrap through config module)

## Testing
- Each service/util file must have a corresponding .test.ts
- Mock external dependencies, no real network requests
- Test descriptions in plain English, explain business scenario

Deliverables and cross-links

  • Output should include directory patterns, stack, anti-patterns, and cross-references to code review guidance.
  • Change policy: substantive rule updates go through PRs with impact notes for existing sessions.
  • Specific: list concrete rules; avoid vague "follow best practices" descriptions.
  • Executable: rules can be directly followed by AI, with clear do/don't.
  • With examples: non-obvious rules include ✅ and ❌ code snippets.

React project and Python project rule template examples:

# react-components.mdc — React component conventions
---
description: React component development conventions
globs: ["src/components/**/*.tsx", "src/pages/**/*.tsx"]
alwaysApply: false
---

# React Component Conventions

## Component structure
- Use function components + hooks; ban class components
- Props interface naming: `${ComponentName}Props`
- Component file export: named export (ban default export for components)

## State management
- Local state with useState / useReducer
- Cross-component shared state with Zustand (ban Context for frequently updated state)
- Server state with TanStack Query (ban hand-written fetch in useEffect)

## Forbidden
- Ban defining event handlers inside render function (performance)
- Ban inline styles in JSX (use CSS modules or Tailwind)

✅ Correct:
const handleClick = useCallback(() => { ... }, [deps]);

❌ Wrong:
<button onClick={() => { ... }}>

# python-api.mdc — Python API conventions
---
description: Python FastAPI project conventions
globs: ["**/*.py"]
alwaysApply: false
---

# Python Project Conventions

## Tech stack
- Python 3.12+, FastAPI, SQLAlchemy 2.x, Pydantic v2
- Testing: pytest + httpx (async tests use pytest-asyncio)

## Code style
- Type annotations must be complete (parameters and return values)
- Use Pydantic models for input validation; ban manual if/else validation
- DB operations through Repository pattern; ban direct db.query in router

## Forbidden
- Ban `except Exception: pass` (must log or re-raise)
- Ban `Optional[X]` in Pydantic models (use `X | None` instead)

Monorepos and change policy

Split rule files per subproject and document precedence at the repo root. When ESLint/Prettier already exist, reference “follow config files—to avoid duplicated, drifting instructions.

SKILL bootstrap snippet

---
name: cursor-rules-bootstrap
description: Generate a .cursor/rules draft from repository layout
---
# Scanning steps
1. Read repo root: package.json / pyproject.toml / go.mod to identify tech stack
2. Check tsconfig.json / .eslintrc / Makefile to gather existing constraints
3. List src/ directory structure, identify components / services / api layers

# Rule file generation principles
- project.mdc: always, include stack versions, forbidden items, commit conventions
- {stack}.mdc: auto_attached, triggered by file globs
- Each rule block: specific & executable + ✅/❌ examples
- Machine checks defer to config files (ESLint/Prettier); rules only cover AI behavior

# Three alwaysApply types
- alwaysApply: true   → every session (global principles)
- alwaysApply: false + globs → auto-attached when file matches
- agent_requested     → on-demand @ attachment (specialist checks)

# High-quality rule elements
- Specific: list concrete do/don't items, not "follow best practices"
- Executable: Agent can directly follow; clear do/don't
- With examples: non-obvious rules include code snippets

# Monorepo strategy
- Root project.mdc: global baselines (security/compliance non-negotiable)
- Sub-package rules/*.mdc: only subtree deltas
- No duplication with ESLint/Prettier; reference "follow config file"

Back to skills More skills