Skip to main content

빈 파일에서 시작하지 않기

규칙 파일은 멋진 선언문이 아니라, 에이전트가 매번 참고하는 작업 지시서다. 사람이 새 프로젝트에 합류하면 먼저 README, 폴더 구조, 테스트 명령어, 배포 절차를 읽는다. Cursor의 에이전트도 마찬가지다. 다만 사람과 다른 점이 있다. 에이전트는 매 대화마다 기억이 초기화되므로, 프로젝트의 반복되는 약속을 규칙으로 넣어 두지 않으면 같은 설명을 계속 반복해야 한다.

이 부록의 목표는 단순하다. .cursor/rules/ 폴더를 만들고, 필요한 .mdc 파일을 복사한 다음, TODO로 표시된 부분만 자신의 프로젝트에 맞게 고치면 된다. 예전에는 루트의 단일 .cursorrules 파일에 모든 내용을 넣는 방식이 흔했지만, 지금은 .cursor/rules/*.mdc를 기본으로 삼는 편이 좋다. Cursor의 Project Rules는 저장소 안에 함께 버전 관리할 수 있고, .mdc 파일의 frontmatter를 통해 언제 규칙을 적용할지 조절할 수 있다.1

핵심은 모든 규칙을 항상 읽히게 하지 않는 것이다. alwaysApply: true는 언어와 프레임워크를 가리지 않고 반드시 지켜야 하는 최소 원칙에만 사용한다. React 컴포넌트 규칙, API 라우트 규칙, SQL 마이그레이션 규칙처럼 특정 파일에서만 필요한 지침은 globs로 범위를 좁힌다. 이렇게 해야 에이전트가 불필요한 규칙에 휘둘리지 않고, 컨텍스트도 아낄 수 있다. .mdc 형식은 description, globs, alwaysApply 같은 메타데이터를 앞부분에 두고, 그 아래에 마크다운으로 규칙을 쓰는 구조다.2

자주 쓰는 .cursor/rules/ 템플릿 모음

추천 폴더 구조

처음에는 아래 정도면 충분하다. 모든 템플릿을 한 번에 넣을 필요는 없다. 자신의 프로젝트에 해당하는 것만 고르고, 나머지는 나중에 필요할 때 추가한다.

.cursor/
└── rules/
    ├── 00-core.mdc
    ├── 01-code-style.mdc
    ├── 02-security.mdc
    ├── 03-testing.mdc
    ├── 04-git-pr.mdc
    ├── 05-docs.mdc
    ├── 10-nextjs-react.mdc
    ├── 11-react-spa.mdc
    ├── 20-node-api.mdc
    ├── 30-python.mdc
    └── 40-database-sql.mdc

번호는 필수가 아니다. 다만 사람이 읽기 쉽게 하기 위한 장치다. 00-core.mdc처럼 항상 적용되는 최소 규칙을 앞에 두고, 10-, 20-, 30-처럼 스택별 규칙을 뒤에 두면 관리하기 쉽다.

중요한 점은 성격이 다른 지침을 한 파일에 몰아넣지 않는 것이다. 코드 스타일, 테스트, 보안, Git, 문서화, 프레임워크 규칙은 서로 다른 순간에 필요하다. 모든 내용을 하나의 긴 규칙 파일로 합치면 에이전트는 매번 불필요한 문서를 읽어야 하고, 서로 충돌하는 지침도 늘어난다. Cursor 팀의 에이전트 작업 가이드에서도 규칙은 필수 요소에 집중하고, 전체 스타일 가이드를 복사하기보다 대표 파일을 참조하라고 권한다.3

템플릿 1: 모든 프로젝트에 넣는 최소 규칙

파일명: .cursor/rules/00-core.mdc

이 파일은 거의 모든 프로젝트에 넣어도 된다. 다만 너무 많은 내용을 담지 않는다. alwaysApply: true는 귀한 자리다. 여기에 프레임워크 취향까지 넣기 시작하면 금방 무거워진다.

---
description: Universal working rules for this repository
alwaysApply: true
---

## Core working rules

- Inspect existing code patterns before creating or changing files.
- Prefer small, focused changes over broad rewrites.
- If requirements are ambiguous, ask one clarifying question before implementation.
- Do not introduce new libraries without explaining why they are needed.
- Do not modify generated files, lockfiles, or migrations unless the task explicitly requires it.
- Never hardcode secrets, tokens, API keys, private URLs, or production credentials.
- Keep user-facing behavior stable unless the requested change requires otherwise.

## Project commands

<!-- TODO: Replace these commands with the real commands for this repository. -->

- Install dependencies: `pnpm install`
- Run development server: `pnpm dev`
- Type check: `pnpm typecheck`
- Run tests: `pnpm test`
- Run lint: `pnpm lint`
- Build: `pnpm build`

## Before finishing a task

- Summarize changed files and why they changed.
- Mention commands that were run and their results.
- If verification was not possible, explain the exact reason.

여기서 가장 중요한 줄은 '기존 코드 패턴을 먼저 확인하라'는 문장이다. 에이전트가 새 파일을 만들 때 가장 흔한 실수는 프로젝트 안에 이미 있는 패턴을 무시하고 인터넷에서 본 듯한 구조를 가져오는 것이다. 이 한 줄은 생각보다 많은 문제를 막는다.

템플릿 2: 코드 스타일 공통 규칙

파일명: .cursor/rules/01-code-style.mdc

TypeScript, JavaScript, Python처럼 언어가 다른 파일을 함께 다루는 저장소라면 코드 스타일 규칙도 너무 구체적으로 쓰면 안 된다. 이 템플릿은 여러 언어에 걸쳐 적용 가능한 원칙만 담고, 세부 문법은 스택별 규칙에서 다룬다.

---
description: General code style and maintainability rules
alwaysApply: false
globs:
  - '**/*.{ts,tsx,js,jsx,py,go,sql}'
---

## Code style

- Prefer readable code over clever code.
- Use descriptive names that reveal intent.
- Keep functions focused on one responsibility.
- Use early returns to reduce deeply nested conditionals.
- Remove unused code instead of leaving commented-out blocks.
- Do not add obvious comments that merely repeat the code.
- Add comments only when they explain non-obvious decisions, tradeoffs, or constraints.

## Error handling

- Handle expected error cases explicitly.
- Do not swallow errors silently.
- Return or throw errors in the style already used in this codebase.
- Never expose internal stack traces, database errors, or secret values to end users.

## Refactoring discipline

- Preserve public APIs unless the task explicitly asks to change them.
- When refactoring, keep behavior equivalent and call out any intentional behavior changes.
- Prefer incremental extraction over large rewrites.

<!-- TODO: Add project-specific naming conventions here. -->
<!-- Example: React component files use PascalCase, route folders use kebab-case. -->

write clean code처럼 추상적인 문장만 있는 규칙은 효과가 약하다. '중첩 조건문을 줄이기 위해 early return을 사용하라', '주석 처리된 코드는 남기지 말라'처럼 행동으로 바꿀 수 있는 문장이 더 잘 작동한다.

템플릿 3: 보안과 비밀값 관리

파일명: .cursor/rules/02-security.mdc

보안 규칙은 항상 적용하고 싶어지지만, 너무 길게 만들면 매 대화의 컨텍스트를 잡아먹는다. 그래서 최소 보안 원칙은 00-core.mdc에 넣고, 자세한 보안 지침은 에이전트가 관련 작업이라고 판단할 때 불러올 수 있도록 description을 자세히 적는다.

---
description: Security rules for authentication, authorization, secrets, payments, webhooks, file uploads, external APIs, and user input handling
alwaysApply: false
---

## Secrets and environment variables

- Never hardcode secrets in source code, tests, fixtures, or documentation.
- Read secrets from environment variables or the existing secret management layer.
- Do not print secrets in logs, errors, screenshots, or debug output.
- If a secret appears in code, stop and report it instead of copying it elsewhere.

## User input

- Validate all user-controlled input at the boundary.
- Sanitize or escape user-generated content before rendering it as HTML.
- Do not use dangerous rendering APIs with user data unless the project has an approved sanitizer.

## Authentication and authorization

<!-- TODO: Replace with this project's real auth helpers and middleware names. -->

- Check authentication before accessing private resources.
- Check authorization and ownership before reading or modifying user-owned records.
- Do not rely on client-side checks for access control.
- Follow the existing auth pattern in `src/lib/auth` or the nearest equivalent file.

## External services

- Use HTTPS for external API calls.
- Add timeouts and error handling for network calls.
- Do not send unnecessary personal data to third-party services.

## Webhooks and payments

- Verify webhook signatures before processing payloads.
- Make webhook handlers idempotent when possible.
- Do not trust client-provided payment status, subscription status, or role claims.

솔로 메이커에게 보안은 '나중에 하는 일'처럼 느껴지기 쉽다. 하지만 에이전트가 빠르게 코드를 만들어 줄수록 작은 구멍도 빠르게 늘어난다. 특히 인증, 결제, 업로드, 웹훅은 기능이 작아 보여도 위험도가 높다.

템플릿 4: 테스트 작성 규칙

파일명: .cursor/rules/03-testing.mdc

테스트 규칙은 테스트 파일에 자동으로 붙게 하는 것이 좋다. 단, 기능 구현 중에도 테스트 작성 요청이 자주 나오므로 description도 명확하게 적는다.

---
description: Testing rules for unit, integration, and end-to-end tests
alwaysApply: false
globs:
  - '**/*.{test,spec}.{ts,tsx,js,jsx,py}'
  - 'tests/**/*'
  - '__tests__/**/*'
---

## Testing principles

- Test behavior, not implementation details.
- Prefer small, focused tests with clear setup, action, and assertion steps.
- Use existing test utilities and factories before creating new ones.
- Do not call real external APIs in automated tests.
- Avoid brittle snapshots unless the project already uses them intentionally.

## Test naming

- Test names should describe the observable behavior.
- Include important edge cases, permission failures, and validation failures.

## When adding a feature

<!-- TODO: Replace with this project's actual test framework and commands. -->

- Add or update tests near the changed code.
- Use Vitest for TypeScript tests unless an existing nearby test uses another framework.
- Use pytest for Python tests unless an existing nearby test uses another framework.
- Run the smallest relevant test command first.
- If the focused test passes, run the broader test command when practical.

## Do not

- Do not weaken existing assertions to make tests pass.
- Do not delete failing tests unless the requirement changed and you explain why.
- Do not mock the code under test just to pass the test.

테스트 규칙의 마지막 세 줄은 매우 중요하다. 에이전트는 목표를 달성하려는 성향이 강해서, 가끔 테스트를 통과시키기 위해 테스트 자체를 느슨하게 바꾸려 한다. '테스트를 약화하지 말라'는 규칙은 이런 우회로를 막는 안전장치다.

템플릿 5: Git 커밋과 PR 규칙

파일명: .cursor/rules/04-git-pr.mdc

Git 규칙은 매번 필요하지 않다. 커밋 메시지를 쓰거나 PR 설명을 만들 때만 수동으로 호출해도 충분하다. 예를 들어 채팅에서 @04-git-pr 현재 변경사항으로 커밋 메시지 작성해줘처럼 사용할 수 있다.

---
description: Git commit and pull request writing rules
alwaysApply: false
---

## Commit message rules

<!-- TODO: Choose the convention used by this project. -->

- Use Conventional Commits when possible.
- Allowed types: `feat`, `fix`, `docs`, `refactor`, `test`, `chore`, `perf`, `ci`.
- Keep the subject line concise and specific.
- Use the imperative mood.
- Do not mention AI tools in commit messages unless the project explicitly requires it.

## Pull request description

Include:

- What changed
- Why it changed
- How it was verified
- Any risks, migrations, or follow-up tasks

## Review checklist

- Check for accidental secret exposure.
- Check for unrelated formatting-only changes.
- Check whether tests or type checks should be run.
- Check whether documentation needs to be updated.

커밋 메시지 규칙은 에이전트만을 위한 규칙이 아니다. 나중의 자신을 위한 검색 인덱스다. 혼자 일하는 사람일수록 Git 기록이 곧 동료가 된다.

템플릿 6: 문서화 규칙

파일명: .cursor/rules/05-docs.mdc

문서 규칙은 docs/**/*.md나 README.md를 수정할 때만 자동으로 적용되게 한다.

---
description: Documentation writing rules for README, docs, architecture notes, and runbooks
alwaysApply: false
globs:
  - 'README.md'
  - 'docs/**/*.md'
  - '**/*.md'
---

## Documentation style

- Write for a developer who is new to this repository.
- Prefer concrete commands and file paths over abstract explanations.
- Keep setup instructions executable from top to bottom.
- Update outdated instructions instead of adding contradictory notes.
- Use diagrams or tables only when they make the explanation easier to scan.

## Required sections for operational docs

<!-- TODO: Adapt these sections to your project. -->

- Purpose
- Prerequisites
- Commands
- Environment variables
- Verification steps
- Troubleshooting

## Do not

- Do not document secrets or real credentials.
- Do not invent behavior that is not present in the codebase.
- Do not copy large code blocks from source files unless the document truly needs them.

문서 규칙은 특히 운영 문서에서 빛난다. 배포, 장애 대응, 결제 웹훅 재처리 같은 작업은 자주 하지 않기 때문에 기억에 의존하기 어렵다. 에이전트가 문서를 만들거나 수정할 때 이 규칙을 적용하면 '나중에 나를 살리는 문서'에 가까워진다.

템플릿 7: Next.js와 React 규칙

파일명: .cursor/rules/10-nextjs-react.mdc

Next.js 프로젝트에서 에이전트가 가장 자주 헷갈리는 지점은 Server Component와 Client Component의 경계다. 이 규칙은 그 경계를 먼저 잡아 준다. App Router를 쓰지 않는 프로젝트라면 해당 부분을 반드시 수정해야 한다.

---
description: Next.js and React rules for App Router, components, data fetching, and UI state
globs:
  - 'app/**/*.{ts,tsx}'
  - 'src/app/**/*.{ts,tsx}'
  - 'src/components/**/*.{ts,tsx}'
  - 'components/**/*.{ts,tsx}'
alwaysApply: false
---

## Tech stack

<!-- TODO: Update versions and libraries to match this project. -->

- Next.js App Router is used for routing.
- React is used with TypeScript strict mode.
- Styling uses Tailwind CSS.
- Package manager is pnpm.
- Prefer existing UI components before creating new ones.

## File structure

<!-- TODO: Replace with this project's actual structure. -->

- Routes live in `app/` or `src/app/`.
- Reusable UI components live in `src/components/ui/`.
- Feature-specific components live in `src/features/` or `src/components/features/`.
- Shared utilities live in `src/lib/`.
- Shared types live in `src/types/`.

## React component rules

- Use functional components only.
- Use named exports for reusable components.
- Define props types near the component.
- Keep components focused; extract subcomponents when a file becomes hard to scan.
- Use existing design tokens, utility functions, and UI primitives.

## Server and client boundary

- Default to Server Components unless interactivity is required.
- Add `use client` only when using hooks, browser APIs, event handlers, or client-only libraries.
- Do not import server-only modules into Client Components.
- Pass only serializable props from Server Components to Client Components.

## Data fetching and mutations

<!-- TODO: Choose the actual data fetching pattern: Server Components, Server Actions, TanStack Query, tRPC, or API routes. -->

- Do not fetch server data in `useEffect` when a Server Component or existing data layer is more appropriate.
- Keep database access out of UI components unless this project explicitly allows it in Server Components.
- Validate mutation input on the server.
- After mutations, follow the existing cache invalidation or revalidation pattern.

## Error and loading states

- Add meaningful loading states for async UI.
- Add empty states when lists can be empty.
- Use existing toast, alert, or error boundary patterns.
- Do not expose internal error details to users.

이 템플릿은 그대로 복사해도 되지만, TODO를 반드시 고쳐야 한다. 어떤 프로젝트는 src/를 쓰고, 어떤 프로젝트는 루트의 app/을 쓴다. 어떤 프로젝트는 Server Action을 선호하고, 어떤 프로젝트는 API Route와 TanStack Query를 쓴다. 규칙이 실제 코드베이스와 다르면 에이전트는 규칙을 따를수록 더 틀린 코드를 만든다.

템플릿 8: React SPA 규칙

파일명: .cursor/rules/11-react-spa.mdc

Next.js가 아니라 Vite 기반 React SPA를 운영한다면 이 템플릿을 사용한다. Next.js 규칙과 동시에 넣어도 되지만, 같은 파일에 동시에 적용되지 않도록 globs를 조정하는 것이 좋다.

---
description: React SPA rules for Vite, routing, client state, server state, and components
globs:
  - 'src/**/*.{ts,tsx}'
alwaysApply: false
---

## Tech stack

<!-- TODO: Update this section to match the real project. -->

- React SPA built with Vite.
- TypeScript strict mode is enabled.
- Routing uses React Router.
- Server state uses TanStack Query.
- Client state uses local component state first, then the existing store when needed.
- Styling uses Tailwind CSS or the existing project styling system.

## Component conventions

- Use functional components only.
- Use named exports for components and hooks.
- Keep props types close to the component.
- Prefer composition over large prop-heavy components.
- Use custom hooks for reusable stateful behavior.

## State management

<!-- TODO: Replace with Zustand, Jotai, Redux Toolkit, or the actual state library if used. -->

- Use TanStack Query for server state.
- Do not duplicate server state in a client store unless there is a clear reason.
- Keep global state minimal.
- Store UI-only state near the component that owns it.

## API calls

- Use existing API client functions instead of calling `fetch` directly from components.
- Validate or type API responses according to the project pattern.
- Handle loading, error, empty, and success states explicitly.

## Anti-patterns

- Do not store secrets or long-lived sensitive tokens in localStorage.
- Do not use array index as a key for dynamic lists when a stable id exists.
- Do not mutate props or state directly.

React SPA에서는 '서버 상태'와 '클라이언트 상태'를 구분하는 규칙이 특히 중요하다. 서버에서 온 데이터를 전역 스토어에 복사해 두기 시작하면, 캐시 무효화와 동기화 문제가 금방 복잡해진다.

템플릿 9: Node.js API 규칙

파일명: .cursor/rules/20-node-api.mdc

Express, Hono, Fastify, NestJS 등 Node.js API 프로젝트에 맞춰 수정해 쓰는 템플릿이다. 기본 구조는 route, controller, service, repository 또는 db 계층을 분리하는 방식이다.

---
description: Node.js API rules for routes, controllers, services, validation, and error handling
globs:
  - 'src/routes/**/*.{ts,js}'
  - 'src/controllers/**/*.{ts,js}'
  - 'src/services/**/*.{ts,js}'
  - 'src/api/**/*.{ts,js}'
  - 'server/**/*.{ts,js}'
alwaysApply: false
---

## Tech stack

<!-- TODO: Replace with Express, Hono, Fastify, NestJS, or the real framework. -->

- Node.js API written in TypeScript.
- Use ES modules unless the project already uses CommonJS.
- Runtime validation uses the existing validation library.
- Database access goes through the existing db or repository layer.

## Layering

<!-- TODO: Align these folders with the actual project. -->

- Routes define URL paths and attach middleware.
- Controllers parse requests, validate input, and call services.
- Services contain business logic.
- Repositories or db query modules contain database access.
- Middleware handles cross-cutting concerns such as auth, logging, rate limiting, and errors.

## Validation

- Validate params, query strings, headers, and request bodies at the boundary.
- Do not trust client-provided user ids, roles, prices, or ownership claims.
- Reuse existing schemas before creating new ones.

## Error handling

<!-- TODO: Replace response shape with the project's real API response format. -->

- Use the project's existing error class or error middleware.
- Return consistent error responses.
- Do not leak stack traces or internal database errors in production responses.
- Preserve useful server-side logs for debugging.

## API response shape

<!-- TODO: Delete this section if the project uses a different response convention. -->

- Success: `{ success: true, data: ... }`
- Error: `{ success: false, error: { code, message } }`

## Implementation order

- Update or add validation schema first.
- Add service logic second.
- Add route or controller wiring third.
- Add tests for success, validation failure, and authorization failure.

Node API 규칙에서 가장 중요한 것은 '어디에 무엇을 둘지'다. 에이전트가 모든 로직을 라우트 핸들러 안에 몰아넣기 시작하면 처음에는 빨라 보이지만, 세 번째 기능부터 유지보수가 어려워진다.

템플릿 10: Python 규칙

파일명: .cursor/rules/30-python.mdc

FastAPI, Django, Flask 중 무엇을 쓰든 Python 프로젝트에는 타입 힌트, 계층 분리, 테스트 규칙이 큰 도움이 된다. 아래 템플릿은 FastAPI를 기준으로 작성했지만, Django나 Flask라면 TODO 부분을 바꾸면 된다.

---
description: Python backend rules for FastAPI or similar API services
globs:
  - '**/*.py'
alwaysApply: false
---

## Tech stack

<!-- TODO: Replace with the real framework, Python version, ORM, and package manager. -->

- Python 3.12 or later.
- API framework is FastAPI.
- Use type hints for function parameters and return values.
- Use the existing package manager and dependency workflow.
- Tests use pytest.

## Project structure

<!-- TODO: Align these folders with the actual project. -->

- `app/routers/` contains route definitions.
- `app/services/` contains business logic.
- `app/repositories/` contains database queries.
- `app/schemas/` contains request and response schemas.
- `app/models/` contains database models.
- `app/core/` contains config, dependencies, and infrastructure.

## Python style

- Prefer clear, explicit code over clever abstractions.
- Use type hints consistently.
- Avoid mutable default arguments.
- Keep route handlers thin.
- Extract helpers when a function becomes hard to read.

## FastAPI conventions

<!-- TODO: Remove this section if this is not a FastAPI project. -->

- Use Pydantic models for request and response data.
- Do not return raw database rows directly from endpoints.
- Use dependency injection according to the existing project pattern.
- Use async functions for I/O paths when the project uses async database clients.

## Error handling

- Raise or return errors using the existing project convention.
- Include useful error details for developers without exposing secrets or internals to clients.
- Roll back database transactions when a write operation fails.

## Testing

- Add pytest tests for new service logic and API endpoints.
- Mock external services.
- Do not require real production credentials for tests.

Python 규칙에서는 '타입 힌트'를 가볍게 보지 않는 편이 좋다. 에이전트는 타입 정보가 있을 때 다음 코드를 훨씬 안정적으로 이어 쓴다. Python이 동적 언어라서 느슨하게 써도 된다는 말은, 에이전트와 함께 일할 때는 오히려 손해가 될 때가 많다.

템플릿 11: 데이터베이스와 SQL 규칙

파일명: .cursor/rules/40-database-sql.mdc

데이터베이스 규칙은 반드시 별도 파일로 분리하자. SQL, 마이그레이션, ORM 스키마 파일은 실수의 비용이 크다. 특히 솔로 메이커는 리뷰해 줄 팀원이 없기 때문에 에이전트에게 더 엄격한 가드레일을 줘야 한다.

---
description: Database and SQL rules for migrations, schema changes, queries, and data safety
globs:
  - '**/*.sql'
  - '/migrations//*'
  - '**/schema.{ts,js,py}'
  - '**/prisma/schema.prisma'
  - '/db//*.{ts,js,py}'
  - '/repositories//*.{ts,js,py}'
alwaysApply: false
---

## Database safety

- Never concatenate user input into SQL strings.
- Use parameterized queries or the approved ORM query builder.
- Confirm destructive operations before writing them.
- Do not drop columns, tables, or data without an explicit requirement.
- For large data changes, propose a safe rollout plan.

## Schema changes

<!-- TODO: Replace with Prisma, Drizzle, SQLAlchemy, Alembic, Rails migrations, or the real migration tool. -->

- Use the project's migration system for schema changes.
- Include reversible migrations when the tool supports them.
- Add indexes for new lookup columns when needed.
- Consider backfills when adding non-null columns to existing tables.
- Keep schema, generated types, and application code in sync.

## Query rules

- Select only the columns needed when practical.
- Avoid N+1 query patterns.
- Use transactions for multi-step writes that must succeed or fail together.
- Check authorization and ownership before returning user-owned records.

## Data privacy

- Do not log personal data unless the project has an approved redaction pattern.
- Mask emails, tokens, and identifiers in debug examples when possible.
- Do not create seed data that contains real user information.

## Verification

<!-- TODO: Replace with real commands. -->

- Run migration generation or validation commands after schema changes.
- Run relevant repository or integration tests.
- Explain any migration risk before finishing.

SQL 규칙에는 '하지 말라'가 많아도 괜찮다. 데이터베이스 작업에서는 창의성보다 안전성이 먼저다. 특히 DROP, DELETE, 대규모 UPDATE, 결제 상태 변경, 권한 변경은 에이전트에게 절대 가볍게 맡기면 안 된다.

템플릿 12: 폴더 구조 규칙

파일명: .cursor/rules/06-folder-structure.mdc

새 파일을 만들 때마다 위치가 흔들린다면 폴더 구조 규칙을 따로 만든다. 이 규칙은 프로젝트마다 반드시 수정해야 한다.

---
description: File placement and folder structure rules for creating new files
alwaysApply: false
---

## File placement

<!-- TODO: Replace this entire section with the real folder structure of your project. -->

- New reusable UI components go in `src/components/ui/`.
- New feature components go in `src/features/{feature-name}/components/`.
- New hooks go in `src/hooks/` or inside the relevant feature folder.
- New API client functions go in `src/services/`.
- New server-only utilities go in `src/lib/server/`.
- New shared types go in `src/types/` only when they are used by multiple features.
- Feature-local types should stay inside the feature folder.

## Naming

<!-- TODO: Replace with your naming convention. -->

- React component names use PascalCase.
- Hook names start with `use`.
- Utility function names use camelCase.
- Route folders use kebab-case when the framework allows it.
- Test files live next to the file under test unless the project uses a central `tests/` folder.

## Before creating a file

- Search for an existing equivalent file first.
- Follow the nearest existing pattern.
- If there are two competing patterns, ask which one to follow.

폴더 구조 규칙은 에이전트의 '파일 생성 습관'을 교정한다. 기능이 하나둘 늘어날 때는 차이가 작아 보이지만, 석 달 뒤에는 이 규칙이 프로젝트의 질서를 지켜 준다.

커뮤니티 템플릿을 가져올 때의 점검 절차

커뮤니티 템플릿은 좋은 출발점이다. awesome-cursorrules 같은 저장소에는 다양한 프레임워크와 조합을 위한 규칙이 정리되어 있어 빈 파일에서 시작하는 부담을 줄여 준다.4 하지만 그대로 믿고 붙여 넣으면 안 된다. 템플릿은 평균적인 프로젝트를 위한 것이고, 당신의 프로젝트는 언제나 조금 다르다.

가져온 규칙은 다음 순서로 점검한다.

  • 실제로 쓰는 프레임워크와 버전이 맞는지 확인한다.

  • 존재하지 않는 라이브러리, 폴더, 명령어, alias를 삭제한다.

  • 프로젝트의 현재 코드 패턴과 충돌하는 지침을 고친다.

  • 너무 장황한 설명, 일반론, 중복 문장을 줄인다.

  • 보안, 테스트, 데이터베이스처럼 중요한 규칙은 작은 작업으로 검증한다.

검증은 복잡할 필요가 없다. 예를 들어 SQL 규칙을 추가했다면 Cursor에게 간단한 조회 함수를 만들게 해 본다. 결과가 파라미터 바인딩을 사용하는지, 기존 repository 계층을 따르는지, 에러 처리가 프로젝트 방식과 맞는지 보면 된다. React 규칙을 추가했다면 작은 컴포넌트를 만들게 하고, 파일 위치, export 방식, 상태 관리, 스타일링 방식이 맞는지 확인한다.

좋은 규칙은 에이전트의 결과물을 '조금 더 낫게' 만드는 것이 아니라, 수정해야 할 반복 실수를 줄인다. 규칙을 추가했는데도 매번 같은 수정을 해야 한다면 규칙이 너무 모호하거나, 적용 범위가 잘못되었거나, 실제 코드베이스와 충돌하고 있을 가능성이 높다.

규칙이 길어질 때의 리팩터링 예시

규칙 파일도 코드처럼 리팩터링이 필요하다. 처음에는 하나의 파일로 시작해도 괜찮다. 하지만 아래처럼 한 파일에 모든 것이 들어가기 시작하면 신호가 온 것이다.

---
description: All project rules
alwaysApply: true
---

## Stack
Next.js, React, Node API, PostgreSQL, Stripe, Sentry, Tailwind...

## Architecture
긴 아키텍처 설명 80줄...

## API rules
API 응답 형식, 인증, 에러 처리, 라우팅 규칙 100줄...

## Database rules
마이그레이션, SQL, 인덱스, 백필, 롤백 규칙 120줄...

## Testing
테스트 전략, 테스트 데이터, 목킹 규칙 100줄...

## Deployment
배포 절차, 환경 변수, 롤백 절차 100줄...

이런 파일은 보기에는 든든하지만, 실제로는 에이전트의 집중력을 떨어뜨린다. 해결책은 두 가지다. 첫째, 적용 조건이 다른 규칙을 .mdc 파일로 분리한다. 둘째, 길고 안정적인 설명은 문서로 빼고 .mdc에는 핵심 원칙과 참조 경로만 남긴다.

리팩터링 후에는 이렇게 바꿀 수 있다.

.cursor/rules/
├── 00-core.mdc
├── 02-security.mdc
├── 03-testing.mdc
├── 10-nextjs-react.mdc
├── 20-node-api.mdc
└── 40-database-sql.mdc

docs/
├── architecture.md
├── api.md
├── database.md
└── deployment.md

.cursor/skills/
└── release-checklist/
    └── SKILL.md

그리고 규칙 파일은 짧게 유지한다.

---
description: API implementation rules. Apply when creating or changing API routes, controllers, services, or response formats.
globs:
  - 'src/api/**/*.{ts,js}'
  - 'src/routes/**/*.{ts,js}'
  - 'src/controllers/**/*.{ts,js}'
  - 'src/services/**/*.{ts,js}'
alwaysApply: false
---

## API rules

- Follow the API architecture described in `docs/api.md`.
- Keep route handlers thin and move business logic to services.
- Validate all request input at the boundary.
- Use the existing response envelope.
- Do not expose internal errors to clients.

## Canonical examples

- Follow the pattern in `src/api/users` for CRUD endpoints.
- Follow the pattern in `src/services/billing` for external service calls.

이 방식의 장점은 문서와 규칙의 역할이 분명해진다는 점이다. docs/api.md는 사람이 읽는 자세한 설명이고, .mdc는 에이전트가 작업 순간에 지켜야 할 짧은 지시다. 배포 절차처럼 항상 필요하지 않은 긴 워크플로우는 규칙보다 Skill로 빼는 편이 낫다. 규칙은 자동으로 붙는 가드레일이고, Skill은 특정 작업을 할 때 꺼내 쓰는 플레이북에 가깝다.

적용 후 첫 10분 체크리스트

템플릿을 복사했다면 바로 큰 기능을 맡기지 말자. 먼저 작은 작업으로 규칙이 잘 작동하는지 본다.

  • 00-core.mdc의 명령어가 실제로 존재하는지 확인한다.

  • 스택별 규칙의 globs가 실제 파일 경로와 맞는지 확인한다.

  • Cursor에게 작은 컴포넌트, 작은 API 함수, 작은 테스트를 하나씩 만들게 한다.

  • 결과물이 기존 파일 구조와 naming convention을 따르는지 본다.

  • 이상한 라이브러리를 import하거나 존재하지 않는 helper를 호출하는지 확인한다.

  • 규칙이 너무 자주 적용된다면 alwaysApply를 끄고 globs를 좁힌다.

  • 규칙이 적용되지 않는다면 파일 패턴과 description을 더 구체적으로 고친다.

규칙 파일은 한 번 작성하고 끝나는 문서가 아니다. 에이전트가 같은 실수를 두 번 반복하면 규칙을 추가한다. 반대로 규칙이 거의 쓰이지 않거나 다른 규칙과 충돌하면 삭제하거나 합친다. 좋은 .cursor/rules/ 폴더는 거창한 헌장이 아니라, 실제 작업 중에 다듬어진 작은 약속들의 모음이다.

솔로 메이커에게 이 약속들은 조용한 동료가 된다. PR을 대신 봐 줄 팀원이 없어도, 어제의 내가 정리해 둔 규칙이 오늘의 에이전트에게 방향을 알려 준다. 빈 파일에서 시작하지 말자. 위 템플릿을 붙여 넣고, 프로젝트에 맞게 깎아 내면 된다. 규칙은 길수록 좋은 것이 아니라, 맞을수록 좋다.

참고

1Rules | Cursor Docs

2Cursor Rules Guide - AI Configuration | design.dev

3에이전트와 함께 코딩할 때의 모범 사례 · Cursor

4GitHub - PatrickJS/awesome-cursorrules

책 목록

Cursor로 일하는 법: 에이전트 시대의 솔로 메이커 워크플로우

전체 목차 보기

이 노트는 보도·비평·교육·연구 목적으로 작성되었습니다. 저작권 문의가 있으시면 에서 알려주세요.

틸노트는 사용자가 AI를 활용해 노트를 쉽게 작성하거나 편집할 수 있는 서비스입니다.

AI 스퀘어 단톡방에 함께해요

AI 활용과 틸노트 사용 팁을 나누는 오픈채팅방입니다. 입장 비밀번호는 tilnote입니다.

참여하기