Org Skills

apex-development

Write production-grade Salesforce Apex for Spring '26 — one-line triggers with a handler/service/selector layering, bulkified SOQL and DML, USER_MODE security, governor-limit-aware design, async Apex (Queueable with AsyncOptions, Batch, Apex Cursors, Schedulable, Platform Events), invocable methods for Flow and Agentforce, error handling and logging.

Download .zip Raw Source
When agents use itUse this whenever the user asks to write, refactor or debug an Apex class, trigger, `.cls`/`.trigger` file, handler, selector, service, Queueable, Batch, Schedulable, `@InvocableMethod` or `@AuraEnabled` method; hits "Too many SOQL queries: 101", CPU time, heap or DML row limits; asks about trigger recursion, MIXED_DML_OPERATION, order of execution, `WITH USER_MODE` vs `WITH SECURITY_ENFORCED`, `Database.queryWithBinds`, `System.enqueueJob`, `Database.getCursor`, or "how do I do X in Apex". Also apply it when deciding whether new logic belongs in an Apex trigger or a record-triggered flow. For tests use `apex-testing`.

Install

Copilot (VS Code, Visual Studio, Copilot CLI and github.com) reads skills from the repository — commit them so the whole team gets them.

npx skills add AGCO-Global/org-skills --skill apex-development -a github-copilot
# or with the org installer (adds .github/skills/apex-development):
npx -y github:AGCO-Global/org-skills add skill apex-development

Uses the open skills CLI. Works with Claude Code, Codex, Cursor, Copilot, Gemini CLI, OpenCode, Windsurf and 60+ others — it asks which agent to install into.

npx skills add AGCO-Global/org-skills --skill apex-development
# user-level instead of project-level:
npx skills add AGCO-Global/org-skills --skill apex-development -g

Installs the salesforce-apex-skills plugin, which bundles all Salesforce / Apex skills and keeps them updated.

/plugin marketplace add AGCO-Global/org-skills
/plugin install salesforce-apex-skills@org-skills
# or just this skill, in this repository:
npx skills add AGCO-Global/org-skills --skill apex-development -a claude-code

Use Download .zip above, then upload it under Customize → Skills → Upload skill. Team and Enterprise admins can sync this repo as a plugin marketplace instead.

Installs into .agents/skills/, which Codex reads.

npx skills add AGCO-Global/org-skills --skill apex-development -a codex

Installs into Cursor's skills folder.

npx skills add AGCO-Global/org-skills --skill apex-development -a cursor

Installs into Gemini CLI's skills folder.

npx skills add AGCO-Global/org-skills --skill apex-development -a gemini-cli

Nothing to install. Press Download .zip above, unzip it, and drop the apex-development folder into your tool's skills folder — .claude/skills/, .github/skills/, .cursor/skills/ or .agents/skills/. Step-by-step, per tool: How to use it. For any other tool with rules or custom prompts, Copy SKILL.md and paste it in — it is plain Markdown.

The npx commands need Node.js 20+ and use your normal git sign-in to GitHub, so they work while the repository is private. Without Node.js, see the No Node.js tab — a skill is a folder of Markdown, so copying it in works just as well.

Skill contents

Apex Development

Targets: Salesforce Spring '26 (API 66.0), Winter '26 noted · Verified: 2026-09 against https://developer.salesforce.com (Apex Developer Guide, Apex Reference) and https://architect.salesforce.com decision guides

Apex runs in a multi-tenant transaction with hard limits. Write every method as if it receives 200 records, runs as a user with restricted sharing, and shares its transaction with flows and other triggers. Design for that case and the single-record case is free.

1. Decide first

Question Default Change when
Flow or Apex on this object? One entry-point mechanism per object: record-triggered Flow or one Apex trigger — never both (decision guide) Apex when logic needs cross-object aggregation, callouts with retry, recursion control, or "high automation density"; if both already exist, an ADR names which owns which fields and nothing adds a third
Where does logic live? Trigger (1 line) → TriggerHandler (routing) → Service (rules) → Selector (SOQL) Tiny org with one trigger: handler + service is enough; never logic in the trigger body
Which trigger framework? TriggerTemplateV2, the org's framework — see salesforce-org-conventions Never for new work; an object on an older framework is migrated, not forked
Security mode for SOQL/DML WITH USER_MODE / AccessLevel.USER_MODE SYSTEM_MODE only in a dedicated without sharing class with a comment saying why; then Security.stripInaccessible before returning data to a user
Sync or async? Sync inside the transaction Callouts, > ~50 ms of extra work per record, or setup-object DML → Queueable
Async job type Queueable (chainable, AsyncOptions, Finalizer) > 50 k rows and each chunk needs its own transaction/roll-up → Batch; large read traversal, resumable, no per-chunk state → Apex Cursors (GA Spring '26); @future never in new code
Config values Custom Metadata Types Per-user/profile hierarchy → Custom Setting; runtime-writable/reportable → custom object

2. Layering and bulkification

  • One trigger per object, one line: new OrderTriggerHandler().run();. The handler routes by Trigger.operationType; services hold rules; selectors hold every SOQL. Copy the skeleton in references/trigger-handler-skeleton.md.
  • Never SOQL or DML inside a loop. Collect Ids → one query into a Map<Id, SObject> → work in memory → one DML. Build Map<Id, List<Child__c>> in one pass; aggregate with GROUP BY/SUM in SOQL instead of nested loops.
  • Change detection: compare Trigger.new with Trigger.oldMap.get(id) and process only records whose relevant fields changed. Same-record field updates go in before context (no extra DML, no recursion).
  • Recursion guard: static Set<Id> of processed Ids per context, not a static boolean (booleans skip records in later 200-record chunks).
  • Limits to design against (sync → async): 100 → 200 SOQL, 150 → 150 DML statements, 10 000 DML rows, 50 000 query rows, 10 s → 60 s CPU, 6 → 12 MB heap. Table with sources in references/async-apex.md.

3. SOQL, DML and security

  • WITH USER_MODE on every query in user-facing paths. WITH USER_MODE supersedes WITH SECURITY_ENFORCED; when you touch a query that has the old clause, replace it — never combine them.
  • Dynamic SOQL: Database.queryWithBinds(query, binds, AccessLevel.USER_MODE); bind variables always, no string concatenation.
  • DML: Database.insert(records, AccessLevel.USER_MODE); Database.insert(records, false) only when partial success is acceptable, and inspect every SaveResult.
  • Every class declares its sharing model explicitly: with sharing by default, without sharing only in a small dedicated class with a documented reason. The org standard recognises these two keywords only — inherited sharing is not used here (see salesforce-org-conventions).
  • Filter on indexed fields (Id, Name, OwnerId, CreatedDate, SystemModStamp, lookups, external Ids); avoid !=, NOT IN, leading % and formula fields in WHERE on large tables.
  • No hard-coded Ids, profile names or record type Ids — record type Ids come from Utils.getRecordTypeId('Case:Digital_Support') held in a static final (see salesforce-org-conventions). Secrets live in Named/External Credentials or Credential__c, never in code.
  • Modern syntax: ?? null-coalescing and ?. safe navigation instead of nested null checks.

4. Async Apex

AsyncOptions options = new AsyncOptions();
options.MaximumQueueableStackDepth = 5;
options.DuplicateSignature = QueueableDuplicateSignature.Builder()
    .addId(accountId).addString('OrderSync').build();
try {
    System.enqueueJob(new OrderSyncQueueable(accountId), options);
} catch (DuplicateMessageException e) {
    // an identical job is already queued — by design
}
  • Queueable: Database.AllowsCallouts for callouts, System.attachFinalizer(this) for retry/cleanup, AsyncOptions for depth and dedupe (AsyncOptions). Chain, don't fan out.
  • Apex Cursors: Database.getCursor(soql) → cursor.fetch(position, count) from a self-re-enqueuing Queueable; up to 50 M rows, 10 fetch calls per transaction. Full sample in references/async-apex.md.
  • Batch: idempotent execute, Database.Stateful only when needed, scope ≤ 200 when callouts are involved.
  • Platform Events: EventBus.publish honours the event definition's Publish After Commit; subscriber triggers are idempotent on EventUuid and throw EventBus.RetryableException only for transient failures.
  • Every async job is idempotent by design — it will run twice eventually.

5. Order of execution and pitfalls

Before-save flows → before triggers → validation rules → duplicate rules → save (uncommitted) → after triggers → assignment → auto-response → workflow (may re-fire triggers once) → escalation → after-save flows → entitlement → roll-ups → criteria-based sharing → commit → post-commit (email, async). Numbered list with the API 54.0 note in references/order-of-execution.md.

  • MIXED_DML_OPERATION: setup objects (User, PermissionSet) and standard objects in one transaction — move one side to a Queueable.
  • Callouts must happen before any DML in the transaction; never call out synchronously from a trigger.
  • Trigger.new is read-only in after context.

6. Invocables, errors and logging

  • @InvocableMethod(label='…' description='…' category='…') on a static method taking List<Request> and returning List<Result>; the label and description are the contract Flow admins and Agentforce agents read, so write them as instructions. Thin façade → service.
  • @AuraEnabled methods: thin, return DTOs, throw AuraHandledException with a user-safe message, log the real exception.
  • Catch specific exceptions (DmlException, QueryException, CalloutException); never an empty catch. Database.setSavepoint()/rollback around multi-step DML that must be atomic.
  • Log through the project's logger to a custom object or Platform Event so logs survive rollback; System.debug is not a logging strategy.
  • ApexDoc on public members (@description, @param, @return, @example) — the Winter '26 tooling reads these tags.

7. Deliverable format

## Design — trigger/handler/service/selector names, before vs after context, Flow coexistence decision
## Code — complete classes with sharing keyword, USER_MODE, bulk-safe loops
## Limits — expected SOQL/DML per 200 records; async choice and why
## Tests — pointer to apex-testing cases to add (positive, bulk 200, negative, runAs)

Checklist

  • One trigger per object, one line; no logic in trigger or handler body
  • Object has either record-triggered flows or an Apex trigger as entry point — not a new second one
  • No SOQL/DML in loops; change detection against Trigger.oldMap
  • with sharing (or without sharing, documented) on every class, and WITH USER_MODE; no WITH SECURITY_ENFORCED left behind
  • Bind variables or queryWithBinds; no hard-coded Ids
  • Async choice justified (Queueable/Batch/Cursor); job idempotent; AsyncOptions where duplicates are possible
  • Callouts before DML; no sync callout from a trigger
  • Specific exceptions caught, logged, rethrown as domain/AuraHandledException
  • Code Analyzer v5 (sf code-analyzer run) has no PMD/SFGE findings at severity 1–2

Anti-patterns

  • Logic in triggers or several triggers per object → one trigger, handler routes, services own rules.
  • Adding an Apex trigger to an object that already has record-triggered flows (or vice versa) → keep one entry point; if both exist, ADR names field ownership.
  • WITH SECURITY_ENFORCED + WITH USER_MODE in one query → USER_MODE only.
  • Static boolean recursion flag → static Set<Id> per context.
  • @future in new code → Queueable with AsyncOptions/Finalizer.
  • Batch Apex for a read-only traversal → Apex Cursors from a Queueable.
  • Schema.getGlobalDescribe() in loops → SObjectType.X.getDescribe() once.
  • Custom Setting for feature flags → Custom Metadata Type (deployable, no DML in tests).

Go deeper

  • references/trigger-handler-skeleton.md — copy-able trigger, handler, service and selector with sharing and USER_MODE.
  • references/async-apex.md — limits table (sync vs async), Queueable + Finalizer, Apex Cursor sample, Batch rules.
  • references/order-of-execution.md — the full numbered list and the API 54.0 flow/workflow note.
  • Sibling skills: apex-testing for tests, salesforce-automation for the Flow side of the coexistence rule, salesforce-security for sharing and CRUD/FLS enforcement, salesforce-integration for callouts and events, salesforce-code-review for reviews, salesforce-org-conventions for the org's naming and mandated patterns.

References

Deeper material the agent loads only when needed.