# Salesforce Coding Standards — Agent Nova

## Purpose and application

Agent Nova must use this file when analysing requirements, designing, writing, reviewing, and fixing Salesforce code and metadata. Apply it to new and changed components; do not perform unrelated cleanup of existing components. These are project standards, not a claim that every convention is a Salesforce platform requirement.

Rule format: `- **ID** LEVEL [auto]: text`. Keep each rule on one line and keep IDs stable.

- **MUST**: Required. An unresolved violation blocks a compliance/pass verdict unless an explicit, documented exception has been authorized by the project owner.
- **SHOULD**: Preferred. Report any departure and its reason; it does not automatically block delivery.
- **[auto]**: Identifies rules intended for automatic checking. Verify the repository checker and its rule coverage before relying on it; the marker alone does not establish enforcement. Review semantic requirements even when a syntactic check passes.
- Rules without `[auto]` still apply and require agent review, tests, or other evidence.
- A valid exception records the rule ID, affected components, reason, security/behavior impact, and authorizing instruction. A code comment alone is not authorization to bypass a requirement.

## Agent workflow and scope

- **AGENT-01** MUST: Before coding, read the ticket and available acceptance criteria, relevant business documentation, and the current repository implementation, including affected metadata, tests, automation, and configuration; identify conflicts and missing material requirements instead of inventing answers.
- **AGENT-02** MUST: Confirm the target Salesforce project, source directories, namespace/package boundaries, and component API versions; discover validation commands from repository instructions, CI workflows, package scripts, and tool configuration, verify their arguments and target, and record the exact commands used; use APIs supported by the target and do not upgrade API versions merely to make generated code compile.
- **AGENT-03** MUST: Verify referenced objects, fields, record types, permission sets, classes, Flows, and configuration against available source or authorized org inspection; when a required dependency cannot be verified, report it explicitly and do not present it as existing.
- **AGENT-04** MUST: Inspect and reuse existing handlers, services, selectors, logging utilities, test factories, and automation patterns before adding new equivalents; explain any necessary departure from the established architecture.
- **AGENT-05** MUST: Keep changes limited to the requested behavior and its necessary dependencies; preserve existing public contracts and metadata API names unless the task explicitly requires a compatible migration.
- **AGENT-06** MUST: For Agent Nova v1, create or modify only record-triggered Flows unless the task explicitly authorizes expanding that scope; inspect other relevant Flow types when assessing dependencies and impact.
- **AGENT-07** MUST: Do not weaken standards, checker configuration, validation gates, assertions, or security controls to make a task pass; changes to those controls require an explicit task instruction and a stated impact.
- **AGENT-08** MUST: Separate verified facts from assumptions; ask a targeted question only when missing information materially affects business behavior, access, data integrity, or scope, and continue independent work where possible.
- **AGENT-09** MUST: Before completing work, review the diff against applicable rule IDs, run available relevant checks, and report exact results; never describe unexecuted or blocked checks as passed.
- **AGENT-10** MUST: Do not deploy to production, activate production automation, change live permissions, or perform destructive data/metadata operations unless the task explicitly authorizes that action.

## Architecture

- **ARCH-01** MUST: Give each class, component, and automation a clear responsibility; keep UI handling, trigger routing, business rules, and data access separate where those responsibilities exist.
- **ARCH-02** MUST: Keep triggers as delegates to handlers, put business rules in service classes, and encapsulate reusable production SOQL in selector classes or the repository's established equivalent; reuse the existing framework rather than introducing a competing one.
- **ARCH-03** SHOULD: Keep abstractions proportionate to the feature; do not create empty layers, speculative frameworks, or unused extension points solely to satisfy naming conventions.
- **ARCH-04** MUST: Identify existing Apex and Flow automation on affected objects, including entry criteria and relevant execution order; avoid duplicate ownership of the same update or side effect and document intentional interactions.

## Apex

- **APEX-01** MUST [auto]: Every top-level Apex class declares `with sharing` or `inherited sharing`; use `without sharing` only for an explicitly authorized need, with a comment on the line above explaining why, and enforce the database access policy independently.
- **APEX-02** MUST [auto]: Test classes are annotated `@isTest`, are named `<ClassUnderTest>Test`, and every test method contains at least one meaningful assertion (`Assert.*` or `System.assert*`) verifying an expected outcome; document intentional naming exceptions for integration tests and shared test utilities.
- **APEX-03** MUST: Bulkify Apex using collections, sets, and maps; do not execute SOQL, SOSL, or DML inside loops, including through methods invoked in loops; do not assume a transaction is limited to 200 records.
- **APEX-04** MUST: Define and enforce the access mode for every database operation; use `WITH USER_MODE` for user-context SOQL and user-mode DML such as `AccessLevel.USER_MODE` where supported; any required system-mode operation needs an explicit business justification and authorization checks, not just a sharing declaration.
- **APEX-05** MUST [auto]: Do not hardcode Salesforce record, user, profile, queue, or record-type IDs; resolve them using stable verified identifiers or environment-appropriate configuration, and handle missing or ambiguous results.
- **APEX-06** SHOULD [auto]: Do not retain `System.debug` statements in non-test classes; use the approved logging utility for operational diagnostics.
- **APEX-07** SHOULD: Name new classes in PascalCase with an appropriate role suffix such as `Service`, `Handler`, `Selector`, `Controller`, `Batch`, `Queueable`, `Scheduler`, or `Test`; preserve established repository conventions and allow meaningful utility/model names.
- **APEX-08** SHOULD: Name methods using camelCase verbs, variables using descriptive camelCase nouns, and constants using UPPER_SNAKE_CASE.
- **APEX-09** SHOULD: Document public classes and methods with ApexDoc comments explaining purpose, parameters, return values, and significant side effects or exceptions where applicable.
- **APEX-10** MUST: Do not leave empty catch blocks or swallow failures; catch only when adding useful handling, safe context, recovery, or translation, and ensure logging does not convert a failed business operation into apparent success.
- **APEX-11** MUST: Create isolated test data without `SeeAllData=true` for ordinary unit tests; use `Test.startTest()` and `Test.stopTest()` around the behavior under test where relevant, and cover bulk operations of at least 200 records and negative cases for collection-processing logic.
- **APEX-12** MUST: When using `Security.stripInaccessible()`, select the appropriate access type, operate on records returned by `getRecords()`, and handle removed fields according to the business requirement; field stripping is not a substitute for record-sharing enforcement or permission to silently omit required values.
- **APEX-13** MUST: Respect the component API version when choosing security syntax; do not generate `WITH SECURITY_ENFORCED` for new code, and do not use it in API version 67.0 or later, where it is unsupported; review security behavior explicitly when changing API versions.
- **APEX-14** MUST: Use bind variables for dynamic query values and allowlist any dynamic identifiers or sort expressions; never concatenate untrusted input into executable SOQL/SOSL.
- **APEX-15** MUST: Query only required fields and records, and design for query rows, CPU, heap, DML, and asynchronous limits across the whole transaction; use appropriate filtering, pagination, or asynchronous processing for large workloads.
- **APEX-16** MUST: Define transaction behavior for multi-step writes; if partial-success DML is used, inspect every result and surface or handle each failure, and do not claim atomic behavior without implementing it.
- **APEX-17** MUST: For asynchronous work, define the execution/security context, bulk behavior, retry limits, duplicate prevention, and failure reporting; do not enqueue one job per record in bulk execution.

## Triggers

- **TRIG-01** MUST [auto]: Triggers contain no business logic or queries and only delegate to the existing handler framework or an appropriate handler class.
- **TRIG-02** MUST: Maintain at most one project-owned Apex trigger per object, named `<Object>Trigger` for new triggers; extend the existing trigger rather than creating another, and report pre-existing or managed-package triggers without deleting or restructuring them outside scope.
- **TRIG-03** MUST: Handle each required trigger context explicitly; use new/old records and maps only in contexts where they are available, and implement before/after behavior according to the requirement.
- **TRIG-04** MUST: Make repeated execution safe through relevant field-change checks and idempotent processing; where a recursion guard is needed, scope it to the operation and records, and do not use a single transaction-wide boolean that can skip valid subsequent batches.

## Flows

- **FLOW-01** SHOULD: Name new Flows `<Object>_<Purpose>` with readable PascalCase words separated by underscores, for example `Account_Customer_Tier_Assignment`.
- **FLOW-02** SHOULD [auto]: Every Flow has a meaningful `<description>` describing its purpose and relevant entry conditions.
- **FLOW-03** MUST: Do not place Get, Create, Update, or Delete Records elements inside a Loop; retrieve data outside the loop and collect changes for bulk operations outside it, using a design compatible with the Flow type.
- **FLOW-04** MUST: For elements supporting fault connectors, provide appropriate fault handling for record changes and external actions; where a connector is unavailable, document how failures are surfaced, and never hide a failed operation behind a success path.
- **FLOW-05** MUST [auto]: Do not hardcode record IDs in Flow formulas, filters, or assignments; resolve records using verified stable identifiers or configuration.
- **FLOW-06** MUST: Choose before-save versus after-save execution according to the work required, define precise entry and re-entry criteria, and prevent unnecessary updates and recursive interactions with other automation.
- **FLOW-07** SHOULD: Store configurable business thresholds and mappings in Custom Metadata or other suitable configuration and user-facing text in Custom Labels where appropriate; ordinary boolean checks and stable literals do not automatically require configuration.
- **FLOW-08** MUST: Validate the Flow's intended execution context, permissions, bulk behavior, and failure paths; include relevant Flow versions and dependencies in the change and do not activate production changes without authorization.

## Lightning Web Components

- **LWC-01** SHOULD: Name new component folders in camelCase, for example `accountSummary`, consistent with Salesforce component naming constraints.
- **LWC-02** SHOULD [auto]: Do not retain `console.log` statements in committed code; use approved diagnostics when operational logging is required.
- **LWC-03** SHOULD: Prefer standard base components and Lightning Data Service for supported record operations; use wire adapters for reactive reads and imperative LDS functions for create/update/delete before adding custom Apex.
- **LWC-04** MUST: Keep components focused and reusable; preserve one-way data flow, do not mutate values received from wire adapters or parent components directly, and communicate changes through appropriate events.
- **LWC-05** MUST: Handle loading, empty, success, and error states; show understandable inline errors or supported toast messages, prevent unintended duplicate submissions, and avoid exposing stack traces or sensitive server details.
- **LWC-06** MUST: When Apex is used, enforce authorization on the server, keep cacheable methods read-only, and refresh the appropriate client data after mutations; client-side visibility checks do not grant access.
- **LWC-07** SHOULD: Use schema imports for known object/field references and accessible standard components; provide labels, keyboard interaction, and appropriate focus handling for custom UI.
- **LWC-08** MUST: Add or update relevant LWC tests for changed interactive behavior, including successful operations, errors, and events; follow the repository's Jest setup when available.

## Custom fields and metadata

- **FIELD-01** MUST [auto]: Name new ordinary custom fields using PascalCase words joined by underscores and the `__c` suffix, for example `Customer_Tier__c`; do not rename existing fields for style, and preserve Salesforce-defined suffixes and names for special field types and generated components.
- **FIELD-02** SHOULD [auto]: Every custom field has a meaningful `<description>` explaining its business purpose.
- **FIELD-03** SHOULD: Fields shown to users include useful `<inlineHelpText>` where the metadata supports it.
- **FIELD-04** MUST: Inspect existing fields before creating a near-duplicate; reuse a field only when its meaning, type, access, and lifecycle fit, and assess integrations, record-type availability, and automation before extending picklist values.
- **FIELD-05** MUST: Use Salesforce-supported API names and suffixes for each metadata type; `__r` is a relationship reference, not a substitute suffix for defining a custom lookup field.
- **FIELD-06** MUST: Include required metadata dependencies and relevant permission updates with a feature, and assess existing-data impact before adding required fields, restricting values, or changing field types.

## Validation rules

- **VR-01** SHOULD: Name new validation rules descriptively using PascalCase words separated by underscores, for example `Customer_Tier_Required_For_Customer`.
- **VR-02** MUST [auto]: Every validation rule has a non-empty `<errorMessage>` explaining the problem and how the user can correct it; automated presence checks do not establish message quality.
- **VR-03** SHOULD: Provide a meaningful `<description>` and use `<errorDisplayField>` when the error relates to one supported field.
- **VR-04** MUST: Assess validation rules against existing data, imports, integrations, and automation; implement bypasses only when explicitly required, using an appropriate permission-based mechanism rather than hardcoded users or profiles.

## Permissions, credentials, and logging

- **PERM-01** SHOULD: Grant feature access through purpose-named permission sets, for example `Account_Customer_Tier_Edit`, and follow existing permission-set-group conventions rather than adding profile-based grants.
- **PERM-02** MUST: Grant only the access required by the feature; do not add `Modify All Data` or `View All Data` to feature permission sets, and justify any object-level broad-access permission separately.
- **PERM-03** MUST: Include the object, field, Apex class, and other feature access actually needed, and test representative authorized and unauthorized users rather than relying solely on administrator execution.
- **SEC-01** MUST: Do not embed credentials, access tokens, passwords, or secrets in code, metadata, test fixtures, prompts, or logs; use Named Credentials/External Credentials or the project's approved secret-management mechanism.
- **SEC-02** MUST: Do not log sensitive personal data, tokens, or unrestricted request/response payloads; use safe identifiers and approved redaction, and return only data the caller is authorized to receive.
- **SEC-03** MUST: For external calls, define authentication, timeouts, response/error handling, bounded retry behavior where applicable, and idempotency for operations that could be repeated; use callout mocks in tests.

## Testing and delivery validation

- **TEST-01** MUST: Test required business outcomes with meaningful assertions, including relevant success, rejection, null/empty input, bulk, permission, and repeated-execution cases; coverage percentage alone is not evidence of correctness.
- **TEST-02** SHOULD: Reuse deterministic test factories and `@testSetup` where appropriate; avoid dependencies on existing org business records, execution order, and uncontrolled dates or external services.
- **TEST-03** MUST: Test asynchronous work with appropriate test boundaries and assert its resulting behavior; use mocks for callouts and verify error handling as well as successful responses.
- **TEST-04** MUST: Run applicable repository-configured static analysis, standards checks, Apex tests, LWC tests, and non-deploying deployment validation against an authorized non-production target; verify that the checker loads the intended standards file and recognizes applicable rule IDs/severities, report unsupported checks, and select tests based on changed components and dependencies. Never guess command arguments, org aliases, or test levels; if configuration is missing, report the gap.
- **TEST-05** MUST: Meet Salesforce coverage requirements for the chosen deployment test level and any stricter project gate; ordinary overall coverage requirements include at least 75% Apex coverage and some coverage for every trigger, while `RunSpecifiedTests` requires at least 75% coverage for each deployed class and trigger from the specified tests.
- **TEST-06** MUST: If tools, credentials, dependencies, or a validation org are unavailable, report exactly which checks remain unverified and provide the required follow-up; do not fabricate output or claim deployment readiness.

## Completion report

The agent's final delivery must state:

1. What changed and which requirement it addresses.
2. Files/components changed and required configuration or metadata dependencies.
3. Exact validation commands executed, their target and test level where applicable, their actual results, and coverage when measured; omit secrets from command output.
4. Applicable unresolved rule violations, exceptions, and assumptions.
5. Checks not executed and the reason, plus any required rollout or activation steps.
