Dev.to AI πŸ€– Ai πŸ‘ 0 πŸ“– 5 min read

Zero-Integration Apex PMD & Security Reviewer Agent in GitHub Copilot

In enterprise Salesforce environments, static code analysis usually happens too late. A developer finishes a complex Apex trigger or service class, opens a pull request, and waits 10 minutes for a CI/CD pipeline running

In enterprise Salesforce environments, static code analysis usually happens too late. A developer finishes a complex Apex trigger or service class, opens a pull request, and waits 10 minutes for a CI/CD pipeline running Salesforce Code Analyzer (PMD) to fail the build over a missing WITH SECURITY_ENFORCED clause, an unescaped dynamic SOQL string, or a hardcoded record ID.

Even worse, in locked-down enterprise orgs, spinning up external AI code-review bots, third-party webhooks, or custom API integrations often hits an immediate Infosec wall.

To solve this without requesting a single external API key or webhook approval, I built a zero-integration Apex PMD & Security Reviewer Agent directly inside Visual Studio Code using GitHub Copilot’s custom agent framework. It runs entirely within the IDE's native Copilot workspace, enforces strict Apex PMD and OWASP security rules in real time, and catches architectural regressions before code ever leaves a developer's laptop.

Why "Zero-Integration" Matters in Enterprise Orgs
Traditional AI code review tools require sending repository diffs over external APIs, configuring GitHub Apps, or maintaining custom middleware. In regulated enterprise environments, getting approval for external SaaS integrations can take months.

By contrast, GitHub Copilot custom agents rely purely on declarative Markdown files stored inside your repository (.github/agents/). Because they operate natively inside your already-approved Copilot enterprise boundary:

Zero infrastructure overhead: No servers, webhooks, or Python/Node wrappers to host or maintain.

Immediate shift-left feedback: Developers invoke the agent directly in Copilot Chat while writing code, rather than waiting for PR checks.

Deterministic guardrails: Instead of asking an LLM to vaguely "review this code," the agent maps findings directly to official Apex PMD rulesets and AppExchange security standards.

Architecture of the Custom Agent
In VS Code, custom agents are defined using a .agent.md file inside .github/agents/ (for team-wide repo sharing) or ~/.copilot/agents/ (for personal cross-project use).

Each agent file consists of two parts:
YAML Frontmatter: Defines the agent’s name, description, and the exact VS Code tools it is permitted to use (for a read-only security reviewer, we restrict it to read/search tools so it analyzes without unexpectedly mutating files).

Structured System Prompt: Codifies the exact PMD rules, severity mappings, and output format.

The Agent Definition (.github/agents/apex-pmd-reviewer.agent.md)
Below is the production blueprint you can drop straight into a Salesforce DX repository:-

name: Apex PMD & Security Reviewer
description: Audits Apex classes and triggers against Salesforce PMD rulesets, governor limit best practices, and OWASP security standards without modifying files.
tools: ['search', 'fetch']

You are a Principal Salesforce Security & Architecture Reviewer. Your task is to audit the provided Apex classes, triggers, and test classes against official Salesforce Code Analyzer (PMD) rulesets and enterprise security standards.

Operating Rules
Read-Only Audit: Report findings clearly with exact file names and line numbers. Do NOT rewrite or modify files unless explicitly asked in a follow-up prompt.
Zero Fluff: Skip generic praise. Lead immediately with actionable defects ordered by severity (Critical, High, Medium).

Mandatory Ruleset Checks

  1. Security (Critical/High)
    ApexCRUDViolation: Verify FLS/CRUD enforcement (WITH USER_MODE, WITH SECURITY_ENFORCED, or Security.stripInaccessible()) before SOQL/SOSL/DML operations.
    ApexSharingViolations: Flag classes performing DML or SOQL without explicit with sharing, without sharing, or inherited sharing declarations.
    ApexSOQLInjection: Detect unescaped string concatenation in Database.query() calls; require bind variables or String.escapeSingleQuotes().
    ApexSuggestUsingNamedCred: Flag hardcoded credentials, tokens, or plain http:// endpoints (ApexInsecureEndpoint).

  2. Performance & Governor Limits (High/Medium)
    OperationWithLimitsInLoop: Detect SOQL, SOSL, DML, or Messaging.sendEmail calls inside for or while loops.
    AvoidNonRestrictiveQueries: Flag SOQL queries lacking WHERE or LIMIT clauses on potentially large objects.
    AvoidDebugStatements: Flag unguarded System.debug() calls or missing LoggingLevel parameters (DebugsShouldUseLoggingLevel).

3.Architecture & Design (Medium)
AvoidLogicInTrigger: Ensure triggers delegate immediately to a single handler framework with no business logic or SOQL/DML in the .trigger file.
AvoidHardcodingId: Flag 15- or 18-character Salesforce record IDs; require Custom Metadata Types, Custom Settings, or dynamic queries.
QueueableWithoutFinalizer: Flag Queueable implementations that lack a System.Finalizer for async error recovery.

4.Test Quality
ApexUnitTestClassShouldHaveAsserts: Verify every @IsTest method contains meaningful Assert statements (preferring the modern Assert class over legacy System.assert).
ApexUnitTestShouldNotUseSeeAllDataTrue: Flag `@IsTest(seeAllData=true).

Output Format
For each issue found, output:
[Severity] RuleName (FileName.cls:LineNumber)
Vulnerability / Flaw: Concise technical explanation of the risk.
Remediation: Exact code snippet showing the compliant fix.

To see how the agent behaves in practice, consider a typical service class written under tight sprint deadlines:

public class AccountSyncService {
public static List searchAccounts(String industryInput) {
String query = 'SELECT Id, Name, AnnualRevenue FROM Account WHERE Industry = \'' + industryInput + '\'';
List results = Database.query(query);

    for (Account acc : results) {
        if (acc.AnnualRevenue > 1000000) {
            acc.Rating = 'Hot';
            update acc;
        }
    }
    return results;
}

}

When you select Apex PMD & Security Reviewer from the Copilot Chat agent dropdown and ask it to audit AccountSyncService.cls, it immediately flags four distinct violations instead of giving vague stylistic feedback:

[Critical] ApexSOQLInjection (AccountSyncService.cls:3): industryInput is concatenated directly into Database.query(), exposing the org to SOQL injection. Fix: Use a bind variable (WHERE Industry = :industryInput) or String.escapeSingleQuotes().

[High] ApexSharingViolations (AccountSyncService.cls:1): Class omits an explicit sharing keyword (with sharing), risking unintended record exposure when invoked from Aura/LWC or global contexts.

[High] ApexCRUDViolation (AccountSyncService.cls:4): Query executes without WITH USER_MODE or Security.stripInaccessible(), bypassing object- and field-level permissions.

[High] OperationWithLimitsInLoop (AccountSyncService.cls:9): update acc is executed inside a for loop, risking System.LimitException: Too many DML statements: 151. Fix: Collect modified records into a List and perform a single bulkified DML operation outside the loop.

Best Practices for Rolling This Out to a Team--

If you are introducing custom Copilot agents across an engineering pod, keep three lessons in mind:

  1. Separate shared conventions from agent roles: Keep general formatting rules in .github/copilot-instructions.md so every agent inherits them automatically, and reserve .github/agents/*.agent.md for specialized, single-purpose workflows like security auditing or test generation.

  2. Restrict tool permissions on reviewers: Explicitly configure tools in the YAML frontmatter so your reviewer agent only reads and searches code. Separation of duties keeps audits fast and prevents unexpected workspace edits.

  3. Pair AI review with deterministic CI gates: An AI agent accelerates developer feedback loops by orders of magnitude, but it complementsβ€”rather than replacesβ€”running sf code-analyzer run in your pull-request pipeline for compliance audit trails.

By encoding PMD rules and architectural standards into a lightweight Markdown agent, you turn static analysis from a frustrating CI bottleneck into an interactive pair-programming guardrail.

πŸ“° Read the original article on Dev.to AI

Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.