# AI Context File Generator for Salesforce

> Generate project instruction files (CLAUDE.md, AGENTS.md, Cursor rules, GitHub Copilot instructions) so AI coding assistants write better Salesforce code. Formats checked against vendor docs on 2026-11-17. Instructions improve results but do not guarantee correct code: review everything and run tests.

Source: [Claude Code documentation: How Claude remembers your project (CLAUDE.md)](https://code.claude.com/docs/en/memory)
Interactive generator: https://sfdxtalk.com/tools/ai-context-file-generator/

## Where each file goes

| Assistant | File | Notes |
| --- | --- | --- |
| CLAUDE.md | `CLAUDE.md` | Claude Code reads it from the project root (or .claude/CLAUDE.md). |
| AGENTS.md | `AGENTS.md` | Open format read by many coding agents, including Cursor and Claude Code when no CLAUDE.md exists. |
| Cursor rule | `.cursor/rules/salesforce.mdc` | Cursor project rules live in .cursor/rules and use .mdc with frontmatter. |
| Copilot instructions | `.github/copilot-instructions.md` | GitHub Copilot reads this repository-wide file from the .github folder. |

## Rules by topic

### Apex

Bulk-safe, readable Apex that respects governor limits.

- Write every method to handle a list of records (bulkify), never a single record. Triggers, Flows and batches deliver up to 200 records at a time.
- Never run SOQL or DML inside a loop. Query once into a Map, then loop over the Map. Each query and DML statement counts against per-transaction limits.
- Never hard-code record IDs, profile names or org-specific URLs. Query them, or use Custom Metadata, Custom Labels or Named Credentials.
- Do not try to catch LimitException to recover. It cannot be caught, so check the Limits class before expensive work instead.
- Use bind variables in SOQL. If a query must be dynamic, bind values or escape them with String.escapeSingleQuotes(). Prevents SOQL injection.
- Choose async Apex deliberately: Queueable for most new work, Batch Apex for large volumes, Schedulable for timed jobs. Avoid new @future methods.
- Keep methods small and name them for what they do. Put reusable logic in service classes, not in triggers or controllers.

### Triggers

One thin trigger per object that delegates to a handler class.

- Create one trigger per object and keep it logic-free: it only calls a handler class. Order of multiple triggers on one object is not guaranteed.
- Branch on Trigger.operationType in the handler. Use before triggers to change the records being saved, and after triggers for work that needs the record ID.
- Guard against recursion and compare Trigger.oldMap with Trigger.new so logic runs only when a relevant field actually changed.
- Do not make synchronous callouts from a trigger. Enqueue a Queueable that implements Database.AllowsCallouts instead.

### SOQL

Selective, minimal and safe queries.

- Select only the fields you need and filter in the WHERE clause. Never query all records of an object without a filter or LIMIT.
- Prefer indexed fields (Id, Name, lookup and master-detail fields, external IDs) in WHERE clauses on large objects. Non-selective queries on large objects fail or run slowly.
- Use relationship queries and aggregate queries instead of several separate queries when one will do.
- Use WITH USER_MODE in queries that run on behalf of the user. See the Security topic.

### Security and sharing

Sharing, CRUD and field-level security by default.

- Declare classes with `with sharing` by default. Use `without sharing` or `inherited sharing` only deliberately, with a comment explaining why.
- Enforce object and field permissions: use `WITH USER_MODE` in SOQL and `as user` or AccessLevel.USER_MODE for DML, or Security.stripInaccessible() on records you read or write. Apex runs in system mode by default and ignores the user's CRUD and FLS.
- Never build SOQL, SOSL or JavaScript from raw user input. Use bind variables and escape output.
- Never put secrets, tokens or passwords in code, metadata or logs. Use Named Credentials or protected Custom Metadata.
- Do not use Schema describe calls to hide fields as a substitute for real permission checks. Rely on permission sets and the enforcement mechanisms above.

### Testing

Tests that assert behavior, not tests that only add coverage.

- Every test must assert expected behavior with System.Assert methods. Never write tests whose only purpose is code coverage.
- Create test data in the test or in a test data factory. Do not rely on existing org data, and do not use SeeAllData=true.
- Use @TestSetup for data shared by the methods of a test class.
- Test in bulk (200 records), test a negative path, and test as a user with limited permissions using System.runAs().
- Wrap the code under test in Test.startTest() and Test.stopTest(), and call Test.stopTest() before asserting on async results.
- Mock callouts with Test.setMock() and HttpCalloutMock. Real callouts are not allowed in tests.

### Lightning Web Components

Modern LWC patterns and safe Apex calls from components.

- Build new UI as Lightning Web Components, not Aura, unless extending existing Aura code.
- Mark an Apex method `@AuraEnabled(cacheable=true)` only if it is read-only, because @wire requires it and cached results can be stale. Use imperative calls for anything that changes data.
- Prefer Lightning Data Service wire adapters and base components (such as lightning-record-form) over custom Apex for simple record reads and edits.
- Handle errors from Apex and wire results, and show them to the user. Call refreshApex() after changing data that a wire depends on.
- Never set innerHTML or use lwc:dom="manual" with unsanitized data. Do not rely on global DOM queries such as document.querySelector; use this.template.querySelector.
- Write Jest tests for components with the @salesforce/sfdx-lwc-jest tooling.

### Flow and automation

Declarative automation that coexists with Apex.

- Prefer Flow for simple automation and Apex for complex logic. Do not duplicate the same logic in both a Flow and a trigger on one object.
- Use before-save record-triggered flows for same-record field updates, and set precise entry conditions so the flow does not run on every save.
- Never put Get Records, Create, Update or Delete elements inside a loop in a Flow. Collect records in a collection variable and run one element after the loop.
- Add fault paths to elements that can fail, and give a clear error message or log the failure.
- Do not use Process Builder or Workflow Rules for new automation. Salesforce is retiring them in favor of Flow.

### Integration and callouts

Authenticated, mockable, async-friendly callouts.

- Use Named Credentials (callout:Name) for endpoints and authentication. Never hard-code URLs, keys or tokens.
- Do not make a callout after uncommitted DML in the same transaction. Do the callout first, or move it to a Queueable.
- Check the HTTP status code, handle non-2xx responses and timeouts, and set an explicit timeout on the request.
- Keep callout code in a dedicated service class that tests can mock with HttpCalloutMock.
- For event-driven integration, consider Platform Events or Change Data Capture instead of polling.

### Salesforce CLI and deployment

Modern sf commands, source-driven development.

- Use the `sf` CLI (for example `sf project deploy start`). Do not use the legacy `sfdx` commands or the old force:source commands.
- Keep metadata in source format in the repository and treat the repository as the source of truth, not the org.
- Run local tests before deploying: `sf apex run test --test-level RunLocalTests --wait 10 --result-format human --code-coverage`.
- Validate production deployments first with `sf project deploy start --dry-run`. Production deployments need Apex test coverage of at least 75%.
- Never run commands that deploy to, delete from or modify a production org without explicit confirmation from the user.
- Scan code before review with Salesforce Code Analyzer and fix reported issues.

### Known AI mistakes

Things coding assistants commonly get wrong on Salesforce.

- Do not invent Apex methods, classes, SObject fields, metadata types or CLI flags. If you are not certain something exists in API version 68.0, say so and ask, rather than guessing.
- Do not use deprecated or retired features (Workflow Rules, Process Builder, legacy sfdx commands) in new code.
- Do not state governor limits from memory. Say the limit may differ and check the current documentation.
- Do not assume Apex works like Java or JavaScript. Check that a language feature or library idiom exists in Apex before using it.
- Do not claim code works unless it was compiled or tested. State what was not verified.

## Example CLAUDE.md

~~~markdown
# Acme Sales: Salesforce development instructions

Follow these rules when writing or changing code in this Salesforce DX project. Ask when a rule conflicts with the task.

## Project facts

- Salesforce API version: 68.0. Keep `sourceApiVersion` in sfdx-project.json and new metadata at this version.
- Source directory: `force-app`
- Apex test coverage target: at least 85% per class, with meaningful assertions.

## Apex

- Write every method to handle a list of records (bulkify), never a single record. Triggers, Flows and batches deliver up to 200 records at a time.
- Never run SOQL or DML inside a loop. Query once into a Map, then loop over the Map. Each query and DML statement counts against per-transaction limits.
- Never hard-code record IDs, profile names or org-specific URLs. Query them, or use Custom Metadata, Custom Labels or Named Credentials.
- Do not try to catch LimitException to recover. It cannot be caught, so check the Limits class before expensive work instead.
- Use bind variables in SOQL. If a query must be dynamic, bind values or escape them with String.escapeSingleQuotes(). Prevents SOQL injection.
- Choose async Apex deliberately: Queueable for most new work, Batch Apex for large volumes, Schedulable for timed jobs. Avoid new @future methods.
- Keep methods small and name them for what they do. Put reusable logic in service classes, not in triggers or controllers.

## Triggers

- Create one trigger per object and keep it logic-free: it only calls a handler class. Order of multiple triggers on one object is not guaranteed.
- Branch on Trigger.operationType in the handler. Use before triggers to change the records being saved, and after triggers for work that needs the record ID.
- Guard against recursion and compare Trigger.oldMap with Trigger.new so logic runs only when a relevant field actually changed.
- Do not make synchronous callouts from a trigger. Enqueue a Queueable that implements Database.AllowsCallouts instead.

## SOQL

- Select only the fields you need and filter in the WHERE clause. Never query all records of an object without a filter or LIMIT.
- Prefer indexed fields (Id, Name, lookup and master-detail fields, external IDs) in WHERE clauses on large objects. Non-selective queries on large objects fail or run slowly.
- Use relationship queries and aggregate queries instead of several separate queries when one will do.
- Use WITH USER_MODE in queries that run on behalf of the user. See the Security topic.

## Security and sharing

- Declare classes with `with sharing` by default. Use `without sharing` or `inherited sharing` only deliberately, with a comment explaining why.
- Enforce object and field permissions: use `WITH USER_MODE` in SOQL and `as user` or AccessLevel.USER_MODE for DML, or Security.stripInaccessible() on records you read or write. Apex runs in system mode by default and ignores the user's CRUD and FLS.
- Never build SOQL, SOSL or JavaScript from raw user input. Use bind variables and escape output.
- Never put secrets, tokens or passwords in code, metadata or logs. Use Named Credentials or protected Custom Metadata.
- Do not use Schema describe calls to hide fields as a substitute for real permission checks. Rely on permission sets and the enforcement mechanisms above.

## Testing

- Every test must assert expected behavior with System.Assert methods. Never write tests whose only purpose is code coverage.
- Create test data in the test or in a test data factory. Do not rely on existing org data, and do not use SeeAllData=true.
- Use @TestSetup for data shared by the methods of a test class.
- Test in bulk (200 records), test a negative path, and test as a user with limited permissions using System.runAs().
- Wrap the code under test in Test.startTest() and Test.stopTest(), and call Test.stopTest() before asserting on async results.
- Mock callouts with Test.setMock() and HttpCalloutMock. Real callouts are not allowed in tests.

## Lightning Web Components

- Build new UI as Lightning Web Components, not Aura, unless extending existing Aura code.
- Mark an Apex method `@AuraEnabled(cacheable=true)` only if it is read-only, because @wire requires it and cached results can be stale. Use imperative calls for anything that changes data.
- Prefer Lightning Data Service wire adapters and base components (such as lightning-record-form) over custom Apex for simple record reads and edits.
- Handle errors from Apex and wire results, and show them to the user. Call refreshApex() after changing data that a wire depends on.
- Never set innerHTML or use lwc:dom="manual" with unsanitized data. Do not rely on global DOM queries such as document.querySelector; use this.template.querySelector.
- Write Jest tests for components with the @salesforce/sfdx-lwc-jest tooling.

## Flow and automation

- Prefer Flow for simple automation and Apex for complex logic. Do not duplicate the same logic in both a Flow and a trigger on one object.
- Use before-save record-triggered flows for same-record field updates, and set precise entry conditions so the flow does not run on every save.
- Never put Get Records, Create, Update or Delete elements inside a loop in a Flow. Collect records in a collection variable and run one element after the loop.
- Add fault paths to elements that can fail, and give a clear error message or log the failure.
- Do not use Process Builder or Workflow Rules for new automation. Salesforce is retiring them in favor of Flow.

## Integration and callouts

- Use Named Credentials (callout:Name) for endpoints and authentication. Never hard-code URLs, keys or tokens.
- Do not make a callout after uncommitted DML in the same transaction. Do the callout first, or move it to a Queueable.
- Check the HTTP status code, handle non-2xx responses and timeouts, and set an explicit timeout on the request.
- Keep callout code in a dedicated service class that tests can mock with HttpCalloutMock.
- For event-driven integration, consider Platform Events or Change Data Capture instead of polling.

## Salesforce CLI and deployment

- Use the `sf` CLI (for example `sf project deploy start`). Do not use the legacy `sfdx` commands or the old force:source commands.
- Keep metadata in source format in the repository and treat the repository as the source of truth, not the org.
- Run local tests before deploying: `sf apex run test --test-level RunLocalTests --wait 10 --result-format human --code-coverage`.
- Validate production deployments first with `sf project deploy start --dry-run`. Production deployments need Apex test coverage of at least 75%.
- Never run commands that deploy to, delete from or modify a production org without explicit confirmation from the user.
- Scan code before review with Salesforce Code Analyzer and fix reported issues.

## Known AI mistakes

- Do not invent Apex methods, classes, SObject fields, metadata types or CLI flags. If you are not certain something exists in API version 68.0, say so and ask, rather than guessing.
- Do not use deprecated or retired features (Workflow Rules, Process Builder, legacy sfdx commands) in new code.
- Do not state governor limits from memory. Say the limit may differ and check the current documentation.
- Do not assume Apex works like Java or JavaScript. Check that a language feature or library idiom exists in Apex before using it.
- Do not claim code works unless it was compiled or tested. State what was not verified.
~~~
