@salesforce/afv-skills 1.1.0 → 1.2.0

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 (103) hide show
  1. package/package.json +4 -4
  2. package/skills/agentforce-development/SKILL.md +427 -0
  3. package/skills/agentforce-development/assets/README-legacy.md +89 -0
  4. package/skills/agentforce-development/assets/agent-spec-template.md +90 -0
  5. package/skills/agentforce-development/assets/agents/README.md +45 -0
  6. package/skills/agentforce-development/assets/agents/hello-world.agent +60 -0
  7. package/skills/agentforce-development/assets/agents/multi-topic.agent +105 -0
  8. package/skills/agentforce-development/assets/agents/production-faq.agent +101 -0
  9. package/skills/agentforce-development/assets/agents/production-faq.bundle-meta.xml +4 -0
  10. package/skills/agentforce-development/assets/agents/simple-qa.agent +72 -0
  11. package/skills/agentforce-development/assets/apex/models-api-queueable.cls +225 -0
  12. package/skills/agentforce-development/assets/bundle-meta.xml +23 -0
  13. package/skills/agentforce-development/assets/components/apex-action.agent +52 -0
  14. package/skills/agentforce-development/assets/components/error-handling.agent +58 -0
  15. package/skills/agentforce-development/assets/components/escalation-setup.agent +169 -0
  16. package/skills/agentforce-development/assets/components/flow-action.agent +66 -0
  17. package/skills/agentforce-development/assets/components/n-ary-conditions.agent +110 -0
  18. package/skills/agentforce-development/assets/components/topic-with-actions.agent +40 -0
  19. package/skills/agentforce-development/assets/deterministic-routing.agent +166 -0
  20. package/skills/agentforce-development/assets/escalation-pattern.agent +209 -0
  21. package/skills/agentforce-development/assets/flow-action-lookup.agent +115 -0
  22. package/skills/agentforce-development/assets/hub-and-spoke.agent +104 -0
  23. package/skills/agentforce-development/assets/invocable-apex-template.cls +187 -0
  24. package/skills/agentforce-development/assets/local-info-agent-annotated.agent +355 -0
  25. package/skills/agentforce-development/assets/metadata/basic-prompt-template.promptTemplate-meta.xml +109 -0
  26. package/skills/agentforce-development/assets/metadata/genai-function-apex.xml +92 -0
  27. package/skills/agentforce-development/assets/metadata/genai-function-flow.xml +57 -0
  28. package/skills/agentforce-development/assets/metadata/genai-plugin.xml +72 -0
  29. package/skills/agentforce-development/assets/metadata/http-callout-flow.flow-meta.xml +348 -0
  30. package/skills/agentforce-development/assets/metadata/record-grounded-prompt.promptTemplate-meta.xml +136 -0
  31. package/skills/agentforce-development/assets/minimal-starter.agent +42 -0
  32. package/skills/agentforce-development/assets/patterns/README.md +254 -0
  33. package/skills/agentforce-development/assets/patterns/action-callbacks.agent +178 -0
  34. package/skills/agentforce-development/assets/patterns/advanced-input-bindings.agent +141 -0
  35. package/skills/agentforce-development/assets/patterns/bidirectional-routing.agent +156 -0
  36. package/skills/agentforce-development/assets/patterns/critical-input-collection.agent +244 -0
  37. package/skills/agentforce-development/assets/patterns/delegation-routing.agent +89 -0
  38. package/skills/agentforce-development/assets/patterns/lifecycle-events.agent +127 -0
  39. package/skills/agentforce-development/assets/patterns/llm-controlled-actions.agent +184 -0
  40. package/skills/agentforce-development/assets/patterns/multi-step-workflow.agent +282 -0
  41. package/skills/agentforce-development/assets/patterns/open-gate-routing.agent +286 -0
  42. package/skills/agentforce-development/assets/patterns/procedural-instructions.agent +273 -0
  43. package/skills/agentforce-development/assets/patterns/prompt-template-action.agent +188 -0
  44. package/skills/agentforce-development/assets/patterns/system-instruction-overrides.agent +293 -0
  45. package/skills/agentforce-development/assets/prompt-rag-search.agent +131 -0
  46. package/skills/agentforce-development/assets/template-multi-topic.agent +160 -0
  47. package/skills/agentforce-development/assets/template-single-topic.agent +81 -0
  48. package/skills/agentforce-development/assets/verification-gate.agent +208 -0
  49. package/skills/agentforce-development/references/action-prompt-templates.md +164 -0
  50. package/skills/agentforce-development/references/actions-reference.md +592 -0
  51. package/skills/agentforce-development/references/agent-access-guide.md +72 -0
  52. package/skills/agentforce-development/references/agent-design-and-spec-creation.md +1010 -0
  53. package/skills/agentforce-development/references/agent-metadata-and-lifecycle.md +575 -0
  54. package/skills/agentforce-development/references/agent-script-core-language.md +1218 -0
  55. package/skills/agentforce-development/references/agent-topic-map-diagrams.md +323 -0
  56. package/skills/agentforce-development/references/agent-user-setup.md +526 -0
  57. package/skills/agentforce-development/references/agent-validation-and-debugging.md +803 -0
  58. package/skills/agentforce-development/references/known-issues.md +353 -0
  59. package/skills/agentforce-development/references/minimal-examples.md +67 -0
  60. package/skills/agentforce-development/references/production-gotchas.md +279 -0
  61. package/skills/agentforce-development/references/salesforce-cli-for-agents.md +393 -0
  62. package/skills/agentforce-development/references/version-history.md +23 -0
  63. package/skills/generate-permission-set/SKILL.md +174 -0
  64. package/skills/salesforce-custom-application/SKILL.md +1 -2
  65. package/skills/salesforce-custom-field/SKILL.md +0 -4
  66. package/skills/salesforce-custom-tab/SKILL.md +84 -8
  67. package/skills/salesforce-experience-lwr-site/SKILL.md +196 -0
  68. package/skills/salesforce-experience-lwr-site/docs/bootstrap-template-byo-lwr.md +224 -0
  69. package/skills/salesforce-experience-lwr-site/docs/configure-content-brandingSet.md +131 -0
  70. package/skills/salesforce-experience-lwr-site/docs/configure-content-route.md +232 -0
  71. package/skills/salesforce-experience-lwr-site/docs/configure-content-themeLayout.md +141 -0
  72. package/skills/salesforce-experience-lwr-site/docs/configure-content-view.md +233 -0
  73. package/skills/salesforce-experience-lwr-site/docs/configure-guest-sharing-rules.md +42 -0
  74. package/skills/salesforce-experience-lwr-site/docs/handle-component-and-region-ids.md +27 -0
  75. package/skills/salesforce-experience-lwr-site/docs/handle-ui-components.md +215 -0
  76. package/skills/salesforce-flow/SKILL.md +2 -2
  77. package/skills/salesforce-fragment/SKILL.md +85 -10
  78. package/skills/salesforce-lightning-app-build/SKILL.md +102 -10
  79. package/skills/apex-class/SKILL.md +0 -253
  80. package/skills/apex-class/examples/AccountDeduplicationBatch.cls +0 -148
  81. package/skills/apex-class/examples/AccountSelector.cls +0 -193
  82. package/skills/apex-class/examples/AccountService.cls +0 -201
  83. package/skills/apex-class/templates/abstract.cls +0 -128
  84. package/skills/apex-class/templates/batch.cls +0 -125
  85. package/skills/apex-class/templates/domain.cls +0 -102
  86. package/skills/apex-class/templates/dto.cls +0 -108
  87. package/skills/apex-class/templates/exception.cls +0 -51
  88. package/skills/apex-class/templates/interface.cls +0 -25
  89. package/skills/apex-class/templates/queueable.cls +0 -92
  90. package/skills/apex-class/templates/schedulable.cls +0 -75
  91. package/skills/apex-class/templates/selector.cls +0 -92
  92. package/skills/apex-class/templates/service.cls +0 -69
  93. package/skills/apex-class/templates/utility.cls +0 -97
  94. package/skills/apex-test-class/SKILL.md +0 -101
  95. package/skills/apex-test-class/references/assertion-patterns.md +0 -209
  96. package/skills/apex-test-class/references/async-testing.md +0 -276
  97. package/skills/apex-test-class/references/mocking-patterns.md +0 -219
  98. package/skills/apex-test-class/references/test-data-factory.md +0 -176
  99. package/skills/deployment-readiness-check/SKILL.md +0 -257
  100. package/skills/deployment-readiness-check/assets/deployment_checklist.md +0 -286
  101. package/skills/deployment-readiness-check/references/rollback_procedures.md +0 -308
  102. package/skills/deployment-readiness-check/scripts/check_metadata.sh +0 -207
  103. package/skills/salesforce-experience-site/SKILL.md +0 -178
@@ -16,7 +16,7 @@ Use this skill when you need to:
16
16
  # Fragment Generation Guide
17
17
 
18
18
  ## 📋 Overview
19
- Fragments are reusable pieces of UI similar to templates, with placeholders for actual data values. The purpose of this file is to assist developers in creating and editing fragments.
19
+ Fragments are reusable pieces of UI similar to templates, with placeholders for actual data values. The purpose of this file is to assist developers in creating and editing fragments.
20
20
 
21
21
  ## 🎯 Purpose
22
22
  Fragments render data in a structured and unified way across various Salesforce experiences like Slack, Mobile, LEX etc
@@ -24,19 +24,94 @@ Fragments render data in a structured and unified way across various Salesforce
24
24
  ## ⚙️ Composition
25
25
  A fragment is a UEM (Unified Experience Model) tree of blocks and regions. The fragment you return must follow the Typescript interfaces below:
26
26
 
27
- - **Block definition**: Follow `{namespace}}/{{blockName}` convention and use the same value as the block's definition when it appears in a fragment.
28
-
29
27
  ```ts
30
28
  interface BlockType {
31
- type: 'block'
32
- definition: string // {namespace}/{blockName}, e.g. "bcx/heading"
33
- attributes?: Record<string, any>
34
- children?: (BlockType | RegionType)[]
29
+ type: 'block'
30
+ definition: string // {namespace}/{blockName}
31
+ attributes?: Record<string, any>
32
+ children?: (BlockType | RegionType)[]
35
33
  }
36
34
 
37
35
  interface RegionType {
38
- type: 'region'
39
- name: string
40
- children: BlockType[]
36
+ type: 'region'
37
+ name: string
38
+ children: BlockType[]
41
39
  }
42
40
  ```
41
+
42
+ ---
43
+
44
+ ## 🔧 Available Metadata Actions
45
+
46
+ ### When to Use Each Action
47
+
48
+ #### discoverUiComponents
49
+
50
+ **When:** You want to see what block components are available for fragments.
51
+
52
+ **Purpose:** Discover the palette of available blocks that can be used in fragment composition.
53
+
54
+ **Input Parameters:**
55
+ - `pageType` (required): "FRAGMENT"
56
+ - `pageContext` (optional): JSON object - not required for FRAGMENT type
57
+ - `searchQuery` (optional): String to filter components by name or description
58
+
59
+ **Returns:** List of components with:
60
+ - `definition`: Fully qualified name (e.g., "namespace/definiton")
61
+ - `description`: Component description
62
+ - `label`: Human-readable label
63
+ - `attributes`: Optional attribute metadata
64
+
65
+ **Use for:** Finding available blocks before building your fragment structure.
66
+
67
+ #### getUiComponentSchemas
68
+
69
+ **When:** You know which components you want but need to understand their properties and attributes.
70
+
71
+ **Purpose:** Get detailed JSON schemas for component configuration, including property types, required vs optional fields, and validation rules.
72
+
73
+ **Input Parameters:**
74
+ - `pageType` (required): "FRAGMENT"
75
+ - `pageContext` (optional): JSON object - not required for FRAGMENT type
76
+ - `componentDefinitions` (required): List of fully qualified names (e.g., ["namespace/definition"])
77
+ - `includeKnowledge` (optional): Boolean, defaults to true - includes additional component-specific guidance
78
+
79
+ **Returns:**
80
+ - `componentSchemas`: List of results (supports partial failures)
81
+ - **Success entries**: Contains JSON schema with property definitions, types, constraints
82
+ - **Failure entries**: Contains error message explaining why schema couldn't be retrieved
83
+ - `$defs`: Schema definitions and references (if schema transformation applied)
84
+
85
+ **Use for:** Understanding how to configure component attributes before adding blocks to your fragment.
86
+
87
+ **Key Feature:** Supports partial failures - if some components can't be found, you still get schemas for the successful ones.
88
+
89
+ ---
90
+
91
+ ## 💡 Typical Workflow
92
+
93
+ 1. **Discover Available Blocks**
94
+ - Use `discoverUiComponents` to explore what blocks are available
95
+ - Optional: Use `searchQuery` to filter by keywords (e.g., "text", "button", "image")
96
+
97
+ 2. **Select Components**
98
+ - Choose blocks that fit your fragment requirements
99
+ - Note their fully qualified definitions (e.g., "namespace/definition")
100
+
101
+ 3. **Get Component Schemas**
102
+ - Use `getUiComponentSchemas` with the selected component definitions
103
+ - Review the JSON schemas to understand required and optional attributes
104
+
105
+ 4. **Build Fragment**
106
+ - Construct your fragment using the UEM tree structure
107
+ - Configure block attributes according to the schemas
108
+ - Use the TypeScript interfaces defined above
109
+
110
+ ---
111
+
112
+ ## ⚠️ Important Notes
113
+
114
+ - Block definitions always follow the `{namespace}/{blockName}` convention
115
+ - Use the same definition format returned by `discoverUiComponents` when calling `getUiComponentSchemas`
116
+ - The FRAGMENT page type doesn't require additional `pageContext` parameters
117
+ - Schemas include both required and optional attributes - review carefully to ensure valid configuration
@@ -1,16 +1,17 @@
1
1
  ---
2
2
  name: salesforce-lightning-app-build
3
- description: Use this skill to build and orchestrate complete Salesforce Lightning Applications (LEX Apps), custom projects, or end-to-end business solutions from a natural language scenario. Triggers when a user requests a "custom app", a "business solution", or describes any scenario requiring multiple interconnected Salesforce components to be built together into a complete Lightning Experience (LEX) Application. Orchestrates the sequenced creation of Custom Objects, Relationships, Fields, Lightning Record Pages, Custom Tabs, Custom Applications, Permission Sets, and OPTIONALLY Flows and Validation Rules.
3
+ description: Build complete Salesforce Lightning Experience applications from natural language descriptions. Use this skill when a user requests a "complete app", "Lightning app", "business solution", "management system", or describes a scenario requiring multiple interconnected Salesforce components (objects, fields, pages, tabs, security). Orchestrates all required metadata types in proper dependency order to produce a deployable application.
4
4
  metadata:
5
5
  category: orchestration
6
- related-skills: salesforce-custom-object, salesforce-custom-field, salesforce-custom-tab, salesforce-flexipage, salesforce-custom-application, salesforce-flow, salesforce-validation-rule, salesforce-list-view
6
+ version: "1.0"
7
+ related-skills: salesforce-custom-object, salesforce-custom-field, salesforce-custom-tab, salesforce-flexipage, salesforce-custom-application, salesforce-flow, salesforce-validation-rule, salesforce-list-view, generate-permission-set
7
8
  ---
8
9
 
9
10
  # Salesforce Lightning Application Build
10
11
 
11
12
  ## Overview
12
13
 
13
- Build complete Lightning Experience applications from natural language by orchestrating multiple metadata types in proper dependency order. This skill acts as a "conductor" that invokes specialized metadata skills when available, or generates metadata directly when no skill exists.
14
+ Build a complete, deployable Salesforce Lightning Experience application from a natural language description by orchestrating multiple metadata types in correct dependency order. Invoke specialized metadata skills when available; generate metadata directly when no skill exists.
14
15
 
15
16
  ## When to Use This Skill
16
17
  **Use when:**
@@ -34,7 +35,6 @@ Build complete Lightning Experience applications from natural language by orches
34
35
  - Troubleshooting or debugging existing metadata
35
36
  - Building Salesforce Classic apps (not Lightning Experience)
36
37
  - User asks for just one object, or just one page, or just one permission set (without others)
37
- ---
38
38
 
39
39
  ## Metadata Type Registry
40
40
 
@@ -50,7 +50,7 @@ This table shows which metadata types are commonly needed for LEX apps and their
50
50
  | **List View** | ✅ YES | `salesforce-list-view` | MUST use skill |
51
51
  | **Validation Rule** | ✅ YES | `salesforce-validation-rule` | MUST use skill (if requested) |
52
52
  | **Flow** | ✅ YES | `salesforce-flow` | MUST use skill (if requested) |
53
- | **Permission Set** | NO | - | Generate directly using Metadata API knowledge |
53
+ | **Permission Set** | YES | `generate-permission-set` | MUST use skill |
54
54
 
55
55
  ### Skill Usage Rules
56
56
 
@@ -115,8 +115,8 @@ Custom Application (depends on: Tabs exist)
115
115
  Permission Sets (depends on: Objects, Fields, Tabs, App exist)
116
116
  ```
117
117
 
118
- **Fallback generation (no skill available):**
119
- 1. Generate Permission Set XML directly with access to:
118
+ **Skills to invoke:**
119
+ 1. `generate-permission-set` for each permission set with access to:
120
120
  - Objects (Read, Create, Edit, Delete)
121
121
  - Fields (Read, Edit)
122
122
  - Tabs (Visible)
@@ -170,7 +170,7 @@ METADATA SKILLS TO INVOKE:
170
170
  - salesforce-custom-tab (x N)
171
171
  - salesforce-flexipage (x N)
172
172
  - salesforce-custom-application (x 1)
173
- - [fallback] Permission Set XML generation (x N)
173
+ - generate-permission-set (x N)
174
174
 
175
175
  DEPENDENCY ORDER:
176
176
  1. Phase 1: Data Model (Objects → Fields)
@@ -198,7 +198,99 @@ Execute in strict dependency order. For each metadata component:
198
198
  - For Custom Tab → Invoke `salesforce-custom-tab`
199
199
  - For FlexiPage → Invoke `salesforce-flexipage`
200
200
  - For Custom Application → Invoke `salesforce-custom-application`
201
- - For Permission Sets (no skill) Generate XML directly
201
+ - For Permission SetInvoke `generate-permission-set`
202
+
203
+ ### STEP 3: Final Artifact Assembly
204
+
205
+ After all phases complete, consolidate outputs into deployment-ready structure.
206
+
207
+ ---
208
+
209
+ ## Output
210
+
211
+ The completed build produces:
212
+
213
+ 1. **Salesforce DX Project Directory** containing all generated metadata
214
+ - Organized by standard SFDX structure: `force-app/main/default/`
215
+
216
+ 2. **Metadata Files** - One file per component, organized by type:
217
+ ```
218
+ force-app/main/default/
219
+ ├── objects/ # Custom Objects (.object-meta.xml)
220
+ ├── fields/ # Custom Fields (.field-meta.xml)
221
+ ├── tabs/ # Custom Tabs (.tab-meta.xml)
222
+ ├── flexipages/ # Lightning Pages (.flexipage-meta.xml)
223
+ ├── applications/ # Custom Applications (.app-meta.xml)
224
+ ├── permissionsets/ # Permission Sets (.permissionset-meta.xml)
225
+ ├── flows/ # Flows (.flow-meta.xml) - if applicable
226
+ └── objects/.../validationRules/ # Validation Rules (.validationRule-meta.xml) - if applicable
227
+ ```
228
+
229
+ 3. **Deployment Manifest** (`package.xml`)
230
+ - Lists all components with proper API version
231
+ - Organized by metadata type in dependency order
232
+ - Ready for Salesforce CLI deployment or Metadata API deployment
233
+
234
+ 4. **Build Summary Report** - A markdown file listing:
235
+ - Every component created
236
+ - Component type and API name
237
+ - File path location
238
+ - Dependency relationships
239
+ - Any warnings or recommendations
240
+
241
+ **Example Summary Structure:**
242
+ ```
243
+ 📦 Lightning App Build Complete: Project Management App
244
+
245
+ METADATA GENERATED:
246
+ ✅ 3 Custom Objects
247
+ - Project__c → force-app/main/default/objects/Project__c/Project__c.object-meta.xml
248
+ - Task__c → force-app/main/default/objects/Task__c/Task__c.object-meta.xml
249
+ - Resource__c → force-app/main/default/objects/Resource__c/Resource__c.object-meta.xml
250
+
251
+ ✅ 12 Custom Fields
252
+ - Project__c.Name → force-app/main/default/objects/Project__c/fields/Name.field-meta.xml
253
+ - Project__c.Status__c → force-app/main/default/objects/Project__c/fields/Status__c.field-meta.xml
254
+ [... etc ...]
255
+
256
+ ✅ 3 Custom Tabs
257
+ - Project__c → force-app/main/default/tabs/Project__c.tab-meta.xml
258
+ [... etc ...]
259
+
260
+ ✅ 3 Lightning Record Pages
261
+ - Project_Record_Page → force-app/main/default/flexipages/Project_Record_Page.flexipage-meta.xml
262
+ [... etc ...]
263
+
264
+ ✅ 1 Custom Application
265
+ - Project_Management → force-app/main/default/applications/Project_Management.app-meta.xml
266
+
267
+ ✅ 2 Permission Sets
268
+ - Project_Manager → force-app/main/default/permissionsets/Project_Manager.permissionset-meta.xml
269
+ - Project_User → force-app/main/default/permissionsets/Project_User.permissionset-meta.xml
270
+
271
+ ⚠️ WARNINGS: None
272
+ ```
273
+
274
+ ---
275
+
276
+ ## Validation
277
+
278
+ Before presenting the completed build to the user, verify cross-component integrity:
279
+
280
+ - [ ] **Object-Tab Coverage**: Every Custom Object has at least one Custom Tab
281
+ - [ ] **Relationship Integrity**: Every Custom Object referenced in a relationship (parent or child) exists in the build
282
+ - [ ] **Field References in Pages**: Every field referenced in a FlexiPage exists on the corresponding object
283
+ - [ ] **Tab References in App**: Every tab referenced in the Custom Application was successfully created
284
+ - [ ] **Permission Set Completeness**: Permission Sets grant access to all generated objects, fields, tabs, and the application
285
+ - [ ] **No Orphaned Components**: No tabs without objects, no pages without corresponding tabs, no app without tabs
286
+ - [ ] **Deployment Manifest Completeness**: `package.xml` includes all generated components in proper dependency order
287
+
288
+ **Validation Failure Handling:**
289
+ - If validation fails, include failed checks in the Build Summary Report under a `⚠️ VALIDATION WARNINGS` section
290
+ - Do NOT block delivery of the build, but clearly communicate what needs manual review or correction
291
+ - Provide specific remediation steps for each failed validation check
292
+
293
+ **Note**: Individual component validations (reserved words, name lengths, field types, etc.) are handled by specialized metadata skills and do not need to be re-validated here.
202
294
 
203
295
  ---
204
296
 
@@ -246,7 +338,7 @@ When user doesn't specify details:
246
338
  - Enable Search and Reports for user-facing objects
247
339
  - Set sharingModel based on relationships
248
340
 
249
- ### 5. Validate Before Building
341
+ ### 4. Validate Before Building
250
342
  Check for:
251
343
  - Reserved words in API names
252
344
  - Relationship limits (max 2 M-D per object)
@@ -1,253 +0,0 @@
1
- ---
2
- name: apex-class
3
- description: Generate production-ready Apex classes for Salesforce following enterprise best practices. Covers service classes, selectors, domain classes, batch/queueable/schedulable, DTOs, utilities, interfaces, abstract classes, and custom exceptions. Not for triggers or unit tests. Use this skill whenever the user asks to create, write, build, generate, or scaffold any Apex class — including when they describe functionality that would require an Apex class without explicitly saying "Apex class." Trigger on phrases like "build a service for," "create a handler," "I need a class that," "write Apex to," "scaffold a batch job," "create a queueable," or any request involving Salesforce server-side logic. Also use when the user asks to refactor, improve, or restructure existing Apex classes. Even if the request is vague like "I need something that processes Opportunities nightly," use this skill if the solution would involve an Apex class.
4
- ---
5
-
6
- # Apex Class
7
-
8
- Generate well-structured, production-ready Apex classes for Salesforce development.
9
-
10
- ## Scope
11
-
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
23
-
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
29
-
30
- ---
31
-
32
- ## Gathering Requirements
33
-
34
- Before generating code, gather these inputs from the user (ask if not provided):
35
-
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)
45
-
46
- If the user provides a clear, complete request, generate immediately without unnecessary back-and-forth.
47
-
48
- ---
49
-
50
- ## Code Standards — ALWAYS Follow These
51
-
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.
57
-
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.
62
-
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.
68
-
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.
72
-
73
- ### Naming Conventions
74
-
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:
92
-
93
- ```apex
94
- /**
95
- * @description Brief description of what the class does
96
- * @author Generated by Apex Class Writer Skill
97
- */
98
- ```
99
-
100
- ```apex
101
- /**
102
- * @description Brief description of what the method does
103
- * @param paramName Description of the parameter
104
- * @return Description of the return value
105
- * @example
106
- * List<Account> results = AccountService.deduplicateAccounts(accountIds);
107
- */
108
- ```
109
-
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`.
114
-
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.
119
-
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.
124
-
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.
129
-
130
- ---
131
-
132
- ## Output Format
133
-
134
- For every class, produce TWO files:
135
-
136
- 1. **`{ClassName}.cls`** — The Apex class source code
137
- 2. **`{ClassName}.cls-meta.xml`** — The metadata file
138
-
139
- ### Meta XML Template
140
-
141
- ```xml
142
- <?xml version="1.0" encoding="UTF-8"?>
143
- <ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
144
- <apiVersion>{API_VERSION}</apiVersion>
145
- <status>Active</status>
146
- </ApexClass>
147
- ```
148
-
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: `templates/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: `templates/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: `templates/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: `templates/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: `templates/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: `templates/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: `templates/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: `templates/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: `templates/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: `templates/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: `templates/exception.cls`
223
- - Extend `Exception`
224
- - Keep them simple — Apex exceptions don't support custom constructors well
225
- - Name them descriptively: `AccountServiceException`, `IntegrationTimeoutException`
226
-
227
- ---
228
-
229
- ## Generation Workflow
230
-
231
- 1. Determine the class type from the user's request
232
- 2. Read the corresponding template from `templates/`
233
- 3. Read relevant examples from `examples/` 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
239
-
240
- ---
241
-
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
@@ -1,148 +0,0 @@
1
- /**
2
- * @description Batch Apex class for identifying and flagging duplicate Account records.
3
- * Compares Accounts by Name and BillingPostalCode to find potential duplicates.
4
- * Flags duplicates by setting the Is_Potential_Duplicate__c checkbox.
5
- * Implements Database.Stateful to track results across batch chunks.
6
- * @author Generated by Apex Class Writer Skill
7
- *
8
- * @example
9
- * // Run with default batch size (200)
10
- * Id jobId = AccountDeduplicationBatch.run();
11
- *
12
- * // Run with smaller batch size for complex processing
13
- * Database.executeBatch(new AccountDeduplicationBatch(), 50);
14
- */
15
- public with sharing class AccountDeduplicationBatch implements Database.Batchable<SObject>, Database.Stateful {
16
-
17
- // ─── Constants ───────────────────────────────────────────────────────
18
- private static final Integer DEFAULT_BATCH_SIZE = 200;
19
-
20
- // ─── Stateful Tracking ───────────────────────────────────────────────
21
- private Integer totalScanned = 0;
22
- private Integer duplicatesFound = 0;
23
- private Integer totalErrors = 0;
24
- private List<String> errorMessages = new List<String>();
25
-
26
- // ─── Batchable Interface ─────────────────────────────────────────────
27
-
28
- /**
29
- * @description Queries all active Accounts that haven't already been flagged
30
- * @param bc The batch context
31
- * @return QueryLocator scoped to unflagged active Accounts
32
- */
33
- public Database.QueryLocator start(Database.BatchableContext bc) {
34
- return Database.getQueryLocator([
35
- SELECT Id, Name, BillingPostalCode, Is_Potential_Duplicate__c
36
- FROM Account
37
- WHERE IsDeleted = FALSE
38
- AND Is_Potential_Duplicate__c = FALSE
39
- ORDER BY Name ASC
40
- ]);
41
- }
42
-
43
- /**
44
- * @description Processes each batch by building a duplicate key and checking for matches.
45
- * Uses a composite key of normalized Name + BillingPostalCode.
46
- * @param bc The batch context
47
- * @param scope List of Account records in the current batch
48
- */
49
- public void execute(Database.BatchableContext bc, List<Account> scope) {
50
- totalScanned += scope.size();
51
-
52
- // Build duplicate keys for this batch
53
- Map<String, List<Account>> dupeKeyMap = new Map<String, List<Account>>();
54
- for (Account acct : scope) {
55
- String key = buildDuplicateKey(acct);
56
- if (String.isNotBlank(key)) {
57
- if (!dupeKeyMap.containsKey(key)) {
58
- dupeKeyMap.put(key, new List<Account>());
59
- }
60
- dupeKeyMap.get(key).add(acct);
61
- }
62
- }
63
-
64
- // Flag records that share a key with another record
65
- List<Account> toUpdate = new List<Account>();
66
- for (String key : dupeKeyMap.keySet()) {
67
- List<Account> group = dupeKeyMap.get(key);
68
- if (group.size() > 1) {
69
- for (Account acct : group) {
70
- toUpdate.add(new Account(
71
- Id = acct.Id,
72
- Is_Potential_Duplicate__c = true
73
- ));
74
- }
75
- }
76
- }
77
-
78
- if (!toUpdate.isEmpty()) {
79
- List<Database.SaveResult> results = Database.update(toUpdate, false);
80
- processResults(results);
81
- }
82
- }
83
-
84
- /**
85
- * @description Logs a summary of the deduplication batch run
86
- * @param bc The batch context
87
- */
88
- public void finish(Database.BatchableContext bc) {
89
- String summary = String.format(
90
- 'AccountDeduplicationBatch completed. Scanned: {0}, Duplicates flagged: {1}, Errors: {2}',
91
- new List<Object>{ totalScanned, duplicatesFound, totalErrors }
92
- );
93
-
94
- System.debug(LoggingLevel.INFO, summary);
95
-
96
- if (!errorMessages.isEmpty()) {
97
- System.debug(LoggingLevel.ERROR, 'Error details:\n' + String.join(errorMessages, '\n'));
98
- }
99
- }
100
-
101
- // ─── Private Helpers ─────────────────────────────────────────────────
102
-
103
- /**
104
- * @description Builds a normalized composite key for duplicate detection
105
- * @param acct The Account record
106
- * @return Normalized key string, or null if insufficient data
107
- */
108
- private String buildDuplicateKey(Account acct) {
109
- if (String.isBlank(acct.Name)) {
110
- return null;
111
- }
112
-
113
- String normalizedName = acct.Name.trim().toUpperCase().replaceAll('\\s+', ' ');
114
- String postalCode = (acct.BillingPostalCode ?? '').trim().toUpperCase();
115
-
116
- return normalizedName + '|' + postalCode;
117
- }
118
-
119
- /**
120
- * @description Processes DML results, tracking successes and failures
121
- * @param results List of Database.SaveResult from update operation
122
- */
123
- private void processResults(List<Database.SaveResult> results) {
124
- for (Database.SaveResult sr : results) {
125
- if (sr.isSuccess()) {
126
- duplicatesFound++;
127
- } else {
128
- totalErrors++;
129
- for (Database.Error err : sr.getErrors()) {
130
- errorMessages.add(
131
- 'Record ' + sr.getId() + ': ' +
132
- err.getStatusCode() + ' - ' + err.getMessage()
133
- );
134
- }
135
- }
136
- }
137
- }
138
-
139
- // ─── Static Helpers ──────────────────────────────────────────────────
140
-
141
- /**
142
- * @description Convenience method to execute with default batch size
143
- * @return The batch job Id
144
- */
145
- public static Id run() {
146
- return Database.executeBatch(new AccountDeduplicationBatch(), DEFAULT_BATCH_SIZE);
147
- }
148
- }