Przejdź do głównej zawartości

Project Rules

Ta treść nie jest jeszcze dostępna w Twoim języku.

Project rules are the foundation of effective AI-assisted development. In this 10-minute guide, you’ll learn to create rules that ensure consistent code generation aligned with your team’s standards.

.cursor/rules/
├── always/ # Applied to every AI interaction
├── auto-attached/ # Applied based on file patterns
├── agent-requested/ # AI decides when to apply
└── manual/ # Only when explicitly referenced

Automatic Context

Rules become part of the AI’s context automatically, like having a senior developer always guiding the junior

Version Controlled

Check rules into Git so your entire team benefits from shared knowledge and standards

Hierarchical

Rules cascade from project root to subdirectories, with local rules overriding global ones

Dynamic Updates

Update rules on the fly - AI immediately adopts new guidelines without restart

  1. Open Command Palette: Cmd/Ctrl + Shift + P

  2. Run Generation Command: “Generate Cursor Rules”

  3. Review Generated Structure:

    .cursor/rules/
    ├── code-style.mdc
    ├── architecture.mdc
    ├── testing.mdc
    └── documentation.mdc
  4. Customize Generated Rules: Edit each file to match your standards

Cursor analyzes your codebase and creates rules for:

  • Coding style from existing patterns
  • Architecture from project structure
  • Testing patterns from test files
  • Documentation from comments/docs
  • Dependencies from package files
  • Git conventions from commit history

Always Applied Rules

Rules that apply to every AI interaction. Use sparingly for universal standards.

---
description: Core coding standards
alwaysApply: true
---
# Universal Standards
- Never commit secrets or API keys
- Always handle errors explicitly
- Use TypeScript strict mode
- Follow ESLint configuration
- Include unit tests for new functions
---
description: React component standards
globs: ["src/components/**/*.tsx"]
---
# React Component Rules
- Use functional components only
- Implement proper TypeScript props
- Include Storybook stories
- Use CSS modules for styling
- Follow atomic design principles
## Component Structure
```typescript
interface ComponentProps {
// Documented props
}
export const Component: FC<ComponentProps> = (props) => {
// Implementation
};
---
description: Performance optimization guidelines - AI uses when optimizing code
alwaysApply: false
---
# Performance Optimization
When optimizing code:
- Profile before optimizing
- Document performance improvements
- Consider memory vs CPU tradeoffs
- Use caching strategically
- Implement lazy loading where appropriate
---
description: Legacy code handling - use @legacy-rules
alwaysApply: false
---
# Legacy Code Guidelines
When working with legacy code:
- Maintain backward compatibility
- Add deprecation warnings
- Create migration guides
- Test extensively before refactoring
  1. Be Specific and Actionable

    ❌ "Write good code"
    ✅ "Use const for immutable values, let for mutable"
  2. Include Examples

    ## Error Handling Pattern
    ```typescript
    try {
    const result = await riskyOperation();
    return { success: true, data: result };
    } catch (error) {
    logger.error('Operation failed', { error, context });
    return { success: false, error: error.message };
    }
  3. Provide Context

    # Why This Rule
    We use dependency injection to improve testability
    and reduce coupling between modules.
  4. Keep Rules Focused

    • One topic per rule file
    • 50-200 lines optimal length
    • Clear section headers
---
description: Security best practices
alwaysApply: true
---
# Security Standards
## Authentication
- Use JWT tokens with short expiration
- Implement refresh token rotation
- Store sensitive data in environment variables
- Hash passwords with bcrypt (min 10 rounds)
## Input Validation
- Sanitize all user inputs
- Use parameterized queries
- Implement rate limiting
- Validate file uploads
## NEVER
- Log passwords or tokens
- Use eval() or dynamic code execution
- Trust client-side validation
- Store secrets in code
  1. During Development:

    AI: "I'll use PostgreSQL for this feature"
    You: "# Always use MySQL for our projects, not PostgreSQL"
  2. Rule Gets Added:

    # Database Choice
    Always use MySQL for our projects, not PostgreSQL
  3. Immediate Effect: Next request will use MySQL

After a productive session:

  1. Run /Generate Cursor Rules in chat
  2. AI extracts patterns and decisions
  3. Creates rules for future use
  4. Review and commit to Git
.cursor/rules/
├── features/
│ ├── authentication/
│ │ ├── jwt-tokens.mdc
│ │ └── oauth-flow.mdc
│ ├── payments/
│ │ ├── stripe-integration.mdc
│ │ └── invoice-generation.mdc
│ └── notifications/
│ ├── email-templates.mdc
│ └── push-notifications.mdc
.cursor/rules/
├── presentation/
│ ├── components.mdc
│ └── styles.mdc
├── business/
│ ├── services.mdc
│ └── validation.mdc
└── data/
├── repositories.mdc
└── migrations.mdc
.cursor/rules/
├── performance/
│ ├── caching.mdc
│ └── optimization.mdc
├── security/
│ ├── authentication.mdc
│ └── encryption.mdc
└── quality/
├── testing.mdc
└── code-review.mdc
---
description: Environment-specific rules
globs: ["src/**/*.ts"]
---
# Environment Rules
## Development
When NODE_ENV is development:
- Use verbose logging
- Enable debug endpoints
- Skip email sending
## Production
When NODE_ENV is production:
- Use structured logging
- Disable debug endpoints
- Implement rate limiting
---
description: Architecture patterns
---
# Follow Our Architecture
Implement patterns from:
@architecture/diagrams/system-design.png
@architecture/decisions/adr-001.md
Key principles:
- Event-driven communication
- CQRS for complex domains
- Repository pattern for data access
---
description: Refactoring guidelines
globs: ["src/legacy/**/*"]
---
# Legacy Code Refactoring
## Phase 1: Add Types
- Add TypeScript types to interfaces
- Document existing behavior
- Don't change functionality
## Phase 2: Extract Functions
- Break large functions < 50 lines
- Extract reusable utilities
- Add unit tests
## Phase 3: Modernize
- Convert to async/await
- Use modern JS features
- Update dependencies

Over-Specification

Don’t create rules for every tiny detail - focus on important patterns

Contradictions

Ensure rules don’t conflict with each other or existing tools

Outdated Rules

Review and update rules quarterly as your project evolves

Vague Instructions

Replace “write clean code” with specific, measurable guidelines

  1. Create Test Scenario:

    "Create a new API endpoint for user profiles"
  2. Verify AI Follows Rules:

    • Check code style compliance
    • Verify architecture patterns
    • Confirm testing approach
  3. Iterate if Needed:

    • Clarify ambiguous rules
    • Add missing examples
    • Remove ineffective rules
  1. Commit to Git:

    Terminal window
    git add .cursor/rules/
    git commit -m "Add project coding standards"
    git push
  2. Document in README:

    ## AI Coding Standards
    This project uses Cursor rules for consistent AI assistance.
    Rules are in `.cursor/rules/` and automatically apply.
    To update rules:
    1. Edit relevant `.mdc` files
    2. Test with AI
    3. Commit changes
  3. Regular Reviews:

    • Monthly rule review meetings
    • Track rule effectiveness
    • Update based on team feedback

Continue to PRD Workflow

Now let’s master the PRD → Plan → Todo workflow that transforms how you build features.

PRD Workflow →

Time: 15 minutes