Agent skill

Platform Apex Anonymous Run

by forcedotcom in forcedotcom/sf-skills

Runs anonymous Apex against the connected org (.apex file or pasted snippet), capturing the debug log, surfacing errors.

Apache-2.0Auto-check passedTesting & QA

Install Platform Apex Anonymous Run

skills CLI
$ npx skills add forcedotcom/sf-skills --skill platform-apex-anonymous-run -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install forcedotcom/sf-skills platform-apex-anonymous-run --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/forcedotcom/sf-skills.git skills-src && mkdir -p .claude/skills && cp -r skills-src/plugins/builder/salesforce-development/skills/platform-apex-anonymous-run .claude/skills/platform-apex-anonymous-run && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
platform-apex-anonymous-run
GitHub stars
1.1k
Token cost
~3k tokens
SKILL.md length
1,333 words
Files
1
Skills in repo
251
Repo updated
First seen
Licence
Apache-2.0

At a glance

Runs anonymous Apex against the connected org (.apex file or pasted snippet), capturing the debug log, surfacing errors.

  • Works in 8 steps: Identify the target org → Resolve the input mode → Set up trace flags (for useful logs) → …
  • Run this anonymous apex
  • SKILL.md covers Tool Restrictions, Anonymous Apex is NOT read-only, Workflow and Examples, plus 2 more sections
  • Calls sf

What it does

Platform Apex Anonymous Run is an agent skill from forcedotcom/sf-skills. Runs anonymous Apex against the connected org (.apex file or pasted snippet), capturing the debug log, surfacing errors. Triggers on "run this anonymous apex", "execute this script against my org", "what does this code return", or "execute scripts/foo.apex". Wraps scripts in savepoint+rollback; warns before running in production. DO NOT TRIGGER for authoring .cls/.trigger files (platform-apex-generate), Apex unit tests (platform-apex-test-run), or debug-log analysis (platform-apex-logs-debug).

Its SKILL.md is about 3k tokens, which your agent loads only when the skill is triggered. It is a single SKILL.md file with no bundled scripts.

It sits in Testing & QA, covering Unit testing. It works with Salesforce. The repository describes itself as: Salesforce's curated collection of agent skills for building applications. Optimized for Agentforce Vibes, compatible with all AI tools. The licence is Apache-2.0.

When your agent uses it

  • Run this anonymous apex
  • Execute this script against my org
  • What does this code return
  • Execute scripts/foo.apex

Example prompts

  • “run this anonymous apex”
  • “execute this script against my org”
  • “what does this code return”
  • “/platform-apex-anonymous-run”

Workflow steps

8 steps, taken from the step headings in SKILL.md.

  1. Identify the target org
  2. Resolve the input mode
  3. Set up trace flags (for useful logs)
  4. Snippet mode: write the temp file
  5. Execute
  6. Parse the JSON response
  7. Surface the debug log
  8. Report

What it can do on your machine

Read from SKILL.md and the folder at commit e5164d9. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves nothing: there is no allowed-tools line, so your agent's usual permission prompts apply.

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    Shell commands in SKILL.md call:

    • sf

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    No URLs in SKILL.md.

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names no API keys, tokens, secrets or passwords.

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

Context cost

Platform Apex Anonymous Run loads about 3k tokens when it runs. Until then it costs about 132 tokens; SKILL.md has 1,333 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~132
When it runs · the whole SKILL.md, loaded when a task matches
~3k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check passed

The automated check found no risky patterns in SKILL.md.

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); files beside SKILL.md are not scanned.

SKILL.md

The full file from forcedotcom/sf-skills at commit e5164d9, republished under its Apache-2.0 licence (© forcedotcom). 1,333 words, ~2,982 tokens.

Download SKILL.mdSave it as .claude/skills/platform-apex-anonymous-run/SKILL.md (or your agent's skills folder).
name
platform-apex-anonymous-run
description
Runs anonymous Apex against the connected org (.apex file or pasted snippet), capturing the debug log, surfacing errors. Triggers on "run this anonymous apex", "execute this script against my org", "what does this code return", or "execute scripts/foo.apex". Wraps scripts in savepoint+rollback; warns before running in production. DO NOT TRIGGER for authoring .cls/.trigger files (platform-apex-generate), Apex unit tests (platform-apex-test-run), or debug-log analysis (platform-apex-logs-debug).
metadata.version
1.0
metadata.relatedSkills
platform-apex-generate, platform-apex-test-run, platform-apex-logs-debug

platform-apex-anonymous-run

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.


Tool Restrictions

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 is NOT read-only

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:

    apex
    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.


Workflow

Step 1 — Identify the target org

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.

bash
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.

Step 2 — Resolve the input mode
ModeWhenAction
File modeDeveloper points at an existing path ending in .apex (or any path they specify)Run sf apex run --file <path> directly
Snippet modeDeveloper pastes Apex code into the conversationWrite 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:

bash
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.

Step 3 — Set up trace flags (for useful logs)

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:

bash
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.

Step 4 — Snippet mode: write the temp file

Only applies when the input is a pasted snippet:

bash
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.

Step 5 — Execute
bash
sf apex run --file <path> --target-org <alias> --json
  • Always pass --json. Human-format output conflates compile vs runtime errors.
  • If target-org is already configured, --target-org may be omitted, but log the alias used.
  • The command exits non-zero on compile errors. Capture both stdout and the parsed JSON.
Step 6 — Parse the JSON response

The sf apex run --json response shape (relevant fields):

json
{
  "status": 0,
  "result": {
    "compiled": true,
    "success": true,
    "compileProblem": "",
    "exceptionMessage": "",
    "exceptionStackTrace": "",
    "line": -1,
    "column": -1,
    "logs": "...full debug log text..."
  }
}

Decision tree:

compiledsuccessMeaningSurface
false—Compile failurecompileProblem, line, column, the offending source line
truefalseRuntime exceptionexceptionMessage, exceptionStackTrace, plus log tail
truetrueSuccessWhatever 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.

Step 7 — Surface the debug log
  • Short logs (< ~200 lines): inline the log body in the report between fenced code blocks.
  • Large logs: write the log to .sfdx/tmp/anon-<ts>.log and report the path. Include the last 30 lines inline as a tail summary.
  • Empty / missing log: likely no active TraceFlag. Surface the Step 3 setup hint and proceed with whatever compile/runtime status was returned.

Highlight these patterns when present in the log:

PatternWhy it matters
LIMIT_USAGE_FOR_NS linesGovernor consumption snapshot — flag SOQL/DML/CPU near-limit
EXCEPTION_THROWNUnhandled exception within the anonymous block
FATAL_ERRORUnrecoverable error — show the full trailing block
SOQL_EXECUTE_BEGIN count > 1 inside a loopSOQL-in-loop hint (hand off to platform-apex-logs-debug)
DML_BEGIN count highUnbatched DML hint

Do not attempt full log parsing here — surface signals only, then hand off to platform-apex-logs-debug for deep analysis.

Show full SKILL.md (485 more words)Show less
Step 8 — Report
text
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>

Examples

Example 1 — File mode

"Run scripts/seed-test-data.apex against my default org."

  1. Resolve <alias> from sf config get target-org --json.
  2. Confirm the file exists; if not, stop and surface file not found.
  3. Run sf apex run --file scripts/seed-test-data.apex --target-org <alias> --json.
  4. Parse JSON. Report compile/runtime status, log tail, and org mode.
  5. Suggest: "If this seeded real data and you'd like to verify without persisting, re-run with the rollback wrapper (snippet mode)."
Example 2 — Snippet mode (read query)

"Execute System.debug([SELECT count() FROM Account]); and tell me the count."

  1. Resolve <alias>.
  2. Echo the snippet back; confirm.
  3. Write the snippet to .sfdx/tmp/anon-<ts>.apex (Write tool).
  4. Run sf apex run --file .sfdx/tmp/anon-<ts>.apex --target-org <alias> --json.
  5. Parse result.logs; extract the USER_DEBUG line for the count.
  6. Report: "Account count = N. Source: .sfdx/tmp/anon-<ts>.apex (kept for reference)."
Example 3 — Verification with rollback

"Test that this Apex correctly upserts a Contact, then rollback."

  1. Resolve <alias>. If prod, surface a heads-up before running.

  2. Wrap the developer's snippet:

    apex
    Savepoint sp = Database.setSavepoint();
    try {
        // ---- developer snippet begins ----
        Contact c = new Contact(LastName = 'Smoke', Email = 'smoke@example.com');
        upsert c Email;
        System.debug('Upserted: ' + c.Id);
        // ---- developer snippet ends ----
    } finally {
        Database.rollback(sp);
        System.debug('Rolled back savepoint.');
    }
  3. Write to .sfdx/tmp/anon-<ts>.apex, execute, parse JSON.

  4. Report compile/runtime status, the upserted Id from the log, and Rollback: applied.


Failure Modes

SymptomCauseRecovery
No authorization information found for ...Org not authenticated, or alias is wrongRun 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 cwdConfirm absolute path; re-run
compileProblem non-empty in JSONApex compile errorSurface compileProblem, line, column; show that line; suggest a fix
success: false with exceptionMessageRuntime exception inside the anonymous blockSurface exception type + message + stack; show governor counts if present
logs field is empty even on successNo active TraceFlag for running userTell developer to run sf apex tail log --target-org <alias> in another terminal, then re-run
status !== 0 with no resultCLI / network / auth failure before executionSurface raw stderr; do not retry blindly
Unrecognized flag errorSpec drift with the installed CLIRe-check sf apex run --help; do not invent flags

Rules

  • Always pass --json.
  • Always resolve <alias> from configuration or the developer; never hardcode.
  • Never use --apex-code-style inline flags — they are not supported by the current CLI and are escape-hostile. Always go through --file.
  • Always echo a pasted snippet back to the developer for confirmation before executing.
  • For verification-style scripts, default to wrapping in Database.setSavepoint() + Database.rollback().
  • For prod orgs, surface a heads-up but do not auto-block — the developer is in charge.
  • Do not auto-delete temp files under .sfdx/tmp/.
  • This skill executes anonymous Apex; it does not author, deploy, or test .cls/.trigger files. For those, hand off to platform-apex-generate, the deploy skills, or platform-apex-test-generate.
  • For deep log analysis, hand off to platform-apex-logs-debug.

© forcedotcom, Apache-2.0. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

Just SKILL.md in plugins/builder/salesforce-development/skills/platform-apex-anonymous-run of forcedotcom/sf-skills.

Open the folder on GitHubat commit e5164d9

Compare with similar skills

Platform Apex Anonymous Run next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

Platform Apex Anonymous Run compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Platform Apex Anonymous Run this skillforcedotcom/sf-skills1.1k—~3kAutomated safety check: PassApache-2.0
Soql Lib Testingbeyond-the-cloud-dev/soql-lib154—~2.1kAutomated safety check: PassMIT
Run TestsPortwood-Global-Solutions/Portwood126—~1.6kAutomated safety check: PassApache-2.0
Sf LwcJaganpro/sf-skills424—~1.6kAutomated safety check: PassMIT
TDD WorkflowhellangleZ/burn-in-cceverywhere-ralph11211 repos~2.4kAutomated safety check: PassNone
Testing OpenLogi UIAprilNEA/OpenLogi23k—~1.1kAutomated safety check: PassApache-2.0

Similar skills

  • Soql Lib Testing

    beyond-the-cloud-dev/soql-lib

    Writes unit tests for Salesforce Apex code that uses SOQL Lib (SOQL.cls).

    154 GitHub stars~2.1k tokensUpdated 6 days ago
    Testing & QAAuto-check passed
  • Run Tests

    Portwood-Global-Solutions/Portwood

    Run Portwood's test suites — the one-command QA harness, the anonymous-Apex e2e scripts, Apex unit tests, prettier, and Code Analyzer.

    126 GitHub stars~1.6k tokensUpdated today
    Testing & QAAuto-check passed
  • Sf Lwc

    Jaganpro/sf-skills

    Lightning Web Components with PICKLES methodology and 165-point scoring.

    424 GitHub stars~1.6k tokensUpdated 5 mo ago
    Testing & QAAuto-check passed
  • TDD Workflow

    hellangleZ/burn-in-cceverywhere-ralph

    A skill your agent uses when writing new features, fixing bugs, or refactoring code.

    112 GitHub starsUsed in 11 repos~2.4k tokens
    Testing & QAAuto-check passed
  • Testing OpenLogi UI

    AprilNEA/OpenLogi

    Verifies OpenLogi's native GPUI interface with focused tests, the component gallery and a mock agent, choosing the evidence that fits each change.

    23k GitHub stars~1.1k tokensUpdated today
    Testing & QAAuto-check passed
  • Go Testing

    cxuu/golang-skills

    A skill your agent uses when writing, reviewing, or improving Go test code — including table-driven tests, subtests, parallel tests, test helpers, test doubles, and assertions with cmp.Diff.

    172 GitHub starsUsed in 1 repo~1.3k tokens
    Testing & QAAuto-check passed

More from forcedotcom/sf-skills

All 251 skills in this repo
  • Agentforce Architecture Analyze

    forcedotcom/sf-skills

    Declared architecture snapshot for one Agentforce agent: planner, topics, actions, flows, Apex, prompt templates, and NGA plugins.

    1.1k GitHub stars~4.5k tokensUpdated 2 days ago
    Auto-check passed
  • Agentforce D360 Analyze

    forcedotcom/sf-skills

    Data Cloud 360° view of a single Agentforce session. An agent skill from forcedotcom/sf-skills.

    1.1k GitHub stars~3.4k tokensUpdated 2 days ago
    Auto-check passed
  • Apply a Salesforce sandbox post-copy automation JSON config against a target org.

    1.1k GitHub stars~5.3k tokensUpdated 2 days ago
    Auto-check: notes
  • Apply a Salesforce sandbox post-copy automation JSON config against a target org.

    1.1k GitHub stars~5.4k tokensUpdated 2 days ago
    Auto-check: notes
  • Design Systems Slds Apply

    forcedotcom/sf-skills

    Apply SLDS-compliant UI using the correct blueprints, styling hooks, utility classes, and icons.

    1.1k GitHub stars~3.7k tokensUpdated 2 days ago
    Auto-check passed
  • Experience Lwc Generate

    forcedotcom/sf-skills

    Lightning Web Components with PICKLES methodology and 165-point scoring.

    1.1k GitHub stars~2.4k tokensUpdated 2 days ago
    Auto-check passed

Works with

Categories

Questions about Platform Apex Anonymous Run

What does Platform Apex Anonymous Run do?

Runs anonymous Apex against the connected org (.apex file or pasted snippet), capturing the debug log, surfacing errors. Platform Apex Anonymous Run is an agent skill from forcedotcom/sf-skills.apex file or pasted snippet), capturing the debug log, surfacing errors.

When should I use Platform Apex Anonymous Run?

Platform Apex Anonymous Run fits situations like: run this anonymous apex; execute this script against my org; what does this code return; execute scripts/foo.apex.

How do I install Platform Apex Anonymous Run in Claude Code?

Run `npx skills add forcedotcom/sf-skills --skill platform-apex-anonymous-run -a claude-code`. Or copy the skill folder (plugins/builder/salesforce-development/skills/platform-apex-anonymous-run in forcedotcom/sf-skills) into .claude/skills/platform-apex-anonymous-run in your project. Claude Code loads it when a task matches its description.

How do I install Platform Apex Anonymous Run in Codex?

Run `npx skills add forcedotcom/sf-skills --skill platform-apex-anonymous-run -a codex`. Or copy the skill folder (plugins/builder/salesforce-development/skills/platform-apex-anonymous-run in forcedotcom/sf-skills) into .agents/skills/platform-apex-anonymous-run in your project. Codex loads it when a task matches its description.

Can I use Platform Apex Anonymous Run in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add forcedotcom/sf-skills --skill platform-apex-anonymous-run -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/platform-apex-anonymous-run, .gemini/skills/platform-apex-anonymous-run, .github/skills/platform-apex-anonymous-run and .opencode/skills/platform-apex-anonymous-run in your project.

What does Platform Apex Anonymous Run need to run?

Going by SKILL.md and its folder, Platform Apex Anonymous Run needs the command-line tools its instructions call (sf).

Does Platform Apex Anonymous Run access the network?

SKILL.md contains no URLs. Any network use would come from the scripts or tools the agent runs. This is read from the text; nothing was executed.

Is Platform Apex Anonymous Run safe to install?

Our automated static check of SKILL.md found no risky patterns, such as piping downloads into a shell, reading credential files or hidden Unicode. It is not a guarantee. Review the folder before installing.

What licence does Platform Apex Anonymous Run use?

Platform Apex Anonymous Run is published under the Apache-2.0 licence (the repository's licence). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does Platform Apex Anonymous Run use?

About 3k tokens (SKILL.md is roughly 12k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full.

What are the alternatives to Platform Apex Anonymous Run?

Skills that share tags, products or a category with Platform Apex Anonymous Run: Soql Lib Testing (beyond-the-cloud-dev/soql-lib, 154 stars), Run Tests (Portwood-Global-Solutions/Portwood, 126 stars), Sf Lwc (Jaganpro/sf-skills, 424 stars) and TDD Workflow (hellangleZ/burn-in-cceverywhere-ralph, 112 stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Platform Apex Anonymous Run?

forcedotcom (a GitHub organization) maintains it in forcedotcom/sf-skills, which has 1,065 GitHub stars. The repository holds 251 skills in this directory. The repository was last updated on October 7, 2026.

Source: forcedotcom/sf-skills on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.