@salesforce/afv-skills 1.5.1 → 1.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/README.md +16 -415
  2. package/package.json +5 -3
  3. package/skills/building-ui-bundle-app/SKILL.md +325 -0
  4. package/skills/building-ui-bundle-frontend/SKILL.md +122 -0
  5. package/skills/{building-webapp-react-components → building-ui-bundle-frontend}/implementation/component.md +1 -1
  6. package/skills/creating-b2b-commerce-store/SKILL.md +169 -0
  7. package/skills/creating-b2b-commerce-store/references/store-vs-storefront.md +169 -0
  8. package/skills/deploying-ui-bundle/SKILL.md +77 -0
  9. package/skills/generating-apex/CREDITS.md +30 -0
  10. package/skills/generating-apex/SKILL.md +335 -189
  11. package/skills/generating-apex/assets/abstract.cls +12 -8
  12. package/skills/generating-apex/assets/batch.cls +7 -7
  13. package/skills/generating-apex/assets/domain.cls +5 -5
  14. package/skills/generating-apex/assets/dto.cls +11 -11
  15. package/skills/generating-apex/assets/exception.cls +1 -1
  16. package/skills/generating-apex/assets/interface.cls +2 -2
  17. package/skills/generating-apex/assets/invocable.cls +115 -0
  18. package/skills/generating-apex/assets/queueable.cls +6 -6
  19. package/skills/generating-apex/assets/rest-resource.cls +300 -0
  20. package/skills/generating-apex/assets/schedulable.cls +7 -7
  21. package/skills/generating-apex/assets/selector.cls +7 -7
  22. package/skills/generating-apex/assets/service.cls +4 -4
  23. package/skills/generating-apex/assets/trigger.cls +45 -0
  24. package/skills/generating-apex/assets/utility.cls +5 -5
  25. package/skills/generating-apex/references/AccountDeduplicationBatch.cls +7 -7
  26. package/skills/generating-apex/references/AccountSelector.cls +10 -10
  27. package/skills/generating-apex/references/AccountService.cls +9 -9
  28. package/skills/generating-apex-test/CREDITS.md +30 -0
  29. package/skills/generating-apex-test/SKILL.md +165 -74
  30. package/skills/generating-apex-test/assets/test-class-template.cls +23 -54
  31. package/skills/generating-apex-test/assets/test-data-factory-template.cls +0 -1
  32. package/skills/generating-apex-test/references/assertion-patterns.md +38 -95
  33. package/skills/generating-apex-test/references/async-testing.md +59 -142
  34. package/skills/generating-apex-test/references/mocking-patterns.md +77 -76
  35. package/skills/generating-apex-test/references/test-data-factory.md +29 -130
  36. package/skills/generating-experience-react-site/SKILL.md +9 -9
  37. package/skills/generating-experience-react-site/docs/configure-metadata-digital-experience.md +1 -1
  38. package/skills/generating-flexipage/SKILL.md +28 -12
  39. package/skills/generating-ui-bundle-features/SKILL.md +45 -0
  40. package/skills/generating-ui-bundle-metadata/SKILL.md +106 -0
  41. package/skills/{managing-webapp-agentforce-conversation-client → implementing-ui-bundle-agentforce-conversation-client}/SKILL.md +5 -5
  42. package/skills/{managing-webapp-agentforce-conversation-client → implementing-ui-bundle-agentforce-conversation-client}/references/constraints.md +2 -2
  43. package/skills/{managing-webapp-agentforce-conversation-client → implementing-ui-bundle-agentforce-conversation-client}/references/examples.md +1 -1
  44. package/skills/{implementing-webapp-file-upload → implementing-ui-bundle-file-upload}/SKILL.md +11 -11
  45. package/skills/searching-media/SKILL.md +1 -1
  46. package/skills/{using-webapp-salesforce-data → using-ui-bundle-salesforce-data}/SKILL.md +52 -25
  47. package/skills/using-ui-bundle-salesforce-data/references/mutation-query-generation.md +140 -0
  48. package/skills/using-ui-bundle-salesforce-data/references/query-testing.md +78 -0
  49. package/skills/using-ui-bundle-salesforce-data/references/read-query-generation.md +307 -0
  50. package/skills/using-ui-bundle-salesforce-data/references/schema-introspection.md +53 -0
  51. package/skills/using-ui-bundle-salesforce-data/references/ui-bundle-integration.md +221 -0
  52. package/skills/{using-webapp-salesforce-data → using-ui-bundle-salesforce-data/scripts}/graphql-search.sh +75 -23
  53. package/skills/building-webapp-data-visualization/SKILL.md +0 -72
  54. package/skills/building-webapp-data-visualization/implementation/bar-line-chart.md +0 -316
  55. package/skills/building-webapp-data-visualization/implementation/dashboard-layout.md +0 -189
  56. package/skills/building-webapp-data-visualization/implementation/donut-chart.md +0 -181
  57. package/skills/building-webapp-data-visualization/implementation/stat-card.md +0 -150
  58. package/skills/building-webapp-react-components/SKILL.md +0 -96
  59. package/skills/configuring-webapp-csp-trusted-sites/SKILL.md +0 -90
  60. package/skills/configuring-webapp-metadata/SKILL.md +0 -158
  61. package/skills/creating-webapp/SKILL.md +0 -138
  62. package/skills/deploying-webapp-to-salesforce/SKILL.md +0 -226
  63. package/skills/installing-webapp-features/SKILL.md +0 -210
  64. /package/skills/{building-webapp-react-components → building-ui-bundle-frontend}/implementation/header-footer.md +0 -0
  65. /package/skills/{building-webapp-react-components → building-ui-bundle-frontend}/implementation/page.md +0 -0
  66. /package/skills/{configuring-webapp-csp-trusted-sites/implementation/metadata-format.md → generating-ui-bundle-metadata/implementation/csp-metadata-format.md} +0 -0
  67. /package/skills/{managing-webapp-agentforce-conversation-client → implementing-ui-bundle-agentforce-conversation-client}/references/style-tokens.md +0 -0
  68. /package/skills/{managing-webapp-agentforce-conversation-client → implementing-ui-bundle-agentforce-conversation-client}/references/troubleshooting.md +0 -0
@@ -1,105 +1,209 @@
1
1
  ---
2
2
  name: generating-apex
3
- description: Generate production-ready Apex classes for Salesforce following enterprise best practices. Covers service, selector, domain, batch, queueable, schedulable, DTO, utility, interface, abstract, and custom exception classes. Use this skill when the user asks to create, build, generate, scaffold, or refactor an Apex class. SCOPE Apex classes only does not apply to triggers or unit tests.
3
+ description: Primary 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.
4
4
  ---
5
5
 
6
- # Apex Class
6
+ # Generating Apex
7
7
 
8
- Generate well-structured, production-ready Apex classes for Salesforce development.
8
+ Use this skill for production-grade Apex: new classes, selectors, services, async jobs,
9
+ invocable methods, and triggers; and for evidence-based review of existing `.cls`.
9
10
 
10
- ## Scope
11
+ ## Required Inputs
11
12
 
12
- **Generates:**
13
- - Service classes (business logic layer)
14
- - Selector / query classes (SOQL encapsulation)
15
- - Domain classes (SObject-specific logic)
16
- - Batch Apex classes (`Database.Batchable`)
17
- - Queueable Apex classes (`Queueable`, optionally `Finalizer`)
18
- - Schedulable Apex classes (`Schedulable`)
19
- - DTO / wrapper / request-response classes
20
- - Utility / helper classes
21
- - Custom exception classes
22
- - Interfaces and abstract classes
13
+ Gather or infer before authoring:
23
14
 
24
- **Does NOT generate:**
25
- - Triggers (use a trigger framework skill)
26
- - Unit tests (use a test writer skill)
27
- - Aura controllers
28
- - LWC JavaScript controllers
15
+ - Class type (service, selector, domain, batch, queueable, schedulable, invocable, trigger, trigger action, DTO, utility, interface, abstract, exception, REST resource)
16
+ - Target object(s) and business goal
17
+ - Class name (derive using the naming table below)
18
+ - Net-new vs refactor/fix; any org/API constraints
19
+ - Deployment targets
20
+
21
+ Defaults unless specified:
22
+ - Sharing: `with sharing` (see sharing rules per type below)
23
+ - Access: `public` (use `global` only when required by managed packages or `@InvocableMethod`)
24
+ - API version: `66.0` (minimum version)
25
+ - ApexDoc comments: yes
26
+
27
+ If the user provides a clear, complete request, generate immediately without unnecessary back-and-forth.
29
28
 
30
29
  ---
31
30
 
32
- ## Gathering Requirements
31
+ ## Workflow
33
32
 
34
- Before generating code, gather these inputs from the user (ask if not provided):
33
+ All steps are sequential. Do not skip, merge, or reorder. If blocked, stop and ask for missing context. If not applicable, mark `N/A` with a one-line justification in the report.
35
34
 
36
- 1. **Class type**Service, Selector, Batch, Queueable, Schedulable, Domain, DTO, Utility, Interface, Abstract, Exception
37
- 2. **Class name** — or enough context to derive a meaningful name
38
- 3. **SObject(s) involved** — if applicable
39
- 4. **Business requirements** — plain-language description of what the class should do
40
- 5. **Optional preferences:**
41
- - Sharing model (`with sharing`, `without sharing`, `inherited sharing`)
42
- - Access modifier (`public` or `global`)
43
- - API version (default: `62.0`)
44
- - Whether to include ApexDoc comments (default: yes)
35
+ ### Phase 1Author
45
36
 
46
- If the user provides a clear, complete request, generate immediately without unnecessary back-and-forth.
37
+ 1. **Discover project conventions**
38
+ - Service-Selector-Domain layering, logging utilities
39
+ - Existing classes/triggers and current trigger framework or handler pattern
40
+ - Whether Trigger Actions Framework (TAF) is already in use
41
+
42
+ 2. **Choose the smallest correct pattern** (see Type-Specific Guidance below)
43
+
44
+ 3. **Review templates and assets**
45
+ - Read the matching template from `assets/` before authoring (see Type-Specific Guidance for the file mapping)
46
+ - When a `references/` example exists for the type, read it as a concrete style guide
47
+ - For any test class work, always read and use `generating-apex-test` skill
48
+
49
+ 4. **Author with guardrails** -- apply every rule in the Rules section below
50
+ - Generate `{ClassName}.cls` with ApexDoc
51
+ - Generate `{ClassName}.cls-meta.xml`
52
+
53
+ 5. **Generate test classes** -- delegate to `generating-apex-test` to create `{ClassName}Test.cls` and `{ClassName}Test.cls-meta.xml`. Do not write test code in this skill. If the test skill is unavailable, record `test_skill=unavailable: <reason>` in Step 8.
54
+
55
+ ### Phase 2 — Validate (required before reporting)
56
+
57
+ Writing files is the midpoint, not the finish line. Steps 6 and 7 each require a tool invocation and produce output that must appear in the Step 8 report. Do not summarize or present the report until both steps have run and their output is captured.
58
+
59
+ 6. **Run code analyzer**
60
+ - Invoke MCP `run_code_analyzer` on all generated/updated `.cls` files.
61
+ - Remediate all `sev0`, `sev1`, and `sev2` violations; re-run until clean.
62
+ - Capture the final tool output verbatim for the report.
63
+ - Fallback: `sf code-analyzer run --target <target>`. If both are unavailable, record `run_code_analyzer=unavailable: <error>` in the report.
64
+
65
+ 7. **Execute Apex tests**
66
+ - Run org tests including `{ClassName}Test` via `sf apex run test` or MCP.
67
+ - Delegate all test fixes/coverage work to `generating-apex-test`; iterate until green.
68
+ - Capture pass/fail counts and coverage percentage for the report.
69
+ - If unavailable, record `test_execution=unavailable: <error>` in the report.
70
+
71
+ ### Phase 3 — Report
72
+
73
+ 8. **Report** -- use the output format at the bottom of this file.
74
+ - The `Analyzer` line must contain the actual Step 6 tool output (or `run_code_analyzer=unavailable: <reason>` after attempting invocation).
75
+ - The `Testing` line must contain the actual Step 7 results (or `test_execution=unavailable: <reason>` after attempting invocation).
76
+ - A report missing either line is incomplete. Always attempt the tool invocation before recording unavailable.
47
77
 
48
78
  ---
49
79
 
50
- ## Code Standards — ALWAYS Follow These
80
+ ## Rules
81
+
82
+ ### Hard-Stop Constraints (Must Enforce)
83
+
84
+ If any constraint would be violated in generated code, **stop and explain the problem** before proceeding:
85
+
86
+ | Constraint | Rationale |
87
+ |---|---|
88
+ | Place all SOQL outside loops | Avoid query governor limits (100 queries) |
89
+ | Place all DML outside loops | Avoid DML governor limits (150 statements) |
90
+ | Declare a sharing keyword on every class | Prevent unintended `without sharing` defaults and data exposure |
91
+ | Use Custom Metadata/Labels/describe calls instead of hardcoded IDs | Ensure portability across orgs |
92
+ | Always handle exceptions (log, rethrow, or recover) | Prevent silent failures |
93
+ | Use bind variables for all dynamic SOQL with user input | Prevent SOQL injection |
94
+ | Use Apex-native collections (`List`, `Map`, `Set`) rather than Java types | Prevent compile errors |
95
+ | Verify methods exist in Apex before use | Prevent reliance on non-existent APIs |
96
+ | Prefer structured logging over `System.debug()` | Debug string concatenation consumes CPU even when not observed |
97
+ | Never use `@future` methods | Use Queueable with `System.Finalizer`; `@future` cannot chain, cannot be called from Batch, and cannot accept non-primitive types |
98
+
99
+ ### Bulkification & Governor Limits
100
+
101
+ - All public APIs accept and process collections; single-record overloads delegate to the bulk method
102
+ - In batch/bulk flows, prefer partial-success DML (`Database.update(records, false)`) and process `SaveResult` for errors
103
+ - Use `Map<Id, SObject>` constructor for efficient ID-based lookups from query results
104
+ - Use `Map<Id, List<SObject>>` to group child records by parent; build the map in a single loop before processing
105
+ - Use `Set<Id>` for deduplication and membership checks; prefer `Set.contains()` over `List.contains()`
106
+ - Use relationship subqueries to fetch parent + child records in a single SOQL when both are needed
107
+ - Use `AggregateResult` with `GROUP BY` for rollup calculations instead of querying and counting in Apex
108
+ - Only DML records that actually changed — compare against `Trigger.oldMap` or prior state before adding to the update list
109
+ - Use `Limits.getQueries()`, `Limits.getDmlStatements()`, `Limits.getCpuTime()` to monitor consumption in complex transactions
110
+
111
+ ### SOQL Optimization
112
+
113
+ - Use selective queries with proper `WHERE` clauses; use indexed fields (`Id`, `Name`, `OwnerId`, lookup/master-detail fields, `ExternalId` fields, custom indexes) in filters when possible
114
+ - `SELECT *` does not exist in SOQL -- always specify the exact fields needed
115
+ - Apply `LIMIT` clauses to bound result sets; use `ORDER BY` for deterministic results
116
+ - When querying Custom Metadata Types (objects ending with `__mdt`), do NOT use SOQL — use the built-in methods (`{CustomMdt__mdt}.getAll().values()`, `getInstance()`, etc.)
117
+
118
+ ### Caching
119
+
120
+ - Use Platform Cache (`Cache.Org` / `Cache.Session`) for frequently accessed, rarely changed data; set a TTL and always handle cache misses — cache can be evicted at any time
121
+ - Use `private static Map` fields as transaction-scoped caches to prevent duplicate queries within the same execution context; lazy-initialize on first access
51
122
 
52
- ### Separation of Concerns
53
- - **Service classes** contain business logic. They call Selectors for data and may call Domain classes for SObject-specific behavior.
54
- - **Selector classes** encapsulate all SOQL queries. Services never contain inline SOQL.
55
- - **Domain classes** encapsulate SObject-specific logic (field defaults, validation, transformation).
56
- - Keep classes focused on a single responsibility.
123
+ ### Security
57
124
 
58
- ### Bulkification
59
- - All methods must operate on collections (`List`, `Set`, `Map`) by default.
60
- - Never accept a single SObject when a `List<SObject>` is appropriate.
61
- - Provide convenience overloads for single-record callers only when it makes the API cleaner, and have them delegate to the bulk method.
125
+ - Default to `with sharing`; document justification for `without sharing` or `inherited sharing`
126
+ - `WITH USER_MODE` in SOQL and `AccessLevel.USER_MODE` for `Database` DML for CRUD/FLS enforcement
127
+ - Validate dynamic field/operator names via allowlist or `Schema.describe`
128
+ - Named Credentials for all external credentials/API keys
129
+ - `AuraHandledException` for `@AuraEnabled` user-facing errors (no internal details)
130
+ - `without sharing` requires a Custom Permission check
131
+ - Isolate `without sharing` logic in dedicated helper classes; call from `with sharing` entry points to limit elevated-access scope
132
+ - Encrypt PII/sensitive data at rest via Platform Encryption; never expose PII in debug statements, error messages, or API responses
62
133
 
63
- ### Governor Limit Safety
64
- - **No SOQL or DML inside loops.** Ever.
65
- - Collect IDs/records first, query/DML once outside the loop.
66
- - Use `Limits` class checks in batch/bulk operations where appropriate.
67
- - Prefer `Database.insert(records, false)` with error handling in batch contexts.
134
+ ### Security Verification
68
135
 
69
- ### Sharing Model
70
- - Default to `with sharing` unless the user specifies otherwise.
71
- - If `without sharing` or `inherited sharing` is used, add an ApexDoc `@description` comment explaining WHY.
136
+ Before finalizing, verify: CRUD/FLS enforced (SOQL + DML) · explicit sharing keyword on every class · no hardcoded secrets or Record IDs · PII excluded from logs and error messages · error messages sanitized for end users.
137
+
138
+ ### Error Handling
139
+
140
+ - Catch specific exceptions before generic `Exception`; include context in messages
141
+ - Use `try/catch` only around code that can throw (DML, callouts, JSON parsing, casts); avoid defensive wrapping of simple assignments/collection ops/arithmetic
142
+ - Preserve exception cause chains: `new CustomException('message', cause)` (do not replace stack trace with concatenated messages)
143
+ - Provide a custom exception class per service domain when meaningful
144
+ - In `@AuraEnabled` methods, catch exceptions and rethrow as `AuraHandledException`
145
+
146
+ ### Null Safety
147
+
148
+ - Add guard clauses for null/empty inputs at the top of every public method; match style to context: `return` early in private/trigger-handler methods, `throw` exceptions in public APIs, `record.addError()` in validation services
149
+ - Return empty collections instead of `null`
150
+ - Use safe navigation (`?.`) for chained property access
151
+ - Never dereference `map.get(key)` inline unless presence is guaranteed; use `containsKey`, assignment+null check, or safe navigation first
152
+ - Use null coalescing (`??`) for default values
153
+ - Prefer `String.isBlank(value)` over manual checks like `value == null || value.trim().isEmpty()`
154
+
155
+ ### Constants & Literals
156
+
157
+ - Use enums over string constants whenever possible; enum values follow `UPPER_SNAKE_CASE`
158
+ - Extract repeated literal strings/numbers into `private static final` constants or a constants class
159
+ - Use `Label.` custom labels for user-facing strings
160
+ - Use Custom Metadata for configurable values (thresholds, mappings, feature flags)
161
+ - Never output HTML-escaped entities in code (e.g., `&#39;`); use literal single quotes `'` in Apex string literals
72
162
 
73
163
  ### Naming Conventions
74
164
 
75
- | Class Type | Pattern | Example |
76
- |-------------|-------------------------------|-------------------------------|
77
- | Service | `{SObject}Service` | `AccountService` |
78
- | Selector | `{SObject}Selector` | `AccountSelector` |
79
- | Domain | `{SObject}Domain` | `OpportunityDomain` |
80
- | Batch | `{Descriptive}Batch` | `AccountDeduplicationBatch` |
81
- | Queueable | `{Descriptive}Queueable` | `ExternalSyncQueueable` |
82
- | Schedulable | `{Descriptive}Schedulable` | `DailyCleanupSchedulable` |
83
- | DTO | `{Descriptive}DTO` | `AccountMergeRequestDTO` |
84
- | Wrapper | `{Descriptive}Wrapper` | `OpportunityLineWrapper` |
85
- | Utility | `{Descriptive}Util` | `StringUtil`, `DateUtil` |
86
- | Interface | `I{Descriptive}` | `INotificationService` |
87
- | Abstract | `Abstract{Descriptive}` | `AbstractIntegrationService` |
88
- | Exception | `{Descriptive}Exception` | `AccountServiceException` |
89
-
90
- ### ApexDoc Comments
91
- Include ApexDoc on every `public` and `global` method and on the class itself:
165
+ | Type | Pattern | Example |
166
+ |---|---|---|
167
+ | Service | `{SObject}Service` | `AccountService` |
168
+ | Selector | `{SObject}Selector` | `AccountSelector` |
169
+ | Domain | `{SObject}Domain` | `OpportunityDomain` |
170
+ | Batch | `{Descriptive}Batch` | `AccountDeduplicationBatch` |
171
+ | Queueable | `{Descriptive}Queueable` | `ExternalSyncQueueable` |
172
+ | Schedulable | `{Descriptive}Schedulable` | `DailyCleanupSchedulable` |
173
+ | DTO | `{Descriptive}DTO` | `AccountMergeRequestDTO` |
174
+ | Wrapper | `{Descriptive}Wrapper` | `OpportunityLineWrapper` |
175
+ | Utility | `{Descriptive}Util` | `StringUtil` |
176
+ | Interface | `I{Descriptive}` | `INotificationService` |
177
+ | Abstract | `Abstract{Descriptive}` | `AbstractIntegrationService` |
178
+ | Exception | `{Descriptive}Exception` | `AccountServiceException` |
179
+ | REST Resource | `{SObject}RestResource` | `AccountRestResource` |
180
+ | Trigger | `{SObject}Trigger` | `AccountTrigger` |
181
+ | Trigger Action | `TA_{SObject}_{Action}` | `TA_Account_SetDefaults` |
182
+
183
+ Additional naming rules:
184
+ - Classes: `PascalCase`
185
+ - Methods: `camelCase`, start with a verb (`get`, `create`, `process`, `validate`, `is`, `has`, `can`)
186
+ - Variables: `camelCase`, descriptive nouns; Lists as plural nouns (e.g., `accounts`, `relatedContacts`); Maps as `{value}By{key}` (e.g., `accountsById`); Sets as `{noun}Ids`
187
+ - Constants: `UPPER_SNAKE_CASE`
188
+ - Use full descriptive names instead of abbreviations (`acc`, `tks`, `rec`)
189
+
190
+ ### ApexDoc
191
+
192
+ - Required on the class header and every `public`/`global` method
193
+ - Include: brief description, `@param`, `@return`, `@throws`, `@example` where helpful
194
+
195
+ Class-level format:
92
196
 
93
197
  ```apex
94
198
  /**
95
- * @description Brief description of what the class does
96
- * @author Generated by Apex Class Writer Skill
199
+ * @author Generated by Apex Skill
97
200
  */
98
201
  ```
99
202
 
203
+ Method-level format:
204
+
100
205
  ```apex
101
206
  /**
102
- * @description Brief description of what the method does
103
207
  * @param paramName Description of the parameter
104
208
  * @return Description of the return value
105
209
  * @example
@@ -107,36 +211,153 @@ Include ApexDoc on every `public` and `global` method and on the class itself:
107
211
  */
108
212
  ```
109
213
 
110
- ### Null Safety
111
- - Use guard clauses at the top of methods for null/empty inputs.
112
- - Use safe navigation (`?.`) where appropriate.
113
- - Return empty collections rather than `null`.
214
+ ### Code Structure & Architecture
114
215
 
115
- ### Constants
116
- - No magic strings or numbers in logic.
117
- - Use `private static final` constants or a dedicated constants class.
118
- - Use `Label.` custom labels for user-facing strings when appropriate.
216
+ - Single responsibility per class; max 500 lines -- split when exceeded
217
+ - Return Early: validate preconditions at method top, return/throw immediately
218
+ - Extract private helpers for methods over ~40 lines
219
+ - Use Dependency Injection (constructor/method params) for testability
220
+ - Prefer composition and narrow interfaces over deep inheritance; extend via new implementations, not modifications
221
+ - Enforce single-level abstraction per method across layer boundaries:
119
222
 
120
- ### Custom Exceptions
121
- - Each service class should define or reference a corresponding custom exception.
122
- - Inner exception classes are preferred for simple cases: `public class AccountServiceException extends Exception {}`
123
- - Include meaningful error messages with context.
223
+ | Layer | Owns | Must NOT contain |
224
+ |---|---|---|
225
+ | Trigger | Event routing only | Business logic, orchestration |
226
+ | Handler/Service | Flow control, coordination | Inline SOQL/DML/HTTP/parsing |
227
+ | Domain | Business rules, validation | Queries, callouts, persistence details |
228
+ | Data/Integration | SOQL, DML, HTTP | Business decisions |
124
229
 
125
- ### Error Handling
126
- - Catch specific exceptions, not generic `Exception` unless re-throwing.
127
- - Log errors meaningfully (assume a logging utility exists or stub one).
128
- - In batch contexts, use `Database.SaveResult` / `Database.UpsertResult` with partial success.
230
+ - Disallowed: methods mixing orchestration with inline SOQL/DML/HTTP; business rules mixed with parsing internals; validation + persistence + cross-system plumbing in one method
129
231
 
130
232
  ---
131
233
 
132
- ## Output Format
234
+ ## Async Decision Matrix
133
235
 
134
- For every class, produce TWO files:
236
+ | Scenario | Default | Key Traits |
237
+ |---|---|---|
238
+ | Standard async work | **Queueable** | Job ID, chaining, non-primitive types, configurable delay (up to 10 min via `AsyncOptions`), dedup signatures |
239
+ | Very large datasets | **Batch Apex** | Chunked processing, max 5 concurrent; use `QueryLocator` for large scopes |
240
+ | Modern batch alternative | **CursorStep** (`Database.Cursor`) | 2000-record chunks, higher throughput, no 5-job limit |
241
+ | Recurring schedule | **Scheduled Flow** (preferred) or **Schedulable** | Schedulable has 100-job limit; use only when chaining to Batch or needing complex Apex logic |
242
+ | Post-job cleanup | **Finalizer** (`System.Finalizer`) | Runs regardless of Queueable success/failure |
243
+ | Long-running callouts | **Continuation** | Up to 3 per transaction, 3 parallel |
244
+ | Delays > 10 minutes | `System.scheduleBatch()` | Schedule a Batch job at a specific future time |
245
+ | Legacy fire-and-forget | `@future` | **Do not use in new code** — see Hard-Stop Constraints; replace with Queueable + Finalizer |
135
246
 
136
- 1. **`{ClassName}.cls`** — The Apex class source code
137
- 2. **`{ClassName}.cls-meta.xml`** — The metadata file
247
+ ---
248
+
249
+ ## Type-Specific Guidance
250
+
251
+ ### Service
252
+ - Template: `assets/service.cls` · Reference: `references/AccountService.cls`
253
+ - `with sharing`; stateless — no `public` fields or mutable instance state; keep public APIs focused and `static` where reasonable
254
+ - Delegate all SOQL to Selectors and SObject behavior to Domains
255
+ - Wrap business errors in a custom exception (e.g., `AccountServiceException`)
256
+
257
+ ### Selector
258
+ - Template: `assets/selector.cls` · Reference: `references/AccountSelector.cls`
259
+ - `inherited sharing`; one per SObject or query domain
260
+ - Return `List<SObject>` or `Map<Id, SObject>`; use a shared base field list constant (no inline duplication)
261
+ - Accept filter parameters; always include `WITH USER_MODE`
262
+
263
+ ### Domain
264
+ - Template: `assets/domain.cls`
265
+ - `with sharing`; encapsulate field defaults, derivations, and validations
266
+ - Operate on in-memory lists only; no SOQL/DML (belongs in Services/Selectors)
267
+
268
+ ### Batch
269
+ - Template: `assets/batch.cls` · Reference: `references/AccountDeduplicationBatch.cls`
270
+ - `with sharing`; implement `Database.Batchable<SObject>` (add `Database.Stateful` when tracking across chunks)
271
+ - `start()` = query definition; `execute()` = business logic; `finish()` = logging/notification
272
+ - Use `QueryLocator` for large datasets; handle partial failures via `Database.SaveResult`
273
+ - Accept filter parameters via constructor for reusability
274
+
275
+ ### Queueable
276
+ - Template: `assets/queueable.cls`
277
+ - `with sharing`; implement `Queueable` and optionally `Database.AllowsCallouts` when HTTP callouts are needed
278
+ - Accept data via constructor
279
+ - Add chain-depth guards to prevent infinite chains
280
+ - Optionally implement `Finalizer` for recovery/cleanup
281
+ - Use `AsyncOptions` for configurable delay (up to 10 min) and dedup signatures
282
+
283
+ ### Schedulable
284
+ - Template: `assets/schedulable.cls`
285
+ - `with sharing`; `execute()` delegates to Queueable or Batch
286
+ - Provide CRON constants and a convenience `scheduleDaily()` helper
287
+
288
+ ### DTO / Wrapper
289
+ - Template: `assets/dto.cls`
290
+ - No sharing keyword needed (pure data containers)
291
+ - Simple public properties; no-arg + parameterized constructors; `Comparable` when ordering matters
292
+ - Use `@JsonAccess` on private/protected inner DTOs that are serialized/deserialized
293
+
294
+ ### Utility
295
+ - Template: `assets/utility.cls`
296
+ - No sharing keyword needed; all methods `public static`; `private` constructor
297
+ - Pure, side-effect-free; no SOQL/DML
298
+
299
+ ### Interface
300
+ - Template: `assets/interface.cls`
301
+ - Define clear contracts with ApexDoc on each method signature
302
+
303
+ ### Abstract
304
+ - Template: `assets/abstract.cls`
305
+ - `with sharing`; offer default behavior via `virtual` methods
306
+ - Mark extension points `protected virtual` or `protected abstract`
307
+ - Include a concrete example in the ApexDoc showing how to extend the class
308
+
309
+ ### Custom Exception
310
+ - Template: `assets/exception.cls`
311
+ - No sharing keyword; extend `Exception` with descriptive names
312
+ - Supported constructors: `()`, `('msg')`, `(cause)`, `('msg', cause)`
313
+
314
+ ### Trigger
315
+ - Template: `assets/trigger.cls`
316
+ - One trigger per object; delegate all logic to handler/TAF action classes
317
+ - Include all relevant DML contexts; if TAF: `new MetadataTriggerHandler().run();`
318
+
319
+ ### Trigger Action (TAF)
320
+ - One class per concern per context; implement `TriggerAction.{Context}`
321
+ - Register via `Trigger_Action__mdt` (actions are inactive without registration)
322
+ - Name: `TA_{SObject}_{ActionName}`; prefer field-value comparison over static booleans for recursion
323
+
324
+ ### Invocable Method (`@InvocableMethod`)
325
+ - Template: `assets/invocable.cls`
326
+ - `with sharing`; inner `Request`/`Response` with `@InvocableVariable`
327
+ - Method must be `public static`; non-static or single-object signatures will not compile
328
+ - Accept `List<Request>`, return `List<Response>`; bulkify (SOQL/DML outside loops)
329
+ - Decorator parameters: `label` (required — Flow Builder display name), `description`, `category` (groups actions in Builder), `callout=true` (required when method makes HTTP callouts)
330
+ - `@InvocableVariable` parameters: `label` (required), `description`, `required=true/false`
331
+ - `@InvocableVariable` supports: primitives, `Id`, `SObject`, `List<T>` only (no `Map`/`Set`/`Blob`); use `List<Id>` or `List<SObject>` fields for Flow collection I/O
332
+ - Always include `isSuccess`, `errorMessage`, and `errorType` (`e.getTypeName()`) in Response
333
+ - Return errors in Response (recommended); throwing an exception triggers the Flow Fault path — reserve for unrecoverable failures only
334
+
335
+ ### REST Resource (`@RestResource`)
336
+ - Template: `assets/rest-resource.cls`
337
+ - `global with sharing`; both class and methods must be `global`
338
+ - Versioned URL: `@RestResource(urlMapping='/{resource}/v1/*')`
339
+ - Use proper HTTP status codes per branch (`200`/`201`/`400`/`404`/`422`/`500`); never default all errors to `500`
340
+ - Validate inputs (Id format: `Pattern.matches('[a-zA-Z0-9]{15,18}', value)`); bind all user input in SOQL
341
+ - Include `LIMIT`/`ORDER BY` in queries; implement pagination (`pageSize`/`offset`)
342
+ - Standardized `ApiResponse` wrapper (`success`, `message`, `data`/`records`); inner request/response DTOs
343
+ - Thin controller: delegate business logic to Service classes
344
+
345
+ ### `@AuraEnabled` Controller
346
+ - `with sharing`; use `WITH USER_MODE` in all SOQL
347
+ - Use `@AuraEnabled(cacheable=true)` only for read-only queries; leave `cacheable` unset for DML operations
348
+ - Catch exceptions and rethrow as `AuraHandledException` with user-friendly messages
349
+
350
+ ---
351
+
352
+ ## Output Expectations
353
+
354
+ Deliverables per class:
355
+ - `{ClassName}.cls`
356
+ - `{ClassName}.cls-meta.xml` (default API version `66.0` or higher unless specified)
357
+ - `{ClassName}Test.cls` (generated via `generating-apex-test` skill)
358
+ - `{ClassName}Test.cls-meta.xml` (generated via `generating-apex-test` skill)
138
359
 
139
- ### Meta XML Template
360
+ Meta XML template:
140
361
 
141
362
  ```xml
142
363
  <?xml version="1.0" encoding="UTF-8"?>
@@ -146,108 +367,33 @@ For every class, produce TWO files:
146
367
  </ApexClass>
147
368
  ```
148
369
 
149
- Default `apiVersion` is `62.0` unless the user specifies otherwise.
150
-
151
- ---
152
-
153
- ## Class Type–Specific Instructions
154
-
155
- ### Service Classes
156
- - Read and follow: `assets/service.cls`
157
- - Stateless no instance variables holding mutable state
158
- - All public methods should be `static` unless there's a compelling reason for instance methods
159
- - Delegate queries to a Selector class
160
- - Wrap business logic errors in a custom exception
161
-
162
- ### Selector Classes
163
- - Read and follow: `assets/selector.cls`
164
- - One Selector per SObject (or per logical query domain)
165
- - Return `List<SObject>` or `Map<Id, SObject>`
166
- - Accept filter criteria as method parameters, not hardcoded
167
- - Include a private method that returns the base field list to keep DRY
168
-
169
- ### Domain Classes
170
- - Read and follow: `assets/domain.cls`
171
- - Encapsulate field-level defaults, derivations, and validations
172
- - Operate on `List<SObject>` — designed to be called from triggers or services
173
- - No SOQL or DML — only in-memory SObject manipulation
174
-
175
- ### Batch Classes
176
- - Read and follow: `assets/batch.cls`
177
- - Implement `Database.Batchable<SObject>` and optionally `Database.Stateful`
178
- - Use `Database.QueryLocator` in `start()` for large datasets
179
- - Handle partial failures in `execute()` using `Database.SaveResult`
180
- - Implement meaningful `finish()` — at minimum, log completion
181
-
182
- ### Queueable Classes
183
- - Read and follow: `assets/queueable.cls`
184
- - Implement `Queueable` and optionally `Database.AllowsCallouts`
185
- - Accept data through the constructor — queueables are stateful
186
- - For chaining, include guard logic to prevent infinite chains
187
- - Optionally implement `Finalizer` for error recovery
188
-
189
- ### Schedulable Classes
190
- - Read and follow: `assets/schedulable.cls`
191
- - Implement `Schedulable`
192
- - Keep `execute()` lightweight — delegate to a Batch or Queueable
193
- - Include a static method that returns a CRON expression for convenience
194
- - Document the expected schedule in ApexDoc
195
-
196
- ### DTO / Wrapper Classes
197
- - Read and follow: `assets/dto.cls`
198
- - Use `public` properties — no getters/setters unless validation is needed
199
- - Include a no-arg constructor and optionally a parameterized constructor
200
- - Implement `Comparable` if sorting is needed
201
- - Keep them serialization-friendly (no transient state unless intentional)
202
-
203
- ### Utility Classes
204
- - Read and follow: `assets/utility.cls`
205
- - All methods `public static`
206
- - Class should be `public with sharing` with a `private` constructor to prevent instantiation
207
- - Group related utilities (e.g., `StringUtil`, `DateUtil`, `CollectionUtil`)
208
- - Every method must be side-effect-free (no DML, no SOQL)
209
-
210
- ### Interfaces
211
- - Read and follow: `assets/interface.cls`
212
- - Define the contract clearly with ApexDoc on every method signature
213
- - Use meaningful names that describe the capability: `INotificationService`, `IRetryable`
214
-
215
- ### Abstract Classes
216
- - Read and follow: `assets/abstract.cls`
217
- - Provide default implementations for common behavior
218
- - Mark extension points as `protected virtual` or `protected abstract`
219
- - Include a concrete example in the ApexDoc showing how to extend
220
-
221
- ### Custom Exceptions
222
- - Read and follow: `assets/exception.cls`
223
- - Extend `Exception`
224
- - Keep them simple — Apex exceptions don't support custom constructors well
225
- - Name them descriptively: `AccountServiceException`, `IntegrationTimeoutException`
370
+ Report in this order:
371
+
372
+ ```text
373
+ Apex work: <summary>
374
+ Files: <paths>
375
+ Design: <pattern / framework choices>
376
+ Workflow: all steps completed (1-8); any N/A justified
377
+ Risks: <security, bulkification, async, dependency notes>
378
+ Analyzer: <REQUIRED -- paste actual run_code_analyzer output or state "run_code_analyzer=unavailable: <reason>">
379
+ Testing: <REQUIRED -- paste actual test execution results (pass/fail, coverage) or state "test_execution=unavailable: <reason>">
380
+ Deploy: <dry-run or next step>
381
+ ```
226
382
 
227
383
  ---
228
384
 
229
- ## Generation Workflow
385
+ ## Cross-Skill Integration
230
386
 
231
- 1. Determine the class type from the user's request
232
- 2. Read the corresponding template from `assets/`
233
- 3. Read relevant examples from `references/` if the class type has one
234
- 4. Apply the user's requirements to the template pattern
235
- 5. Generate the `.cls` file with full ApexDoc
236
- 6. Generate the `.cls-meta.xml` file
237
- 7. Present both files to the user
238
- 8. Include a brief note on design decisions if any non-obvious choices were made
387
+ | Need | Delegate to |
388
+ |---|---|
389
+ | Apex tests / fix failures | `generating-apex-test` skill |
390
+ | Describe objects/fields | metadata skill (if available) |
391
+ | Deploy to org | deploy skill (if available) |
392
+ | Flow calling Apex | Flow skill (if available) |
393
+ | LWC calling Apex | LWC skill (if available) |
239
394
 
240
395
  ---
241
396
 
242
- ## Anti-Patterns to Avoid
243
-
244
- - SOQL or DML inside loops
245
- - ❌ Hardcoded IDs or record type names (use `Schema.SObjectType` or Custom Metadata)
246
- - ❌ God classes that mix query + logic + DML
247
- - ❌ `public` fields on service classes
248
- - ❌ Returning `null` from methods that should return collections
249
- - ❌ Generic `catch (Exception e)` without re-throwing or meaningful handling
250
- - ❌ Business logic in Batch `start()` methods
251
- - ❌ Tight coupling between classes — use interfaces for extensibility
252
- - ❌ Magic strings or numbers
253
- - ❌ Methods longer than ~40 lines — break them into private helpers
397
+ ## Troubleshooting Boundary
398
+
399
+ This skill handles production `.cls`/`.trigger` issues only: compile/parse failures, deployment dependency errors, runtime governor-limit failures. For test execution, assertions, coverage, or `sf apex run test` failures, delegate to `generating-apex-test`.