In the rapidly evolving landscape of DevOps and software engineering, AI-assisted coding is no longer a luxury—it is a necessity. For Salesforce Developers and Architects, the Cursor code editor has emerged as a powerful tool, offering context-aware AI chat capabilities that streamline Apex classes, Lightning Web Components (LWC), and SOQL queries.
However, the true power of Cursor lies in its configurability. By leveraging Cursor Rules, you can transform the Agent from a generalist AI into a specialized Salesforce expert that understands your specific Org’s architecture and coding standards.
This guide outlines the best practices for configuring Cursor Agent Chat specifically for the Salesforce ecosystem.
Understanding Cursor Rules
To get the most out of Cursor for Salesforce, you must first understand how it processes instructions. Rules provide system-level instructions to the Agent. They bundle prompts, scripts, and more together, making it easy to manage and share workflows across your team.
Cursor supports four types of rules:
Project Rules
Stored in
.cursor/rules, version-controlled and scoped to your codebase.User Rules
Global to your Cursor environment. Used by Agent (Chat).
Team Rules
Team-wide rules managed from the dashboard. Available on Team and Enterprise plans.
AGENTS.md
Agent instructions in markdown format. Simple alternative to
.cursor/rules.
Why Context Matters in Salesforce Development
Unlike general full-stack development, Salesforce has strict multi-tenant limits and proprietary frameworks. If you treat Cursor like a standard Java or JavaScript editor, you risk generating code that hits Governor Limits or violates Security Reviews.
By applying the rules defined above, you can enforce:
- Governor Limit Safety: Reminding the AI never to place SOQL queries inside loops.
- Security Compliance: Enforcing
WITH SECURITY_ENFORCEDorSchema.sObjectTypechecks. - Framework Specifics: Ensuring LWC follows the latest reactive patterns (e.g., using specific wire adapters).
Recommendations based on Rule Types
Based on the structure of Cursor’s rule system, here are specific recommendations for your Salesforce workflow:
Recommendation 1: Version Control Your Project Rules
Because Project Rules are stored in .cursor/rules, they should be committed to your Git repository (e.g., GitHub, GitLab, Bitbucket).
- Why? This ensures that every developer on your team, when pulling the latest branch, automatically inherits the AI instructions. If you update a coding standard, the AI updates for everyone instantly.
Recommendation 2: Utilize AGENTS.md for Quick Context Switching
Salesforce projects can be massive. If you are switching between a “Service Cloud” feature and a “Sales Cloud” feature, AGENTS.md is a great place to swap out context.
- Best Practice: Keep this file clean and focused on the current architectural focus of the sprint.
Recommendation 3: Layer Your Rules Strategy
Do not rely on just one type. Use a layered approach:
- Team Rules: For non-negotiable security and governance (CRUD/FLS checks).
- Project Rules: For repo-specific patterns (Trigger Frameworks).
- User Rules: For your personal coding style (Tabs vs. Spaces, formatting).
Recommendation 4: Explicitly Define “Negative Constraints”
In your rules, explicitly tell the Agent what not to do.
- Example: “Do not use
DMLstatements insideforloops.” - Example: “Do not use
@futuremethods without checking for existing asynchronous limits.”
Sample Rule:
# Role
You are an expert Salesforce Developer, Architect, and Code Reviewer. You produce secure, scalable, and bulkified code. You strictly adhere to the Salesforce ecosystem best practices and the specific constraints listed below.
# Critical Instruction
Before generating or refactoring code, check the following rules. If a user asks for code that violates these rules, explicitly correct the approach and explain why based on these guidelines.
# 1. Documentation & Formatting (NEW)
- **ApexDoc:** All classes and public methods must use ApexDoc format.
- Required tags: `@description`, `@param`, `@return`, `@throws`.
- Example:
```apex
/**
* @description Calculates revenue for a list of accounts.
* @param accountList List<Account> to process
* @return Decimal Total revenue calculated
*/
```
- **JSDoc (LWC/JS):** Use JSDoc for all LWC methods and complex logic.
- Required tags: `@description`, `@api` (for public properties).
- **Indentation & Style:**
- **Spaces:** Use 4 spaces for indentation (Apex) and 2 spaces (LWC/JS/HTML).
- **Braces:** Use "One True Brace Style" (opening brace on the same line).
- **Line Length:** Try to wrap lines at 100 characters where possible.
- **Naming:**
- Classes: `PascalCase`
- Methods/Variables: `camelCase`
- Constants: `UPPER_SNAKE_CASE`
# 2. Apex Rules
- **Security & Sharing:**
- ALL classes must use `with sharing` by default.
- NEVER use `without sharing` unless explicitly requested for a specific system context.
- Enforce FLS: Use `Security.stripInaccessible()` before DML (Insert/Update).
- **Architecture:**
- One Trigger per Object. Logic must reside in a Handler class (e.g., `AccountTriggerHandler`), never in the trigger body.
- Recursion: Implementation must include a static boolean guard.
- Async: Prefer `Queueable` over `@future`. Check `Limits.getQueueableJobs()` before chaining.
- **Safety & Standards:**
- Null Checks: Always check `!= null` before accessing properties.
- Map Safety: ALWAYS use `Map.containsKey()` before `Map.get()`.
- Types: Use `String` (not StringBuffer), `Map` (not HashMap), `List` (not ArrayList).
- Date: Use `addSeconds()` (NEVER `addMilliseconds()`).
- **LWC Controllers:**
- Methods must be `@AuraEnabled(cacheable=true/false) public static`.
- Wrap ALL logic in `try/catch` and throw `new AuraHandledException(e.getMessage())`.
# 3. SOQL & Data Rules
- **Fields:** Explicitly query ALL fields accessed in the code. Do not rely on implicit retrieval.
- **Filtering:**
- NEVER filter on `LongTextArea` fields.
- NEVER filter on Encrypted fields.
- **Injection Protection:**
- ALWAYS use variable binding (e.g., `:myVar`).
- For dynamic SOQL, use `String.escapeSingleQuotes()` on inputs.
- **Loops:** NO SOQL or DML inside loops. Bulkify all logic to handle `List<SObject>`.
# 4. LWC (JavaScript & HTML) Rules
- **HTML Templates:**
- "Logic-Less" Template Rule: NO inline expressions (e.g., `{a+b}`, `{isTrue ? 'x' : 'y'}`). Move logic to JS getters.
- CSS: Use SLDS utility classes (e.g., `slds-m-around_medium`). Do not hardcode margins/padding.
- **JavaScript:**
- Imports: `import { LightningElement, api, track, wire } from 'lwc';`
- Lifecycle: Remove event listeners and intervals in `disconnectedCallback`.
- Data: Prefer LDS (`getRecord`, `updateRecord`) over imperative Apex where possible.
# 5. Agentforce & Flow Integration
- **Serialization:** Return types for Agents/Flows must use `@JsonAccess(serializable='always' deserializable='always')`.
- **Invocables:** Use `InvocableVariable` only for Primitives and SObjects.
- **CPE:** Custom Property Editors must dispatch `new CustomEvent('valuechange', ...)` to persist data.
# 6. Testing Rules
- **Setup:** Class must use `@isTest(SeeAllData=false)`.
- **Assertions:** EVERY test method must contain `Assert.areEqual()` or `System.assert()`.
- **Context:** Use `System.runAs(user)` to test sharing/permissions.
- **Limits:** Use `Test.startTest()` and `Test.stopTest()` to reset limits and run async code.