/salesforce-development:platform-apex-anonymous-runfrom Salesforce Development
Runs anonymous Apex against a connected Salesforce org, captures debug logs, and surfaces compile-time and runtime errors. Wraps scripts in savepoint+rollback; warns before running in production.
Ships in Salesforce Development. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
Run anonymous Apex against the connected Salesforce org via sf apex run --file, capture the debug log, and narrate compile-time and runtime outcomes back to the developer.
This is the agent-side equivalent of VS Code's Execute Anonymous Apex (document and selection) commands.
This skill is runtime, not generation — for authoring .cls / .trigger files use platform-apex-generate; for running Apex unit tests use platform-apex-test-run; for deep debug-log analysis (governor breakdowns, SOQL-in-loop detection) hand off to platform-apex-logs-debug.
Use ONLY the Bash tool to execute sf apex run, and the Write tool to stage snippet temp files. Do NOT use MCP tools for execution.
Anonymous Apex executes with the running user's permissions and can perform DML, callouts, and platform events. Treat every invocation as a write unless the developer has stated otherwise.
Verification-style scripts (preferred for "test this"): wrap the body in a savepoint + rollback so org state is untouched:
Savepoint sp = Database.setSavepoint();
try {
// ... code under test ...
} finally {
Database.rollback(sp);
}
Production org heads-up: if the resolved <alias> points at a production org (no scratch/sandbox markers in sf org display --json), surface a clear warning before running. This is informational only — there is no automated block. Always wait for an explicit "yes, run it" before executing destructive scripts in prod.
Never run anonymous Apex you did not generate or have not been shown — if the developer pastes a snippet, echo it back and confirm before executing.
Resolve the active org alias from configuration. If target-org is set, the --target-org flag may be omitted from the command, but always log which alias was used in the report.
sf config get target-org --json
Throughout this skill, <alias> is the resolved alias or username. If no target-org is set, ask the developer; do not silently default. If the org is not authenticated, re-authenticate with sf org login web or switch orgs with the dx-org-switch skill.
| Mode | When | Action |
|---|---|---|
| File mode | Developer points at an existing path ending in .apex (or any path they specify) | Run sf apex run --file <path> directly |
| Snippet mode | Developer pastes Apex code into the conversation | Write to .sfdx/tmp/anon-<unix-ts>.apex first, then run sf apex run --file <tmp-path> |
Why a temp file for snippets, instead of an inline flag? The current sf apex run CLI only supports --file (and interactive stdin). It does not expose an --apex-code flag. Even where inline code is supported by other tooling, multi-line Apex passed inline runs into shell-escaping pitfalls (single quotes in string literals, backslashes, embedded $). Writing to a temp file is the only reliable path for arbitrary snippets.
Verify CLI flags before deviating:
sf apex run --help
Supported flags (as of writing): --file/-f, --target-org/-o, --api-version, --json, --flags-dir. Do not invent flags — if the task asks for something not listed, surface that to the developer rather than guessing.
sf apex run returns a debug log only if a TraceFlag is active for the running user (or a streaming tail is attached). Recommended path — let the developer tail logs in another terminal:
sf apex tail log --target-org <alias> --color
This auto-creates a short-lived TraceFlag for the running user and streams logs as anonymous Apex executes. Mention this in the report so the developer can copy/paste it.
If no trace flag is set up, sf apex run will still execute the code and return compile/runtime status — only the debug log body will be missing or sparse.
Only applies when the input is a pasted snippet:
mkdir -p .sfdx/tmp
TS=$(date +%s)
# write the snippet content to .sfdx/tmp/anon-${TS}.apex via the Write tool, NOT via shell heredoc
Use the agent's Write tool (not a heredoc) so the snippet is preserved verbatim — heredocs subject the content to additional shell expansion. Echo the resolved temp path to the developer in the report. Do not auto-clean the temp file after execution — leave it under .sfdx/tmp/ for inspection. The .sfdx/ directory is conventionally gitignored.
sf apex run --file <path> --target-org <alias> --json
--json. Human-format output conflates compile vs runtime errors.target-org is already configured, --target-org may be omitted, but log the alias used.The sf apex run --json response shape (relevant fields):
{
"status": 0,
"result": {
"compiled": true,
"success": true,
"compileProblem": "",
"exceptionMessage": "",
"exceptionStackTrace": "",
"line": -1,
"column": -1,
"logs": "...full debug log text..."
}
}
Decision tree:
compiled | success | Meaning | Surface |
|---|---|---|---|
false | — | Compile failure | compileProblem, line, column, the offending source line |
true | false | Runtime exception | exceptionMessage, exceptionStackTrace, plus log tail |
true | true | Success | Whatever the script printed via System.debug (extracted from logs) |
status !== 0 (top-level) means the CLI itself failed (not authenticated, file not found, network). Surface the raw error and stop.
.sfdx/tmp/anon-<ts>.log and report the path. Include the last 30 lines inline as a tail summary.Highlight these patterns when present in the log:
| Pattern | Why it matters |
|---|---|
LIMIT_USAGE_FOR_NS lines | Governor consumption snapshot — flag SOQL/DML/CPU near-limit |
EXCEPTION_THROWN | Unhandled exception within the anonymous block |
FATAL_ERROR | Unrecoverable error — show the full trailing block |
SOQL_EXECUTE_BEGIN count > 1 inside a loop | SOQL-in-loop hint (hand off to platform-apex-logs-debug) |
DML_BEGIN count high | Unbatched DML hint |
Do not attempt full log parsing here — surface signals only, then hand off to platform-apex-logs-debug for deep analysis.
Anonymous Apex run: <one-line summary — file or snippet, success or failure>
Org: <alias> (mode: scratch | sandbox | production)
Source: <file path or temp path for snippet>
Compile: success | <error + line:column>
Runtime: success | <exception type + message>
Limits: <CPU=x/10000ms, SOQL=y/100, DML=z/150> (only when log includes LIMIT_USAGE_FOR_NS)
Log: <inline | path .sfdx/tmp/anon-<ts>.log>
Rollback: applied | not applied | n/a
Next: <suggested follow-up>
"Run
scripts/seed-test-data.apexagainst my default org."
<alias> from sf config get target-org --json.file not found.sf apex run --file scripts/seed-test-data.apex --target-org <alias> --json."Execute
System.debug([SELECT count() FROM Account]);and tell me the count."
<alias>..sfdx/tmp/anon-<ts>.apex (Write tool).sf apex run --file .sfdx/tmp/anon-<ts>.apex --target-org <alias> --json.result.logs; extract the USER_DEBUG line for the count..sfdx/tmp/anon-<ts>.apex (kept for reference).""Test that this Apex correctly upserts a Contact, then rollback."
Resolve <alias>. If prod, surface a heads-up before running.
Wrap the developer's snippet:
Savepoint sp = Database.setSavepoint();
try {
// ---- developer snippet begins ----
Contact c = new Contact(LastName = 'Smoke', Email = '[email protected]');
upsert c Email;
System.debug('Upserted: ' + c.Id);
// ---- developer snippet ends ----
} finally {
Database.rollback(sp);
System.debug('Rolled back savepoint.');
}
Write to .sfdx/tmp/anon-<ts>.apex, execute, parse JSON.
Report compile/runtime status, the upserted Id from the log, and Rollback: applied.
| Symptom | Cause | Recovery |
|---|---|---|
No authorization information found for ... | Org not authenticated, or alias is wrong | Run sf org list --json; re-auth with sf org login web or use dx-org-switch |
ENOENT: no such file or directory, open '<path>' | .apex file path is wrong or relative to the wrong cwd | Confirm absolute path; re-run |
compileProblem non-empty in JSON | Apex compile error | Surface compileProblem, line, column; show that line; suggest a fix |
success: false with exceptionMessage | Runtime exception inside the anonymous block | Surface exception type + message + stack; show governor counts if present |
logs field is empty even on success | No active TraceFlag for running user | Tell developer to run sf apex tail log --target-org <alias> in another terminal, then re-run |
status !== 0 with no result | CLI / network / auth failure before execution | Surface raw stderr; do not retry blindly |
| Unrecognized flag error | Spec drift with the installed CLI | Re-check sf apex run --help; do not invent flags |
--json.<alias> from configuration or the developer; never hardcode.--apex-code-style inline flags — they are not supported by the current CLI and are escape-hostile. Always go through --file.Database.setSavepoint() + Database.rollback()..sfdx/tmp/..cls/.trigger files. For those, hand off to platform-apex-generate, the deploy skills, or platform-apex-test-generate.platform-apex-logs-debug.What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
38 skills in this plugin
/automation-flow-generateGenerate Salesforce Flows using the MCP tool execute_metadata_action. Use when the user asks to create, build, or generate a flow — including Screen, Autolaunched, Record-Triggered (before/after-save), Scheduled. Also trigger for flow-like requests such as "when a record is created", "trigger daily at", "send an email when", "update the field when", "automate", "workflow", or "flow XML/metadata". This is the only skill for Salesforce Flow generation./dx-org-manageUse to EXECUTE Salesforce org operations immediately via the sf CLI (this skill runs them, it does NOT generate scripts): create scratch orgs (from edition, definition file, snapshot, or org shape), list/display/resume/delete scratch orgs, open orgs in browser. Trigger: 'create scratch org', 'create org from snapshot', 'delete scratch org', 'open my org'. Do NOT use for switching the default org (use dx-org-switch), deploying metadata (use platform-metadata-deploy), or creating/checking/listing/deleting org snapshots (use dx-org-snapshot-manage)./dx-project-createScaffold a Salesforce DX project from any template (standard, agent, analytics, React/Angular/Vue app), move the session in, connect an org, enable source tracking. Use to create a Salesforce/SFDX project. DO NOT TRIGGER for: existing UI-bundle apps (experience-ui-bundle-frontend-generate); UI-bundle scaffold in a larger build (experience-ui-bundle-project-generate, experience-ui-bundle-app-coordinate); tool checks (platform-environment-validate); org login (login); scratch orgs (dx-org-manage)./platform-apex-generatePrimary Apex authoring skill for class generation, refactoring, and review. ALWAYS ACTIVATE when the user mentions Apex, .cls, triggers, or asks to create/refactor a class (service, selector, domain, batch, queueable, schedulable, invocable, DTO, utility, interface, abstract, exception, REST resource). Use this skill for requests involving SObject CRUD, mapping collections, fetching related records, scheduled jobs, batch jobs, trigger design, @AuraEnabled controllers, @RestResource endpoints, custom REST APIs, or code review of existing Apex./platform-apex-logs-debugSalesforce debug log analysis and troubleshooting with 100-point scoring. TRIGGER when: user analyzes debug logs, hits governor limits, reads stack traces, or touches .log files from Salesforce orgs. DO NOT TRIGGER when: running Apex tests (use platform-apex-test-run), generating or fixing Apex code (use platform-apex-generate), or Agentforce session tracing (use agentforce-observe)./platform-apex-test-generateUse to generate and validate Apex test classes with TestDataFactory patterns, bulk testing (251+ records), mocking, assertions, and disciplined test-fix loops. Use when creating Apex test classes (for triggers, services, controllers, batch jobs, queueables, and callouts), improving coverage, debugging or fixing failing Apex tests, or running test/coverage analysis. Triggers on *Test.cls files, sf apex run test, coverage reports. Do NOT trigger for production Apex (use platform-apex-generate) or Jest/LWC tests.2 plugins ship this exact skill · first indexed Sep 23, 2026
npx claudepluginhub forcedotcom/sf-skills --plugin salesforce-developmentOther plugins' skills for the same job