Merge pull request #21 from forcedotcom/gbockus/hsinghbisht/experts-skills

chore: merge first version of experts skills
This commit is contained in:
gbockus-sf 2026-03-06 18:03:50 -06:00 committed by GitHub
commit 8d304f7643
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
16 changed files with 2796 additions and 0 deletions

View File

@ -0,0 +1,76 @@
---
name: lex-app-solution
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.
---
# Salesforce Lightning Application (LEX App) Builder
## Overview
Build and orchestrate complete Salesforce Lightning Applications (LEX Apps) from natural language scenarios. This skill coordinates the sequenced creation of multiple interconnected Salesforce components—Custom Objects, Fields, Lightning Record Pages, Custom Tabs, Custom Applications, Permission Sets, and optionally Flows and Validation Rules—by invoking specialized metadata expert skills in the correct order.
## When to Use This Skill
Use this skill when you need to:
- Build or enhance a complete Lightning Application (LEX App) from a single user prompt.
- Create end-to-end solutions requiring multiple metadata types working together within the Lightning Experience.
- Ensure proper sequencing of metadata creation (Objects → Fields → Tabs → Pages → Apps → Security).
**Do not use this skill for:**
- Creating individual metadata components (use specific metadata expert skills instead).
- Troubleshooting or fixing deployment errors.
- Building Salesforce Classic applications or off-platform integrations.
## Specification
# Salesforce Lightning Application Development Requirements
You are a highly experienced and certified Salesforce Architect. Your purpose is to autonomously orchestrate the generation of a complete Salesforce Lightning application based on the user's requirements.
## Specialized Skill Invocation Requirement
**CRITICAL:** You **MUST NOT** generate raw metadata or XML directly. You **MUST** invoke the specialized metadata expert skill for each component type.
### MANDATORY Skill Mapping (Always Evaluate & Invoke):
- **Custom Objects**`salesforce-custom-object`
- **Custom Fields**`salesforce-custom-field`
- **Custom Tabs**`salesforce-custom-tab`
- **FlexiPages**`salesforce-flexipage`
- **Custom Applications**`salesforce-custom-application` (Ensure this generates a LEX CustomApplication, not Classic)
- **Permission Sets**`salesforce-permission-set` (Create at least one baseline permission set for app access if specific personas aren't requested)
### OPTIONAL Skill Mapping (Strictly Conditional):
*DO NOT invoke these unless the user's prompt explicitly asks for or clearly describes requirements for them (e.g., "enforce that...", "automate the...").*
- **Validation Rules**`salesforce-validation-rule`
- **Flows**`salesforce-flow`
---
## Autonomous Execution Sequence
Execute the following steps sequentially in a single response. Do not stop and ask the user for permission to proceed unless their initial prompt lacks the basic information needed to start building.
### STEP 1: The Pre-Flight Checklist (Planning)
Before invoking any skills, you must analyze the user's request and output a bulleted "Build Plan".
- Explicitly list every Custom Object, Field, Tab, FlexiPage, LEX Application, and Permission Set you are about to create.
- **Evaluate Optional Metadata:** Actively scan the prompt for automation or validation requirements. If found, add them to the plan. If NOT found, explicitly state: *"No optional Flows or Validation Rules requested. Skipping."*
- Explicitly state which metadata skill you will invoke for each planned item.
### STEP 2: The Build Sequence (Skill Invocations)
Immediately after outputting the Pre-Flight Checklist, begin invoking the specialized skills strictly in this order:
1. **Data Model (Mandatory):** Invoke skills for Custom Objects first, followed immediately by Custom Fields.
2. **Business Logic (Optional):** Invoke skills for Validation Rules and Flows **ONLY IF** they were explicitly included in your Pre-Flight Checklist. Otherwise, skip this step entirely.
3. **User Experience (Mandatory):** Invoke skills for Custom Tabs. Then, invoke skills for FlexiPages (only for objects that received tabs, ensuring you include requested components like Highlights Panels).
4. **App Assembly (Mandatory):** Invoke the skill for the Custom Application to create the Lightning App, adding the newly created tabs.
5. **Security (Mandatory):** Invoke the skill for Permission Sets to grant access to the newly created LEX App, Objects, and Fields.
### STEP 3: Skill Invocation Summary
Once all invocations are complete, output a final summary confirming:
- The complete Lightning application has been orchestrated.
- A list of any errors, warnings, or constraints encountered during the skill invocations.
---
### Error Handling & Constraints
- If a specialized skill invocation fails, note it in your internal sequence, skip that specific component, and attempt to continue building the rest of the application.
- Only pause and ask the user for intervention if a critical failure occurs (e.g., a primary Custom Object fails to generate).

View File

@ -0,0 +1,211 @@
---
name: salesforce-custom-application
description: Use this skill when users need to create or configure Salesforce Custom Applications. Trigger when users mention custom apps, application metadata, app navigation, or organizing tabs into applications. Use when users want to create app containers for tabs and pages. Always use this skill for custom application work.
---
## When to Use This Skill
Use this skill when you need to:
- Create Lightning applications
- Organize tabs and features into focused apps
- Configure application navigation and branding
- Set up custom page layouts for objects
- Troubleshoot deployment errors related to custom applications
# CustomApplication (Lightning App) Metadata Specification
## Overview
Custom applications (Lightning Apps) that group tabs and functionality to provide a focused user experience for specific business processes. Always configured for Lightning Experience.
## 🎯 Purpose
- Organize related functionality into focused applications
- Group tabs and components for specific user roles
- Provide tailored user experiences
- Control access to specific features and data
- Use Standard navigation for general business applications or Console navigation for specialized service/support workflows requiring multi-tab workspaces
- Create professional, branded application identity with custom colors and branding
- Override standard actions with custom Lightning pages for enhanced user experience
- Enable profile-specific experiences through profile action overrides
## ⚙️ Required Properties
### Core Application Properties
- **fullName**: API name of the application
- **label**: Display name of the application
- **uiType**: Always "Lightning" for modern apps
- **navType**: CRITICAL - Choose based on user requirements and workflow patterns
- "Standard": DEFAULT for general business applications (e.g., sales, marketing, operations)
- "Console": ONLY when workflow requires managing multiple records simultaneously with split-view or multi-tab workspace (e.g., customer service, call centers, support operations)
- **formFactors**: Array of form factors (["LARGE"] for desktop, ["SMALL"] for mobile, or both)
### Optional Properties
- **description**: Brief description of the application's purpose
- **tabs**: Array of tab names to include
- **utilityBar**: API name of the Utility Bar configuration
- **brand**: ⚠️ HIGHLY RECOMMENDED - Branding configuration object (headerColor, shouldOverrideOrgTheme, footerColor, primaryTabColor)
- **actionOverrides**: ⚠️ REQUIRED when custom record pages exist - Action override configuration (actionName, content, formFactor, type, pageOrSobjectType)
- **profileActionOverrides**: Profile-specific action overrides (actionName, content, formFactor, pageOrSobjectType, type, profile)
- **isNavAutoTempTabsDisabled**: Navigation behavior setting (default: false)
- **isNavPersonalizationDisabled**: Personalization setting (default: false)
- **isNavTabPersistenceDisabled**: Tab persistence setting (default: false)
## 🔧 Application Configuration
### Navigation Type Selection (CRITICAL)
**Decision Criteria for navType:**
**Choose "Standard" (DEFAULT) for:**
- General business applications and most workflows
- Single-record focus or linear navigation patterns
- Standard tab-based navigation is sufficient
**Choose "Console" ONLY when workflow requires:**
- Managing multiple related records simultaneously in split-view
- Multi-tab workspace for handling complex, interconnected data
- Contextual information from multiple sources visible at once
- Examples: customer service operations, support desks, call centers
**When in doubt:** Default to "Standard" for most general business use cases
### Navigation Settings
- **isNavAutoTempTabsDisabled**: Controls automatic temporary tab creation
- **isNavPersonalizationDisabled**: Controls user personalization features
- **isNavTabPersistenceDisabled**: Controls tab persistence across sessions
### Tab Management
- **tabs**: Array of tab names to include in the application
- **formFactors**: Device-specific configurations (Large for desktop, Small for mobile)
### Utility Bar
- **utilityBar**: Reference to Lightning utility bar (appears at bottom of Lightning Experience)
### Branding (HIGHLY RECOMMENDED - DO NOT SKIP)
**IMPORTANT**: Provide branding configuration to create a professional, visually distinct application identity.
- **brand.headerColor**: Header bar color in hex format (e.g., "#0070D2") - RECOMMENDED
- **brand.shouldOverrideOrgTheme**: Override organization theme (true/false) - Default: false
- **brand.footerColor**: Footer color in hex format
- **brand.primaryTabColor**: Primary tab color in hex format
### Action Overrides (CRITICAL - DO NOT SKIP)
**IMPORTANT**: Action overrides MUST be created for every custom object tab that has a record page generated by flexipage expert.
- **actionOverrides.actionName**: Action to override ("View" or "Tab")
- **actionOverrides.content**: Page/component name (FlexiPage, Visualforce, Lightning component)
- For "View" action: Reference record pages generated by flexipage expert
- For "Tab" action: Reference home/app pages generated by flexipage expert
- **actionOverrides.formFactor**: Device type ("Large" or "Small")
- **actionOverrides.type**: Override type ("Default", "Visualforce", "Flexipage", "LightningComponent", "Scontrol")
- Recommended: Use "Flexipage" for Lightning record/home pages generated by flexipage expert
- **actionOverrides.pageOrSobjectType**: Object API name the override applies to
- **actionOverrides.comment**: Optional description (max 1000 characters)
- Auto-generated comment: "Action override created by Lightning App Builder during activation."
- **actionOverrides.skipRecordTypeSelect**: Skip record type selection (default: false)
### Profile Action Overrides
- **profileActionOverrides.actionName**: Action to override ("View" or "Tab")
- **profileActionOverrides.content**: Page/component name
- For "View" action: Reference profile-specific record pages generated by flexipage expert
- For "Tab" action: Reference profile-specific home pages generated by flexipage expert
- Can reference same or different FlexiPages than actionOverrides for profile-specific experiences
- **profileActionOverrides.formFactor**: Device type ("Large" or "Small")
- **profileActionOverrides.pageOrSobjectType**: Object API name
- **profileActionOverrides.type**: Override type
- Recommended: Use "Flexipage" for Lightning pages generated by flexipage expert
- **profileActionOverrides.profile**: Profile API name (e.g., "Admin", "Standard User")
- Enables different page layouts for different user profiles
## 📱 Device Support
### Desktop Configuration
- **formFactor**: "Large"
- **tabs**: Full list of application tabs
### Phone Configuration
- **formFactor**: "Small"
- **tabs**: Mobile-optimized tab selection
### Tablet Configuration
- **formFactor**: "Medium"
- **tabs**: Tablet-appropriate tab selection
## 🎨 User Experience Features
### Navigation Behavior
- **Auto Temporary Tabs**: Can be enabled/disabled
- **Personalization**: User customization options
- **Tab Persistence**: Remember user's tab selections
### Accessibility
- **Keyboard Navigation**: Full keyboard support
- **Screen Reader**: Compatible with assistive technologies
- **High Contrast**: Support for high contrast modes
## 🔗 Integration Points
- **Custom Tabs**: Include custom object and web tabs
- **Standard Tabs**: Include standard Salesforce tabs
- **Lightning Pages**: Integrate with Lightning page layouts
- **Components**: Include custom Lightning components
## ✅ Best Practices
- **Always use Lightning UI**: Set `uiType` to "Lightning" for modern apps
- **Choose appropriate navigation**: CRITICAL - Analyze requirements carefully for `navType` selection
- Use "Standard" (DEFAULT) for general business applications
- Use "Console" ONLY when workflow requires multi-tab workspace, split-view, or managing multiple related records simultaneously
- Examples for Console: customer service, call centers, support operations
- Default to "Standard" for most general business use cases
- **Include Standard Tabs**: Add common Salesforce tabs (Home, Accounts, Contacts, etc.)
- **Use clear, descriptive application names**
- **Group related functionality logically**
- **Consider different user roles and needs**
- **Test across different device types**
- **Ensure proper permissions and access control**
- **Provide meaningful descriptions for users**
- **Follow consistent naming conventions**
- **Always configure branding**: Set headerColor to create professional application identity
- **Use accessible brand colors**: Ensure hex colors have sufficient contrast (WCAG AA compliant)
- **Configure utility bars**: Add useful quick-access tools for users
- **Leverage action overrides**: Customize page layouts for specific objects using FlexiPages from flexipage expert
- **Use profile overrides**: Provide role-specific experiences by referencing different flexipage expert generated pages per profile
## 🎯 Enhancement Rules
- **uiType**: Always set to "Lightning" for modern app experience
- **navType**: CRITICAL DECISION - Analyze user requirements carefully
- Set to "Standard" (DEFAULT) for general business applications
- Set to "Console" ONLY when workflow requires:
- Managing multiple related records simultaneously with split-view capability
- Multi-tab workspace for handling complex, interconnected data
- Contextual information from multiple sources visible at once
- Console examples: customer service operations, call centers, support desks
- When in doubt between Standard and Console, choose "Standard" for most business use cases
- **formFactors**: Always set to ["LARGE"] for desktop Lightning Experience
- **Standard Tabs**: Automatically add Home, Accounts, Contacts, Opportunities, Leads, Cases
- **Navigation Settings**: Set all navigation flags to false for best user experience
- **Branding**: ALWAYS include brand configuration for professional application identity
- MANDATORY: Set brand.headerColor to appropriate color (e.g., "#0070D2" for Salesforce Blue)
- Set brand.shouldOverrideOrgTheme based on requirements
- **Action Overrides**: ALWAYS create action overrides when custom record pages exist
- MANDATORY: Add actionOverrides for "View" action pointing to flexipage expert generated record pages
- Use "Flexipage" type and reference the exact FlexiPage name
- Set formFactor to "Large" for desktop
- Include pageOrSobjectType with the object API name
- **Profile Action Overrides**: Reference flexipage expert generated pages for role-based customization
- **Form Factors**: Use "Large" for desktop, "Small" for mobile in overrides
## ⚠️ CRITICAL Verification Checklist (MUST VERIFY)
- [ ] All tabs are included in the application
- [ ] **navType IS CORRECTLY SET** - Verify Console vs Standard selection
- [ ] Default to "Standard" for most general business applications
- [ ] Set to "Console" ONLY if workflow requires managing multiple records simultaneously, split-view, or multi-tab workspace
- [ ] If requirements are general/ambiguous → navType should be "Standard"
- [ ] **BRANDING IS CONFIGURED** - This is HIGHLY RECOMMENDED for professional applications
- [ ] brand.headerColor is set with valid hex color (e.g., "#0070D2")
- [ ] brand.shouldOverrideOrgTheme is set (default: false)
- [ ] **ACTION OVERRIDES ARE CREATED** - This is MANDATORY for every custom object with a record page
- [ ] Action overrides are defined for EACH custom object tab pointing to the correct record page
- [ ] actionOverrides.content matches the exact FlexiPage name generated by flexipage expert
- [ ] actionOverrides.pageOrSobjectType is set to the correct object API name
- [ ] actionOverrides.type is set to "Flexipage"
- [ ] actionOverrides.actionName is set to "View"
- [ ] actionOverrides.formFactor is set to "Large"
- [ ] All required fields are populated (fullName, label, uiType, navType, formFactors)

View File

@ -0,0 +1,499 @@
---
name: salesforce-custom-field
description: Use this skill when users need to create, generate, or validate Salesforce Custom Field metadata. Trigger when users mention custom fields, field types, Roll-up Summary fields, Master-Detail relationships, Lookup relationships, formula fields, picklists, or field metadata. Also use when users encounter field deployment errors, especially around Roll-up Summary format, Master-Detail constraints, or formula issues. Always use this skill for any custom field metadata work, field generation, or field troubleshooting.
---
## When to Use This Skill
Use this skill when you need to:
- Create custom fields on any object
- Generate field metadata for any field type
- Set up relationship fields (Lookup or Master-Detail)
- Create formula or roll-up summary fields
- Troubleshoot deployment errors related to custom fields
# Salesforce Custom Field Generator and Validator
## Overview
Generate and validate Salesforce Custom Field metadata with mandatory constraints to prevent deployment errors. This skill has special focus on the **highest-failure-rate field types**: Roll-up Summary and Master-Detail relationships.
## Specification
## 1. Purpose
This document defines the mandatory constraints for generating CustomField metadata XML. The agent must verify these constraints before outputting XML to prevent Metadata API deployment errors.
**Critical Focus Areas:**
- Roll-up Summary field format errors
- Master-Detail field attribute restrictions
- Lookup Filter restrictions
---
## 2. Universal Mandatory Attributes
Every generated field must include these tags:
| Attribute | Requirement | Notes |
|-----------|-------------|-------|
| `<fullName>` | Required | Derive from `<label>`: capitalize each word, replace spaces with `_`, append `__c`. Must start with a letter. E.g., label `Total Contract Value``Total_Contract_Value__c` |
| `<label>` | Required | The UI name (Title Case) |
| `<description>` | Mandatory | State the business "why" behind the field |
| `<inlineHelpText>` | Mandatory | Provide actionable guidance for the end-user. Must add value beyond the label (e.g., "Enter the value in USD including tax" instead of just "The amount") |
### External ID Configuration
**Trigger:** If the user mentions "integration," "importing data," "external system ID," or "unique key from [System Name]," set `<externalId>true</externalId>`.
**Applicable Types:** Text, Number, Email
---
## 3. Technical Interplay: Precision, Scale, and Length
To ensure deployment success, follow these mathematical constraints:
### Precision vs. Scale Rules
- `precision` is the total digits; `scale` is the decimal digits
- **Rule:** `precision ≤ 18` AND `scale ≤ precision`
- **Calculation:** Digits to the left of decimal = `precision - scale`
### The "Fixed 255" Rule
For standard TextArea types, the Metadata API requires `<length>255</length>`, even though it isn't configurable in the UI.
### Visible Lines
Mandatory for Long/Rich text and Multi-select picklists to control UI height.
---
## 4. Field Data Types
### 4.1 Simple Attribute Types
| Type | `<type>` Value | Required Attributes |
|------|----------------|---------------------|
| Auto Number | `AutoNumber` | `displayFormat` (must include `{0}`), `startingNumber` |
| Checkbox | `Checkbox` | Default `defaultValue` to `false` |
| Date | `Date` | No precision/length required |
| Date/Time | `DateTime` | No precision/length required |
| Email | `Email` | Built-in format validation |
| Lookup Relationship | `Lookup` | `referenceTo`, `relationshipName`, `deleteConstraint` |
| Master-Detail Relationship | `MasterDetail` | `referenceTo`, `relationshipName`, `relationshipOrder` |
| Number | `Number` | `precision`, `scale` |
| Currency | `Currency` | Default precision: 18, scale: 2 |
| Percent | `Percent` | Default precision: 5, scale: 2 |
| Phone | `Phone` | Standardizes phone number formatting |
| Picklist | `Picklist` | `valueSet` with `valueSetDefinition` and `restricted` |
| Text | `Text` | `length` (Max 255) |
| Text Area | `TextArea` | `<length>255</length>` |
| Text (Long) | `LongTextArea` | `length`, `visibleLines` (default 3) |
| Text (Rich) | `Html` | `length`, `visibleLines` (default 25) |
| Time | `Time` | Stores time only (no date) |
| URL | `Url` | Validates for protocol and format |
### 4.2 Computed & Multi-Value Types
| Type | `<type>` Value | Required Attributes |
|------|----------------|---------------------|
| Formula | Result type (e.g., `Number`) | `formula`, `formulaTreatBlanksAs` |
| Roll-Up Summary | `Summary` | See Section 6 for complete requirements |
| Multi-Select Picklist | `MultiselectPicklist` | `valueSet`, `visibleLines` (default 4) |
### 4.3 Specialized Types
| Type | `<type>` Value | Required Attributes |
|------|----------------|---------------------|
| Geolocation | `Location` | `scale`, `displayLocationInDecimal` |
### Picklist `restricted` Rule
The `<restricted>` boolean inside `<valueSet>` controls whether only admin-defined values are allowed.
- IF user does not specify → default to `<restricted>true</restricted>` (restricted, avoids performance issues with large picklist value sets)
- IF user explicitly says the picklist should allow custom/new values, or mentions "unrestricted" or "open" → set `<restricted>false</restricted>`
- Restricted picklists are limited to 1,000 total values (active + inactive)
```xml
<valueSet>
<restricted>true</restricted>
<valueSetDefinition>
<sorted>false</sorted>
<value>
<fullName>Option_A</fullName>
<default>false</default>
<label>Option A</label>
</value>
</valueSetDefinition>
</valueSet>
```
---
## 5. Master-Detail Relationship Rules ⭐ CRITICAL
Master-Detail fields have **strict attribute restrictions** that differ from Lookup fields. Violating these rules causes deployment failures.
### Forbidden Attributes on Master-Detail Fields
**NEVER include these attributes on Master-Detail fields:**
| Forbidden Attribute | Why | What Happens |
|---------------------|-----|--------------|
| `<required>` | Master-Detail is ALWAYS required by design | Deployment error |
| `<deleteConstraint>` | Master-Detail ALWAYS cascades deletes | Deployment error |
| `<lookupFilter>` | Only supported on Lookup fields | Deployment error |
### Master-Detail vs Lookup Comparison
| Attribute | Master-Detail | Lookup |
|-----------|---------------|--------|
| `<required>` | ❌ FORBIDDEN | ✅ Optional |
| `<deleteConstraint>` | ❌ FORBIDDEN (always CASCADE) | ✅ Required (`SetNull`, `Restrict`, `Cascade`) |
| `<lookupFilter>` | ❌ FORBIDDEN | ✅ Optional |
| `<relationshipOrder>` | ✅ Required (0 or 1) | ❌ Not applicable |
| `<reparentableMasterDetail>` | ✅ Optional | ❌ Not applicable |
| `<writeRequiresMasterRead>` | ✅ Optional | ❌ Not applicable |
### ❌ INCORRECT — Master-Detail with forbidden attributes:
```xml
<CustomField xmlns="http://soap.sforce.com/2006/04/metadata">
<fullName>Account__c</fullName>
<label>Account</label>
<type>MasterDetail</type>
<referenceTo>Account</referenceTo>
<relationshipName>Contacts</relationshipName>
<relationshipOrder>0</relationshipOrder>
<required>true</required> <!-- WRONG: Remove this -->
<deleteConstraint>Cascade</deleteConstraint> <!-- WRONG: Remove this -->
<lookupFilter> <!-- WRONG: Remove this entire block -->
<active>true</active>
<filterItems>
<field>Account.Type</field>
<operation>equals</operation>
<value>Customer</value>
</filterItems>
</lookupFilter>
</CustomField>
```
**Errors:**
- `Master-Detail Relationship Fields Cannot be Optional or Required`
- `Can not specify 'deleteConstraint' for a CustomField of type MasterDetail`
- `Lookup filters are only supported on Lookup Relationship Fields`
### ✅ CORRECT — Master-Detail field:
```xml
<CustomField xmlns="http://soap.sforce.com/2006/04/metadata">
<fullName>Account__c</fullName>
<label>Account</label>
<description>Links this record to its parent Account</description>
<type>MasterDetail</type>
<referenceTo>Account</referenceTo>
<relationshipLabel>Child Records</relationshipLabel>
<relationshipName>ChildRecords</relationshipName>
<relationshipOrder>0</relationshipOrder>
<reparentableMasterDetail>false</reparentableMasterDetail>
<writeRequiresMasterRead>false</writeRequiresMasterRead>
<!-- NO required, deleteConstraint, or lookupFilter -->
</CustomField>
```
### ✅ CORRECT — Lookup field (with optional attributes):
```xml
<CustomField xmlns="http://soap.sforce.com/2006/04/metadata">
<fullName>Related_Account__c</fullName>
<label>Related Account</label>
<description>Optional link to a related Account</description>
<type>Lookup</type>
<referenceTo>Account</referenceTo>
<relationshipLabel>Related Records</relationshipLabel>
<relationshipName>RelatedRecords</relationshipName>
<required>false</required>
<deleteConstraint>SetNull</deleteConstraint>
<lookupFilter>
<active>true</active>
<filterItems>
<field>Account.Type</field>
<operation>equals</operation>
<value>Customer</value>
</filterItems>
<isOptional>false</isOptional>
</lookupFilter>
</CustomField>
```
### Additional Master-Detail Rules
- **Relationship Order:** First Master-Detail on object = `0`, second = `1`
- **Relationship Name:** Must be a plural PascalCase string (e.g., `Travel_Bookings`)
- **Junction Objects:** Use two Master-Detail fields for standard many-to-many (enables Roll-ups)
- **Limit:** Maximum 2 Master-Detail relationships per object. Use Lookup for additional relationships.
---
## 6. Roll-Up Summary Field Rules ⭐ CRITICAL
Roll-up Summary fields have the **highest deployment failure rate**. Follow these rules exactly.
### Required Elements for Roll-Up Summary
| Element | Requirement | Format |
|---------|-------------|--------|
| `<type>` | Required | Always `Summary` |
| `<summaryOperation>` | Required | `count`, `sum`, `min`, or `max` |
| `<summaryForeignKey>` | Required | `ChildObject__c.MasterDetailField__c` |
| `<summarizedField>` | Conditional | Required for `sum`, `min`, `max`. NOT for `count` |
### Forbidden Elements on Roll-Up Summary
**NEVER include these attributes on Roll-Up Summary fields:**
| Forbidden Attribute | Why |
|---------------------|-----|
| `<precision>` | Summary inherits from summarized field |
| `<scale>` | Summary inherits from summarized field |
| `<required>` | Not applicable to Summary fields |
| `<length>` | Not applicable to Summary fields |
### Format Rules for summaryForeignKey and summarizedField
**CRITICAL:** Both `summaryForeignKey` and `summarizedField` MUST use the fully qualified format:
```
ChildObjectAPIName__c.FieldAPIName__c
```
**Decision Logic:**
- `summaryForeignKey` = `ChildObject__c.MasterDetailFieldOnChild__c`
- `summarizedField` = `ChildObject__c.FieldToSummarize__c`
### ❌ INCORRECT — Roll-Up Summary with common errors:
```xml
<CustomField xmlns="http://soap.sforce.com/2006/04/metadata">
<fullName>Total_Amount__c</fullName>
<label>Total Amount</label>
<type>Summary</type>
<precision>18</precision> <!-- WRONG: Remove - inherited from source -->
<scale>2</scale> <!-- WRONG: Remove - inherited from source -->
<summaryOperation>sum</summaryOperation>
<summaryForeignKey>Order__c</summaryForeignKey> <!-- WRONG: Missing field name -->
<summarizedField>Amount__c</summarizedField> <!-- WRONG: Missing object name -->
</CustomField>
```
**Errors:**
- `Can not specify 'precision' for a CustomField of type Summary`
- `Must specify the name in the CustomObject.CustomField format (e.g. Account.MyNewCustomField)`
### ✅ CORRECT — Roll-Up Summary (SUM operation):
```xml
<CustomField xmlns="http://soap.sforce.com/2006/04/metadata">
<fullName>Total_Amount__c</fullName>
<label>Total Amount</label>
<description>Sum of all line item amounts</description>
<inlineHelpText>Automatically calculated from child line items</inlineHelpText>
<type>Summary</type>
<summaryOperation>sum</summaryOperation>
<summarizedField>Order_Line_Item__c.Amount__c</summarizedField>
<summaryForeignKey>Order_Line_Item__c.Order__c</summaryForeignKey>
<!-- NO precision, scale, required, or length -->
</CustomField>
```
### ✅ CORRECT — Roll-Up Summary (COUNT operation):
```xml
<CustomField xmlns="http://soap.sforce.com/2006/04/metadata">
<fullName>Line_Item_Count__c</fullName>
<label>Line Item Count</label>
<description>Count of related line items</description>
<inlineHelpText>Automatically calculated from child records</inlineHelpText>
<type>Summary</type>
<summaryOperation>count</summaryOperation>
<summaryForeignKey>Order_Line_Item__c.Order__c</summaryForeignKey>
<!-- NO summarizedField needed for COUNT -->
<!-- NO precision, scale, required, or length -->
</CustomField>
```
### ✅ CORRECT — Roll-Up Summary (MIN operation):
```xml
<CustomField xmlns="http://soap.sforce.com/2006/04/metadata">
<fullName>Earliest_Due_Date__c</fullName>
<label>Earliest Due Date</label>
<description>Earliest due date among all line items</description>
<inlineHelpText>Shows the soonest deadline</inlineHelpText>
<type>Summary</type>
<summaryOperation>min</summaryOperation>
<summarizedField>Order_Line_Item__c.Due_Date__c</summarizedField>
<summaryForeignKey>Order_Line_Item__c.Order__c</summaryForeignKey>
</CustomField>
```
### ✅ CORRECT — Roll-Up Summary (MAX operation):
```xml
<CustomField xmlns="http://soap.sforce.com/2006/04/metadata">
<fullName>Highest_Price__c</fullName>
<label>Highest Price</label>
<description>Maximum unit price among all line items</description>
<inlineHelpText>Shows the most expensive item</inlineHelpText>
<type>Summary</type>
<summaryOperation>max</summaryOperation>
<summarizedField>Order_Line_Item__c.Unit_Price__c</summarizedField>
<summaryForeignKey>Order_Line_Item__c.Order__c</summaryForeignKey>
</CustomField>
```
### Roll-Up Summary Quick Reference
| Operation | summarizedField Required? | Use Case |
|-----------|---------------------------|----------|
| `count` | NO | Count number of child records |
| `sum` | YES | Add up numeric values |
| `min` | YES | Find smallest value |
| `max` | YES | Find largest value |
### Roll-Up Summary Prerequisites
- Roll-Up Summary fields can ONLY be created on the **parent** object in a Master-Detail relationship
- The child object MUST have a Master-Detail field pointing to this parent
- The summarized field must exist on the child object
---
## 7. Formula Field Rules
### Formula Result Types
A Formula is not a type itself. The `<formula>` tag is added to a field whose `<type>` is set to the **result data type**:
- `Checkbox`, `Currency`, `Date`, `DateTime`, `Number`, `Percent`, `Text`
### Formula XML Generation Rules
- The contents of the `<formula>` tag MUST be wrapped in a `<![CDATA[ ... ]]>` section. This prevents the XML parser from interpreting formula operators (like `&`, `<`, `>`) as XML markup.
- If the formula text itself contains the literal sequence `]]>`, escape it by breaking the CDATA block: e.g., `<![CDATA[Text_Field__c & "]]]]><![CDATA[>"]]>`
- NEVER use an attribute or tag named `returnType`. This does not exist in the Metadata API. The `<type>` tag defines the return data type of the formula result.
### formulaTreatBlanksAs Rule
**Decision Logic:**
- IF formula result type = `Number`, `Currency`, or `Percent` → set `<formulaTreatBlanksAs>BlankAsZero</formulaTreatBlanksAs>`
- IF formula result type = `Text`, `Date`, or `DateTime` → set `<formulaTreatBlanksAs>BlankAsBlank</formulaTreatBlanksAs>`
### ❌ INCORRECT — Using Formula as type:
```xml
<CustomField xmlns="http://soap.sforce.com/2006/04/metadata">
<fullName>Calculated_Value__c</fullName>
<type>Formula</type> <!-- WRONG: Formula is not a valid type -->
<returnType>Number</returnType> <!-- WRONG: returnType does not exist in Metadata API -->
<formula>Field1__c + Field2__c</formula> <!-- WRONG: Missing CDATA wrapper -->
</CustomField>
```
### ✅ CORRECT — Formula field:
```xml
<CustomField xmlns="http://soap.sforce.com/2006/04/metadata">
<fullName>Calculated_Value__c</fullName>
<label>Calculated Value</label>
<description>Sum of Field1 and Field2</description>
<type>Number</type> <!-- Result type, not "Formula" -->
<precision>18</precision>
<scale>2</scale>
<formula><![CDATA[Field1__c + Field2__c]]></formula>
<formulaTreatBlanksAs>BlankAsZero</formulaTreatBlanksAs>
</CustomField>
```
### Formula Field Dependencies
Formula fields that reference other fields will fail deployment if the referenced field does not exist or has not been deployed yet. Ensure all referenced fields are deployed before the formula field.
### Specific Function Guidelines
| Function | Rule |
|----------|------|
| `TEXT()` | MUST NOT be used with Text fields. If the field is already Text, remove the `TEXT()` wrapper. |
| `CASE()` | Last parameter is always the default value. Total parameter count MUST be even (value-result pairs + default). |
| `VALUE()` | MUST only be used with Text fields. If a Number is passed as parameter, remove the `VALUE()` wrapper. |
| `DAY()` | MUST only be used with Date fields. If a DateTime field is used, convert it to Date first (e.g., `DAY(DATEVALUE(DateTimeField__c))`). |
| `MONTH()` | MUST only be used with Date fields. If a DateTime field is used, convert it to Date first (e.g., `MONTH(DATEVALUE(DateTimeField__c))`). |
| `DATEVALUE()` | MUST only be used with DateTime fields. If a Date field is used, remove the `DATEVALUE()` wrapper. |
| `ISPICKVAL()` | MUST be used when checking equality of a Picklist field. NEVER use `==` with Picklist fields. |
| `ISCHANGED()` | Use `ISCHANGED()` to check if a field value has changed. Do not manually compare with `PRIORVALUE()`. |
---
## 8. Common Deployment Errors
| Error Message | Cause | Fix |
|---------------|-------|-----|
| `Field [FieldName] does not exist. Check spelling.` | Referenced field does not exist or has not been deployed yet | Verify the referenced field exists and is deployed before this field |
| `DUPLICATE_DEVELOPER_NAME` | Field fullName already exists on the object | Use a unique business-driven name |
| `MAX_RELATIONSHIPS_EXCEEDED` | More than 2 Master-Detail or 15 Lookup fields on the object | Use Lookup for 3rd+ Master-Detail; review Lookup count |
| Reserved keyword error | Using `Order__c`, `Group__c`, etc. | Rename to `Status_Order__c`, etc. |
---
## 9. Verification Checklist
Before generating CustomField XML, verify:
### Universal Checks
- [ ] Does `<fullName>` use valid format and end in `__c`?
- [ ] Are `<description>` and `<inlineHelpText>` both populated and meaningful?
- [ ] Is `<label>` in Title Case?
### Master-Detail Field Checks ⭐ CRITICAL
- [ ] Is `<required>` attribute ABSENT? (Master-Detail is always required)
- [ ] Is `<deleteConstraint>` attribute ABSENT? (Master-Detail always cascades)
- [ ] Is `<lookupFilter>` block ABSENT? (Only for Lookup fields)
- [ ] Is `<relationshipOrder>` set to `0` or `1`?
- [ ] Is parent object's `<sharingModel>` set to `ControlledByParent`?
### Lookup Field Checks
- [ ] Is `<deleteConstraint>` set to `SetNull`, `Restrict`, or `Cascade`?
- [ ] Is `<relationshipName>` in plural PascalCase?
### Roll-Up Summary Field Checks ⭐ CRITICAL
- [ ] Is `<precision>` attribute ABSENT?
- [ ] Is `<scale>` attribute ABSENT?
- [ ] Is `<summaryForeignKey>` in format `ChildObject__c.MasterDetailField__c`?
- [ ] For SUM/MIN/MAX: Is `<summarizedField>` in format `ChildObject__c.FieldName__c`?
- [ ] For COUNT: Is `<summarizedField>` ABSENT?
- [ ] Does the child object have a Master-Detail field to this parent?
### Formula Field Checks
- [ ] Is `<type>` set to result type (NOT "Formula")?
- [ ] Is `<formula>` content wrapped in `<![CDATA[ ... ]]>`?
- [ ] Is `<returnType>` attribute ABSENT? (does not exist in Metadata API)
- [ ] Is `<formulaTreatBlanksAs>` set to `BlankAsZero` for numeric results or `BlankAsBlank` for text/date results?
- [ ] Do all referenced fields exist and deploy before this field?
### Numeric Field Checks
- [ ] Is `scale ≤ precision`?
- [ ] Is `precision ≤ 18`?
### Text Area Checks
- [ ] For TextArea: Is `<length>255</length>` explicitly included?
- [ ] For LongTextArea/Html: Is `<visibleLines>` set?
### Relationship Limit Checks
- [ ] Are there 2 or fewer Master-Detail relationships on the object?
- [ ] Are there 15 or fewer Lookup relationships on the object?
### Naming Checks
- [ ] Is the API name free of reserved words (`Order`, `Group`, `Select`, etc.)?
- [ ] Is the API name unique on this object?

View File

@ -0,0 +1,157 @@
---
name: salesforce-custom-lightning-type
description: Use this skill when users need to create Custom Lightning Types (CLTs) for Einstein Agent actions or structured input/output schemas. Trigger when users mention CLT, Custom Lightning Types, JSON schemas for agents, type definitions, lightning__objectType, or editor/renderer configurations. This is complex - always use this skill for CLT work.
---
## When to Use This Skill
Use this skill when you need to:
- Create Custom Lightning Types (CLTs) for structured inputs/outputs
- Generate JSON Schema-based type definitions for Lightning Platform
- Configure CLTs for Einstein Agent actions
- Set up editor and renderer configurations for custom UI
- Troubleshoot deployment errors related to Custom Lightning Types
## Specification
# CustomLightningType Metadata Specification
## Overview & Purpose
Custom Lightning Types (CLTs) are JSON Schema-based type definitions used by the Lightning Platform (including Einstein Agent actions) to describe structured inputs/outputs and drive editor/renderer experiences.
## Configuration
- **Choose standard Lightning types** when the structure is simple and can be expressed with properties and supported primitive `lightning:type` identifiers.
- **Choose Apex class types** (`@apexClassType/...`) when the structure already exists server-side and you want the Apex class to define the shape.
- **Include editor/renderer config** only when you need custom UI behavior (custom LWC input/output components). Otherwise, omit.
## Critical Rules (Read First)
- **Root object schemas MUST include**:
- `"type": "object"`
- `"title"`
- `"lightning:type": "lightning__objectType"`
- `"unevaluatedProperties": false`
- `"unevaluatedProperties"` is enforced as `false` by the CLT metaschema. Do not set it to `true`.
- **Root object schemas MUST NOT include** `"examples"` when `"unevaluatedProperties": false` is set.
- **Nested objects (inside `properties`) MUST NOT set** `"lightning:type": "lightning__objectType"`.
- Nested objects should be plain JSON Schema objects (`type`, `properties`, optional `required`, optional `unevaluatedProperties`).
- **List/array properties are highly restricted by the CLT metaschema**:
- **CRITICAL LIMITATION**: the CLT metaschema may reject the `items` keyword entirely. Treat `items` as **disallowed by default**.
- **Root-level arrays** (direct children of the root `properties`):
- **MUST include** `"lightning:type": "lightning__listType"`
- **MUST NOT include** `"items"`
- **OPTIONAL** `"type": "array"`
- **Nested arrays** (arrays inside nested objects) are the most common failure:
- **MUST include** `"type": "array"`
- **MUST NOT include** `"lightning:type": "lightning__listType"`
- **MUST NOT include** `"items"`
- **When `"unevaluatedProperties": false` is set, any unknown keyword will fail validation**. Prefer removing keywords over relaxing strictness.
- **Apex class CLTs are minimal**:
- Include **only** `title`, `description` (optional), and `lightning:type` set to `@apexClassType/...`.
- Do **not** add `type`, `properties`, `required`, or `unevaluatedProperties`.
## Additional CLT Metaschema Validations
- **Org namespace validation**: titles/descriptions and other string fields may be validated to ensure you are not using an org namespace in places that are disallowed.
- **Lightning type validation**: CLTs are validated to prevent referencing internal namespaces (for example, disallowing types from internal namespaces like `sfdc_cms` where not permitted).
- **Object type validation**: the CLT root is validated to ensure `lightning:type` is exactly `lightning__objectType`.
## Primitive Types & Constraints
- `lightning__textType`
- Max length 255
- `lightning__multilineTextType`
- Max length 2000
- `lightning__richTextType`
- Max length 100000
- `lightning__urlType`
- Max length 2000
- Optional `lightning:allowedUrlSchemes` enum values: `https`, `http`, `relative`, `mailto`, `tel`
- `lightning__dateType`
- Data pattern: YYYY-MM-DD
- `lightning__timeType`
- Data pattern: HH:MM:SS.sssZ
- `lightning__dateTimeType`
- Data shape is an object with required `dateTime` and optional `timeZone`
- `lightning__numberType`
- Decimal numbers; optional `maximum`, `minimum`, `multipleOf`
- `lightning__integerType`
- Whole numbers only; optional `maximum`, `minimum`
- `lightning__booleanType`
- true/false
## Allowed Property-Level Keywords
When strict validation is enabled (`unevaluatedProperties: false`), keep each property minimal and prefer only keywords known to be allowed:
- `title`, `description`, `einstein:description`
- `type` (when used, ensure it matches the chosen `lightning:type`)
- `lightning:type`
- `maximum`, `minimum`, `multipleOf` (numeric)
- `maxLength`, `minLength` (string)
- `const`, `enum`
- `lightning:textIndexed`, `lightning:supportsPersonalization`, `lightning:localizable`
- `lightning:uiOptions`, `lightning:allowedUrlSchemes`
- `lightning:tags` (metaschema restricts values; currently `flow` is the only known allowed tag)
## Generation Workflow
1. **Confirm the CLT approach**
- If referencing Apex: capture the exact class reference (`@apexClassType/namespace__ClassName$InnerClass`).
- If using standard primitives: list the fields, their Lightning primitive types, and which fields are required.
2. **Draft `schema.json`**
- Start with the root object structure (required root fields).
- Add `properties` using valid primitive `lightning:type` identifiers.
- For nested objects: omit `lightning:type` and keep keywords minimal.
- For arrays: follow the strict list rules (avoid `items`; avoid `lightning:type` on nested arrays).
3. **(Optional) Draft `editor.json`** (only if custom UI is required)
- **Supported shape:** Top-level `editor` object with `editor.componentOverrides` and `editor.layout`.
- Top-level `editor` object.
- Use `editor.componentOverrides` for component overrides.
- Use `editor.layout` for layout.
- **Root override pattern** (most common for fully custom editing UI):
- `editor.componentOverrides["$"] = { "definition": "c/<yourEditorComponent>", "attributes": { ... } }`
- When passing schema data into a custom LWC, use attribute mapping with the `{!$attrs.<name>}` syntax: e.g. `"attributes": { "myField": "{!$attrs.value}" }` so the runtime binds schema values to your component's attributes.
- **Property-level override pattern** (for individual fields):
- `editor.componentOverrides["<propertyName>"] = { "definition": "es_property_editors/<...>" }`
- **Valid editor components** (examples): `es_property_editors/inputText`, `es_property_editors/inputNumber`, `es_property_editors/inputRichText`, `es_property_editors/inputImage`, `es_property_editors/inputTextarea`. **Do not use** `es_property_editors/inputList`.
- **Collection editor** (for root-level `lightning__listType` properties): Use a collection-level override so the list is edited by a custom component: `collection.editor.componentOverrides["$"] = { "definition": "c/<yourCollectionEditorComponent>" }`. Alternatively, use `editor.layout` with `lightning/propertyLayout` and `attributes.property = "<listPropertyName>"` for default list editing.
- **Layout pattern**:
- `editor.layout.definition = "lightning/verticalLayout"`
- `editor.layout.children[*].definition = "lightning/propertyLayout"` with `attributes.property = "<propertyName>"`
- **Avoid known-invalid patterns**:
- Do not use `es_property_editors/inputList`.
- Do not use `itemSchema` attributes.
4. **(Optional) Draft `renderer.json`** (only if custom UI is required)
- **Supported shape:** Top-level `renderer` object with `renderer.componentOverrides` and `renderer.layout`.
- Top-level `renderer` object.
- Use `renderer.componentOverrides` for component overrides.
- Use `renderer.layout` for layout.
- **Root override pattern** (most common for fully custom rendering UI):
- `renderer.componentOverrides["$"] = { "definition": "c/<yourRendererComponent>", "attributes": { ... } }`
- Use `{!$attrs.<name>}` in attribute mappings when binding schema data to custom renderer component attributes.
- **Property-level override pattern**:
- `renderer.componentOverrides["<propertyName>"] = { "definition": "es_property_editors/outputText" | "es_property_editors/outputNumber" | "es_property_editors/outputImage" | ... }`. **Valid renderer components** (examples): `es_property_editors/outputText`, `es_property_editors/outputNumber`, `es_property_editors/outputImage`. Avoid input-style components in the renderer.
- **Collection renderer** (for root-level `lightning__listType` properties): Use `collection.renderer.componentOverrides["$"] = { "definition": "c/<yourListRendererComponent>" }` or `es_property_editors/genericListTypeRenderer` to render the list.
5. **Place files in the correct bundle structure**
- `lightningTypes/<TypeName>/schema.json`
- (Optional) `lightningTypes/<TypeName>/lightningDesktopGenAi/editor.json`
- (Optional) `lightningTypes/<TypeName>/lightningDesktopGenAi/renderer.json`
- For Gen AI / Copilot the standard path is `lightningDesktopGenAi/`. Other targets (e.g. Experience Builder, Mobile Copilot, Enhanced Web Chat) use different subfolders when supported: `experienceBuilder/`, `lightningMobileGenAi/`, `enhancedWebChat/`.
6. **Deploy and validate**
- Deploy the bundle using your org's standard metadata deployment flow (e.g. Salesforce CLI or IDE). The MCP client or tooling in use should provide or integrate with the appropriate deploy/retrieve commands for Lightning Type bundles.
- Validate incrementally: if deployment fails, remove disallowed keywords first (especially `examples`, `items`, nested `lightning:type`).
## Common Deployment Errors
| Error / Symptom | Likely Cause | Fix |
|---|---|---|
| Schema validation fails due to unknown keyword | `unevaluatedProperties: false` + disallowed keyword (commonly `examples`, `items`) | Remove the offending keyword; keep schema minimal |
| Nested object validation failure | Nested object includes `lightning:type: lightning__objectType` | Remove `lightning:type` from nested objects |
| Array property rejected | Use of `items` (or `lightning:type` in nested arrays) rejected by validator | For nested arrays: keep only `type: "array"`. For root arrays: use minimal structure; remove `items` if rejected |
| Apex-based CLT rejected | Extra fields added (e.g., `type`, `properties`) | Use only `title`, optional `description`, and `lightning:type` |
| Editor config rejected | Use of invalid patterns (`es_property_editors/inputList`, `itemSchema`) or unrecognized top-level keys | Use `editor.componentOverrides` and `editor.layout`; keep config minimal |
## Verification Checklist
- [ ] Root schema has `type: "object"`, `title`, `lightning:type: "lightning__objectType"`, and `unevaluatedProperties: false`
- [ ] Root schema does not include `examples` when strict validation is enabled
- [ ] No nested object includes `lightning:type: "lightning__objectType"`
- [ ] Arrays are defined minimally (especially nested arrays)
- [ ] Only supported primitive `lightning:type` identifiers are used for leaf properties
- [ ] Apex class CLTs contain only `title`/`description` and `lightning:type: "@apexClassType/..."`
- [ ] Bundle structure and filenames match Lightning Types requirements
- [ ] Editor config uses only allowed patterns (no `es_property_editors/inputList`, no `itemSchema`); use valid components (e.g. `es_property_editors/inputText`, `es_property_editors/inputNumber`) or custom `c/` components
- [ ] Renderer config uses output-style components (e.g. `es_property_editors/outputText`, `es_property_editors/outputNumber`) where applicable, not input editors

View File

@ -0,0 +1,236 @@
---
name: salesforce-custom-object
description: Use this skill when users need to create, generate, or validate Salesforce Custom Object metadata. Trigger when users mention custom objects, creating objects, object metadata, .object files, sharing models, name fields, or validation rules on objects. Also use when users say things like "create a custom object", "generate object metadata", "set up an object for...", or when they're troubleshooting object deployment errors especially around sharing models and Master-Detail relationships. Always use this skill for any custom object metadata work.
---
## When to Use This Skill
Use this skill when you need to:
- Create new custom objects
- Generate custom object metadata XML
- Configure object sharing and security settings
- Set up object features and capabilities
- Troubleshoot deployment errors related to custom objects
## Specification
## 1. Overview and Purpose
This document defines the mandatory constraints for generating CustomObject metadata XML (`.object` file). The agent must verify these constraints before outputting XML to prevent Metadata API deployment errors.
---
## 2. Syntactic Essentials (Tier 1)
The following constraints must be true for the XML body to deploy successfully.
**Note:** The API Name (fullName) is NOT a tag; it is the filename (e.g., `Vehicle__c.object`).
### Required Elements
| Element | Requirement | Notes |
|---------|-------------|-------|
| `<label>` | Required | Singular UI name |
| `<pluralLabel>` | Required | Plural UI name |
| `<sharingModel>` | Required | See Sharing Model Rules below |
| `<deploymentStatus>` | Required | Always set to `Deployed` |
| `<nameField>` | Required | Primary record identifier (requires `<label>` and `<type>`) |
| `<visibility>` | Required | Always set to `Public` |
### Sharing Model Rules
**Default:** Set `<sharingModel>` to `ReadWrite`.
**Exception:** If this object contains a Master-Detail relationship field, `<sharingModel>` MUST be `ControlledByParent`.
**Decision Logic:**
- IF object has NO Master-Detail field → use `ReadWrite`
- IF object has Master-Detail field → use `ControlledByParent`
- IF a Master-Detail field is being added to an existing child object → that existing object's `<sharingModel>` must also be updated to `ControlledByParent`
**❌ INCORRECT** — Will cause error: `Cannot set sharingModel to ReadWrite on a CustomObject with a MasterDetail relationship field`
```xml
<CustomObject xmlns="http://soap.sforce.com/2006/04/metadata">
<label>Order Line Item</label>
<pluralLabel>Order Line Items</pluralLabel>
<sharingModel>ReadWrite</sharingModel> <!-- WRONG: Object has a M-D field -->
<deploymentStatus>Deployed</deploymentStatus>
</CustomObject>
```
**✅ CORRECT:**
```xml
<CustomObject xmlns="http://soap.sforce.com/2006/04/metadata">
<label>Order Line Item</label>
<pluralLabel>Order Line Items</pluralLabel>
<sharingModel>ControlledByParent</sharingModel> <!-- CORRECT -->
<deploymentStatus>Deployed</deploymentStatus>
</CustomObject>
```
---
## 3. Smart Defaults & Decision Logic (Tier 2)
The agent must choose which features to enable based on the object's intended use case.
### A. The Name Field Decision
| Type | When to Use | Additional Requirements |
|------|-------------|------------------------|
| **Text** | Default for human-named entities (Projects, Locations, Teams) | None |
| **AutoNumber** | Use for transactions, logs, or IDs (Invoices, Requests, Tickets) | Must include `<displayFormat>` (e.g., `INV-{0000}`) and `<startingNumber>1</startingNumber>` |
**Text Name Field Example:**
```xml
<nameField>
<label>Project Name</label>
<type>Text</type>
</nameField>
```
**AutoNumber Name Field Example:**
```xml
<nameField>
<label>Invoice Number</label>
<type>AutoNumber</type>
<displayFormat>INV-{0000}</displayFormat>
<startingNumber>1</startingNumber>
</nameField>
```
### B. Object Description
**`<description>`**: Mandatory. Every object must contain a professional summary.
If the intent is vague, generate a summary:
> "Object used to track and manage [Intent] within the organization."
### C. Junction Object Naming
If the object is a many-to-many link between two parents, name the object by combining the two parent entities to ensure the schema remains intuitive.
**Examples:**
- `Position_Candidate__c` (links Position and Candidate)
- `Job_Application__c` (links Job and Application)
### D. Feature Enablement (Clean XML)
To maintain "Clean XML," only include optional tags when deviating from the Salesforce platform default of `false`.
**Scenario A: User-Facing Objects (Apps, Trackers, Business Entities)**
- Trigger: The object is intended for direct user interaction
- Action: Set `<enableSearch>`, `<enableReports>`, `<enableActivities>`, and `<enableHistory>` to `true`
**Scenario B: System-Facing Objects (Junctions, Background Logs)**
- Trigger: The object exists for technical associations or background data
- Action: Omit these tags to keep the UI clean and the XML lean
---
## 4. Critical Constraints & Common Failures
### Reserved Words
Never use reserved words as API names for Custom Objects or Custom Fields:
| Category | Reserved Words (Do Not Use as API Names) |
|----------|------------------------------------------|
| SOQL/SQL | `Select`, `From`, `Where`, `Limit`, `Order`, `Group` |
| System | `User`, `External`, `View`, `Type` |
| Temporal | `Date`, `Number` |
### Relationship Cap
Do not create more than **2 Master-Detail relationships** for a single object. If a third relationship is required, use a Lookup instead.
### XML Root Element
Do NOT include the `<fullName>` tag at the root of the `.object` XML file. The API name is derived from the filename.
**❌ INCORRECT:**
```xml
<CustomObject xmlns="http://soap.sforce.com/2006/04/metadata">
<fullName>Vehicle__c</fullName> <!-- WRONG: Remove this -->
<label>Vehicle</label>
</CustomObject>
```
**✅ CORRECT:**
```xml
<CustomObject xmlns="http://soap.sforce.com/2006/04/metadata">
<label>Vehicle</label>
<!-- fullName comes from filename: Vehicle__c.object -->
</CustomObject>
```
### Validation Rule Naming Convention
Validation rule names follow different conventions than custom fields.
**Rules:**
- Must contain only alphanumeric characters and underscores
- Must begin with a letter
- Cannot end with an underscore
- Cannot contain two consecutive underscores
- **Must NOT end with `__c`** (unlike custom fields)
**❌ INCORRECT:**
```xml
<validationRules>
<fullName>Require_Start_Date__c</fullName> <!-- WRONG: Has __c suffix -->
<active>true</active>
<errorMessage>Start Date is required.</errorMessage>
<formula>ISBLANK(Start_Date__c)</formula>
</validationRules>
```
**Error:** `The validation name can only contain alphanumeric characters, must begin with a letter, cannot end with an underscore...`
**✅ CORRECT:**
```xml
<validationRules>
<fullName>Require_Start_Date</fullName> <!-- CORRECT: No __c suffix -->
<active>true</active>
<errorMessage>Start Date is required.</errorMessage>
<formula>ISBLANK(Start_Date__c)</formula>
</validationRules>
```
**Naming Pattern Reference:**
| Metadata Type | Naming Pattern | Example |
|---------------|----------------|---------|
| Custom Fields | Ends with `__c` | `Start_Date__c` |
| Validation Rules | No suffix | `Require_Start_Date` |
| Custom Objects | Ends with `__c` | `Vehicle__c` |
---
## 5. Verification Checklist
Before generating the Custom Object XML, verify:
### Syntactic Checks
- [ ] Are both `<label>` and `<pluralLabel>` present?
- [ ] Is `<deploymentStatus>` set to `Deployed`?
- [ ] Is `<visibility>` set to `Public`?
- [ ] Does `<nameField>` include both `<label>` and `<type>`?
- [ ] If `<type>` is `AutoNumber`, are `<displayFormat>` and `<startingNumber>` included?
### Sharing Model Check (Critical)
- [ ] Does this object have a Master-Detail relationship field?
- If YES → `<sharingModel>` MUST be `ControlledByParent`
- If NO → `<sharingModel>` should be `ReadWrite`
### Constraint Checks
- [ ] Is the API name free of reserved words?
- [ ] Are there 2 or fewer Master-Detail relationships?
- [ ] Is `<fullName>` absent from the XML root?
### Validation Rule Checks (if applicable)
- [ ] Do validation rule names NOT end with `__c`?
- [ ] Do validation rule names follow alphanumeric + underscore pattern?
### Architectural Checks
- [ ] Is `<description>` present with a meaningful summary?
- [ ] Are `<enableSearch>` and `<enableReports>` set to `true` if user-facing?
- [ ] Does the filename match the intended API name?

View File

@ -0,0 +1,78 @@
---
name: salesforce-custom-tab
description: Use this skill when users need to create or configure Salesforce Custom Tabs. Trigger when users mention tabs, navigation tabs, object tabs, web tabs, Visualforce tabs, Lightning component tabs, app page tabs, or tab configuration. Also use when users want to add navigation to custom objects, create tabs for external content, or set up Lightning page tabs. Always use this skill for any custom tab work.
---
## When to Use This Skill
Use this skill when you need to:
- Create tabs for objects, web pages, or Visualforce pages
- Add navigation tabs to applications
- Configure tab visibility and access
- Troubleshoot deployment errors related to custom tabs
## Specification
# CustomTab Metadata Specification
## 📋 Overview
Custom tabs for navigating to objects, web content, or Visualforce pages within Salesforce applications.
## 🎯 Purpose
- Provide navigation to custom objects
- Link to external web content
- Access Visualforce pages
- Organize application navigation
## ⚙️ Required Properties
### Core Tab Properties
- **label**: Display name of the tab
- **fullName**: API name of the object (for object tabs)
- **url**: Web URL (for web tabs)
- **page**: Visualforce page name (for Visualforce tabs)
## 🔧 Tab Types
### Object Tabs
- **Purpose**: Navigate to custom or standard objects
- **Required**: `fullName` property (set to object API name)
- **Example**: `<fullName>CustomObject__c</fullName>`
### Web Tabs
- **Purpose**: Link to external websites or web applications
- **Required**: `url` property
- **Example**: `<url>https://example.com</url>`
### Visualforce Tabs
- **Purpose**: Access custom Visualforce pages
- **Required**: `page` property
- **Example**: `<page>CustomPage</page>`
## 🎨 Tab Configuration
### Tab Style
- **Default**: Use standard tab styling
- **Custom**: Can specify custom tab styles if needed
### Tab Visibility
- **Default**: Visible to all users with access
- **Custom**: Can be configured for specific user profiles
## 📱 Supported Applications
- **Standard Apps**: Available in standard Salesforce applications
- **Custom Apps**: Can be included in custom applications
- **Community Apps**: Available in community applications
## 🔗 Integration Points
- **Object Relationships**: Links to related object records
- **Web Content**: External website integration
- **Visualforce Pages**: Custom page functionality
- **Lightning Components**: Modern component integration
## ✅ Best Practices
- Use clear, descriptive tab labels
- Choose appropriate tab types for functionality
- Consider user experience and navigation flow
- Test tab functionality across different applications
- Ensure proper permissions and visibility settings
- Follow consistent naming conventions

View File

@ -0,0 +1,178 @@
---
name: salesforce-experience-site
description: Use this skill when users need to create, modify, or manage Salesforce Experience Cloud sites (LWR sites). Trigger when users mention Experience sites, LWR sites, DigitalExperience, Experience Cloud, community sites, portals, creating pages, adding routes, views, theme layouts, branding sets, or any DigitalExperience bundle work. Also use when users mention specific content types like sfdc_cms__route, sfdc_cms__view, sfdc_cms__themeLayout, or when troubleshooting site deployment. Always use this skill for any Experience Cloud or LWR site work.
---
## When to Use This Skill
Use this skill when you need to:
- Create Experience Cloud sites or communities
- Build LWR (Lightning Web Runtime) sites
- Set up site configuration and settings
- Generate Experience Site metadata
- Troubleshoot deployment errors related to Experience Sites
## Specification
# Experience LWR Site Metadata Specification
An LWR site can be represented by metadata DigitalExperienceConfig, DigitalExperienceBundle, Network, CustomSite, and CMS contents. Your purpose is to assist developers in creating and editing these metadata.
## Supported Template Types
Template name - Template DevName
- Build Your Own (LWR) - talon-template-byo
## Core Properties
Before doing anything else, identify the following properties from the local project if available. Check with the user if any of the following is missing:
- Site name: Required. (e.g., `'My Community'`).
- URL path prefix: Optional. Alphanumeric characters only. Convert from site name if not provided (e.g., `'mycommunity'`) and verify with the user for the converted value.
- Template type devName: Optional. Defaults to `talon-template-byo`.
## General Tips
TIP 1. When available, the site developer name can be found in the CustomSite filename (e.g., `sites/MySite.site-meta.xml` → developer name is `MySite`).
## Project Structure in DigitalExperienceBundle Format
### Site Metadata
- DigitalExperienceConfig
- Path: `digitalExperienceConfigs/{siteName}1.digitalExperienceConfig-meta.xml`
- DigitalExperienceBundle
- Path: `digitalExperiences/site/{siteName}1/{siteName}1.digitalExperience-meta.xml`
- Network
- Path: `networks/{siteName}.network-meta.xml`
- CustomSite
- Path: `sites/{siteName}.site-meta.xml`
### DigitalExperience Contents
- Path: `digitalExperiences/site/{siteName}1/sfdc_cms__*/{contentApiName}/*`
- Description: These are the content components defining routes, views, theme layouts, etc. Each component must have a `_meta.json` and `content.json` file.
#### Content Type Descriptions
| Content Type | Description | When to Use |
|-|-|-|
| `sfdc_cms__site` | Root site configuration containing site-wide settings | Required for every site; one per site |
| `sfdc_cms__appPage` | Application page container that groups routes and views | Required; defines the app shell |
| `sfdc_cms__route` | URL routing definition mapping paths to views | Create one for each page/URL path |
| `sfdc_cms__view` | Page layout and component structure | Create one for each route; defines page content. Also use to edit existing views (e.g., adding/removing components, updating theme layout) |
| `sfdc_cms__brandingSet` | Brand colors, fonts, and styling tokens | Required; defines site-wide styling |
| `sfdc_cms__languageSettings` | Language and localization configuration | Required; defines supported languages |
| `sfdc_cms__mobilePublisherConfig` | Mobile app publishing settings | Required for mobile app deployment |
| `sfdc_cms__theme` | Theme definition referencing layouts and branding | Required; one per site |
| `sfdc_cms__themeLayout` | Page layout templates used by views | Create layouts for different page structures |
**Important:** Creating any new pages require BOTH `sfdc_cms__route` AND `sfdc_cms__view`.
## CUD Operations on DigitalExperience Contents
- Users can perform create, update, delete operations on DigitalExperience Contents.
- **IMPORTANT:** Before ANY modification (create, update, or delete) to content, ALWAYS call `execute_metadata_action` first to get the schema, examples, and instructions for that content type.
- **Call once per content type per user request**: If you're creating/modifying multiple items of the same content type (e.g., creating 3 routes), you only need to call `execute_metadata_action` ONCE for that content type. Reuse the schema and examples for all items of that type within the same user request.
- For each unique content type you need to work with, call `execute_metadata_action` using the following:
```json
{
"metadataType": "ExperienceSite",
"actionName": "getSiteContentMetadata",
"parameters": {
"contentType": "<content type from table above>",
"shouldIncludeExamples": true
}
}
```
- Do not call the `execute_metadata_action` MCP tool with any other site actionName unless specified in this knowledge doc/instructions.
## Retrieving Site URLs After Deployment
After successfully deploying the site using `sf project deploy`, use the `execute_metadata_action` MCP tool to get the preview and builder URLs:
```json
{
"metadataType": "ExperienceSite",
"actionName": "getSiteUrls",
"parameters": {
"siteDevName": "<site developer name>"
}
}
```
Refer to TIP 1 to get the site developer name.
If the site is not found, an error message will be returned indicating that the site may not be deployed. Ensure the site has been successfully deployed before calling this action.
## Enhancement Rules
- If need to understand how site metadata should be configured, use the `get_metadata_api_context` MCP tool to get the schemas.
- Use MCP tool `execute_metadata_action` with `getSiteTemplateMetadata` to get the knowledge document about the template and its default configurations if needed. **IMPORTANT:** This MUST be used for new site:
```json
{
"metadataType": "ExperienceSite",
"actionName": "getSiteTemplateMetadata",
"parameters": {
"templateDevName": "<template DevName, e.g. talon-template-byo>"
}
}
```
- To validate Experience Site metadata, run CLI command `sf project deploy validate --metadata DigitalExperienceBundle DigitalExperience DigitalExperienceConfig Network CustomSite --target-org ${usernameOrAlias}`
## Guest User Sharing Rules (Public Sites Only)
**When to use**: Only create guest sharing rules when the user explicitly wants to make the site **public** (accessible to unauthenticated visitors). If the site is private/login-required, guest sharing rules are not needed.
If sharingRules metadata is not available locally in force-app/main/default/sharingRules, retrieve it from the org before creating new rules.
To get the full SharingRules schema, use the `get_metadata_api_context` MCP tool:
```json
{
"metadataType": "SharingRules"
}
```
### XML Example
```xml
<?xml version="1.0" encoding="UTF-8"?>
<SharingRules xmlns="http://soap.sforce.com/2006/04/metadata">
<sharingGuestRules>
<fullName>ShareAccountsWithSiteGuest</fullName>
<accessLevel>Read</accessLevel>
<includeHVUOwnedRecords>false</includeHVUOwnedRecords>
<label>Share Accounts With Site Guest</label>
<sharedTo>
<guestUser>[site developer name]</guestUser>
</sharedTo>
<criteriaItems>
<field>Name</field>
<operation>notEqual</operation>
<value>null</value>
</criteriaItems>
</sharingGuestRules>
</SharingRules>
```
Refer to TIP 1 to get the site developer name.
### Critical Requirements
1. **SharedTo Element**: Must use `<guestUser>{siteName}</guestUser>` where `{siteName}` is the Network name (not URL path prefix).
2. **includeHVUOwnedRecords**: Required field. Set to `false` unless records owned by high-volume site users should be included.
3. **One XML file per object**: Put all rules for a given object in one file. Do not create additional.
### Common Mistakes
- Using `<role>` or `<group>` instead of `<guestUser>` in sharedTo
- Omitting the required `includeHVUOwnedRecords` field
- Using `includeRecordsOwnedByAll` (that's for `sharingCriteriaRules`, not guest rules)
## Workflows
### Creating a new site
- Verify with user on the value of site name, url path prefix, and site template type.
- Retrieve template information from `getSiteTemplateMetadata` and strictly follow the rules of its knowledge document.
- Proceed to the workflow of editing an existing site.
### Editing an existing site
- Identify the intent of the user and break it down into steps.
- Make use of `get_metadata_api_context` if user wants to edit site metadata.
- Use `getSiteContentMetadata` to understand how to edit site contents.
- Once the tasks are done, perform site metadata validation.

View File

@ -0,0 +1,471 @@
---
name: salesforce-flexipage
description: Use this skill when users need to create, generate, modify, or validate Salesforce Lightning pages (FlexiPages). Trigger when users mention RecordPage, AppPage, HomePage, Lightning pages, page layouts, adding components to pages, or page customization. Also use when users say things like "create a Lightning page", "add a component to a page", "customize the record page", "generate a FlexiPage", or when they're working with FlexiPage XML files and need help with components, regions, or deployment errors. Always use this skill for any FlexiPage-related work, even if they just mention "page" in the context of Salesforce.
---
## When to Use This Skill
Use this skill when you need to:
- Create Lightning pages (Record, App, or Home pages)
- Build custom page layouts in Lightning Experience
- Add components to Lightning pages
- Configure page structure and components
- Troubleshoot deployment errors related to FlexiPages
# FlexiPage Generation Guide
## Overview
Generate Lightning pages (RecordPage, AppPage, HomePage) using CLI bootstrapping + MCP actions for component discovery and configuration.
---
## Quick Start Workflow
### Step 1: Bootstrap with CLI
```bash
sf template generate flexipage \
--name <PageName> \
--template <RecordPage|AppPage|HomePage> \
--sobject <SObject> \
--primary-field <Field1> \
--secondary-fields <Field2,Field3> \
--detail-fields <Field4,Field5,Field6,Field7> \
--output-dir force-app/main/default/flexipages
```
**Template-specific requirements:**
- **RecordPage**: Requires `--sobject` (e.g., Account, Custom_Object__c)
- **RecordPage**: Requires `--primary-field` and `--secondary-fields` for dynamic highlights, `--detail-fields` for full record details. Use the most important identifying field as primary, e.g. Name. Use the secondary fields (max 12, recommended 4-6) to show a summary of the record. Use Use detail fields to show the full details of the record.
- **AppPage**: No additional requirements
- **HomePage**: No additional requirements
**What you get:**
- Valid FlexiPage XML with correct structure
- Pre-configured regions and basic components
- Proper field references and facet structure
- Ready to deploy as-is or enhance further
### Step 2: Deploy Base Page
```bash
sf project deploy start --source-dir force-app/main/default/flexipages
```
**Deploy early, deploy often.** Start with the bootstrapped page, validate it works, then enhance.
### Step 3: Enhance with MCP Actions (Optional)
If you need to add more components or customize:
#### A. Discover Available Components
```
DISCOVER_UI_COMPONENTS
```
Returns: List of components available for this page type with descriptions.
#### B. Get Component Schemas
```
GET_UI_COMPONENT_SCHEMAS
```
Returns: JSON schemas showing required/optional properties, types, data sources. Also includes instructions specific to each component.
#### C. Get Data Source Values
```
GET_DATA_SOURCE_VALUES
```
Returns: Valid values for properties with data sources.
### Step 4: Update and Redeploy
Modify the generated XML, adding components discovered via MCP. Deploy incrementally.
---
## Critical XML Rules
### 1. Property Value Encoding (MOST COMMON ERROR)
**Any property value with HTML/XML characters MUST be manually encoded in the following order** (wrong order causes double-encoding corruption):
```
1. &&amp; (FIRST! Encode this before others)
2. <&lt;
3. > → &gt;
4. " → &quot;
5. ' → &apos;
```
**Wrong:**
```xml
<value><b>Important</b> text</value>
```
**Correct:**
```xml
<value>&lt;b&gt;Important&lt;/b&gt; text</value>
```
**Check your XML:** Search for `<value>` tags - they should never contain raw `<` or `>` characters.
### 2. Field References
**ALWAYS:** `Record.{FieldApiName}`
**NEVER:** `{ObjectName}.{FieldApiName}`
```xml
<!-- Correct -->
<fieldItem>Record.Name</fieldItem>
<!-- Wrong -->
<fieldItem>Account.Name</fieldItem>
```
### 3. Region vs Facet Types
**Template Regions** (header, main, sidebar):
```xml
<name>header</name>
<type>Region</type>
```
**Component Facets** (internal slots like fieldSection columns):
```xml
<name>Facet-12345</name>
<type>Facet</type>
```
**Rule:** If it's a template region name → `Region`. If it's a component slot → `Facet`.
### 4. fieldInstance Structure
Every fieldInstance requires:
```xml
<itemInstances>
<fieldInstance>
<fieldInstanceProperties>
<name>uiBehavior</name>
<value>none</value> <!-- none|readonly|required -->
</fieldInstanceProperties>
<fieldItem>Record.FieldName__c</fieldItem>
<identifier>RecordFieldName_cField</identifier>
</fieldInstance>
</itemInstances>
```
**Rules:**
- Each fieldInstance in its own `<itemInstances>` wrapper
- Must have `fieldInstanceProperties` with `uiBehavior`
- Use `Record.{Field}` format
---
## Using MCP Actions
### When to Use Each Action
#### DISCOVER_UI_COMPONENTS
**When:** You want to see what components are available for your page type.
**Returns:** Component list with names, namespaces, descriptions.
**Use for:** Finding components to add to your bootstrapped page.
#### GET_UI_COMPONENT_SCHEMAS
**When:** You know which components you want but need to understand their properties. If you have issues configuring a component and need more detailed instructions or knowledge.
**Returns:** JSON schemas with:
- Required vs optional properties
- Property types (string, boolean, array, etc.)
- Data source references
- Descriptions
- Additional component-specific instructions or knowledge, often useful for more complex components.
**Use for:** Understanding how to configure components before adding to XML.
#### GET_DATA_SOURCE_VALUES
**When:** A component property references a data source and you need valid values.
**Returns:** Valid values (e.g., "1", "2", "3" for column count).
**Use for:** Ensuring property values match allowed options.
---
## Common Deployment Errors
### "Invalid field reference"
**Cause:** Used `ObjectName.Field` instead of `Record.Field`
**Fix:** Change to `Record.{FieldApiName}`
### "Element fieldInstance is duplicated"
**Cause:** Multiple fieldInstances in one itemInstances
**Fix:** Each fieldInstance needs its own `<itemInstances>` wrapper
### "Missing fieldInstanceProperties"
**Cause:** No uiBehavior specified
**Fix:** Add `fieldInstanceProperties` with `uiBehavior`
### "Invalid component property"
**Cause:** Wrong property name or format
**Fix:** Use `GET_UI_COMPONENT_SCHEMAS` to see exact property names and types, or to find additional documentation.
### "Unused Facet"
**Cause:** Facet defined but not referenced by any component
**Fix:** Remove Facet or reference it in a component property
### "XML parsing error"
**Cause:** Unencoded HTML/XML in property values
**Fix:** Manually encode `<`, `>`, `&`, `"`, `'` in all `<value>` tags
### "Cannot create component with namespace"
**Cause:** Invalid page name (don't use `__c` suffix in page names)
**Fix:** Use "Volunteer_Record_Page" not "Volunteer__c_Record_Page"
### "Region specifies mode that parent doesn't support"
**Cause:** Added `<mode>` tag to region
**Fix:** Remove `<mode>` tags - they're not needed for standard regions
---
## Component-Specific Tips
### dynamicHighlights (RecordPage Header)
**Location:** Must be in `header` region.
**Explicit Fields** (via CLI): Use the most important fields to show a summary of the record. The single primary field is used to identify the record, like a name. The secondary fields (max 12, recommended 6) are used as a summary of the record.
```bash
--primary-field Name
--secondary-fields Phone,Industry,AnnualRevenue
```
CLI generates Facets with field references automatically.
### fieldSection
**Use for:** Displaying fields in columns.
**Structure:** Three-level nesting:
1. Template Region (Region type)
2. Column Facets (Facet type)
3. Field Facets (Facet type)
**Referenced in component property:**
```xml
<componentInstanceProperties>
<name>columns</name>
<value>Facet-{uuid}</value>
</componentInstanceProperties>
```
---
## Incremental Development Pattern
**Philosophy:** Deploy small, working increments. Don't build entire complex page at once.
**Process:**
1. **CLI bootstrap** → Deploy base page
2. **Add one component** → Deploy
3. **Add another component** → Deploy
4. **Repeat** until complete
**Benefits:**
- Isolated errors (know exactly what broke)
- Faster debugging
- Build confidence with each success
- Get user feedback early
**Anti-pattern:** Building entire complex page → one giant error cascade.
---
## Adding Components to Existing FlexiPages
### Workflow
When user provides an existing FlexiPage file path:
1. **Read the file** using native file I/O
2. **Parse XML** to extract:
- Existing component identifiers
- Available regions (parse from file, don't assume names)
- Existing facets
3. **Use MCP actions** for discovery:
- DISCOVER_UI_COMPONENTS (find available components)
- GET_UI_COMPONENT_SCHEMAS (understand properties and get additional documentation)
- GET_DATA_SOURCE_VALUES (validate data source values)
4. **Generate component XML** (apply all rules from "Critical XML Rules" section)
5. **Insert** into appropriate region
6. **Write** modified XML back to file
7. **Deploy**: `sf project deploy start --source-dir force-app/...`
---
### Generating Unique Identifiers
**Algorithm**:
```
1. Extract all existing <identifier> values from XML
2. Generate base name: {componentType}_{context}
Examples: "relatedList_contacts", "richText_header", "tabs_main"
3. Find first available number:
- Try "{base}_1"
- If exists, try "{base}_2", "{base}_3", etc.
- Use first available
```
**Examples**:
- First contacts related list: `relatedList_contacts_1`
- Second contacts related list: `relatedList_contacts_2`
- Rich text in header: `richText_header_1`
- Field section: `fieldSection_details_1`
**Facet Naming - Two Patterns**:
1. **Named facets** (for major content areas):
- `detailTabContent` (detail tab content)
- `maintabs` (main tab container)
- `sidebartabs` (sidebar tab container)
- Use when facet represents meaningful content area
2. **UUID facets** (for internal structure):
- Format: `Facet-{8hex}-{4hex}-{4hex}-{4hex}-{12hex}`
- Example: `Facet-66d5a4b3-bf14-4665-ba75-1ceaa71b2cde`
- Use for field section columns, nested containers, anonymous slots
---
### Region Selection
**Parse regions from file** - don't hardcode names. Templates vary:
- `flexipage:recordHomeTemplateDesktop``header`, `main`, `sidebar`
- `runtime_service_fieldservice:...``header`, `main`, `footer`
- Others may have different region names
**Default placement**: End of target region (after last `<itemInstances>`)
**Insertion pattern**:
```xml
<flexiPageRegions>
<name>main</name> <!-- or whatever region name exists -->
<type>Region</type>
<itemInstances><!-- Existing component 1 --></itemInstances>
<itemInstances><!-- Existing component 2 --></itemInstances>
<itemInstances>
<!-- INSERT NEW COMPONENT HERE -->
</itemInstances>
</flexiPageRegions>
```
---
### Container Components with Facets
Components like tabs, accordions, field sections require facets.
**Pattern**:
```xml
<!-- 1. Component in region -->
<flexiPageRegions>
<itemInstances>
<componentInstance>
<componentName>flexipage:tabset2</componentName>
<identifier>tabs_main_1</identifier>
<componentInstanceProperties>
<name>tabs</name>
<value>tab1_content</value>
<value>tab2_content</value>
</componentInstanceProperties>
</componentInstance>
</itemInstances>
<name>main</name>
<type>Region</type>
</flexiPageRegions>
<!-- 2. Facets (siblings of region, NOT nested inside) -->
<flexiPageRegions>
<itemInstances><!-- Tab 1 content --></itemInstances>
<name>tab1_content</name>
<type>Facet</type>
</flexiPageRegions>
<flexiPageRegions>
<itemInstances><!-- Tab 2 content --></itemInstances>
<name>tab2_content</name>
<type>Facet</type>
</flexiPageRegions>
```
**Critical**: Facet regions are siblings of template regions at the same level, not nested inside them.
---
## Required Metadata Structure
```xml
<FlexiPage xmlns="http://soap.sforce.com/2006/04/metadata">
<flexiPageRegions>
<!-- Regions and components here -->
</flexiPageRegions>
<masterLabel>Page Label</masterLabel>
<template>
<name>flexipage:recordHomeTemplateDesktop</name>
</template>
<type>RecordPage</type>
<sobjectType>Object__c</sobjectType> <!-- RecordPage only -->
</FlexiPage>
```
**Page Types:**
- `RecordPage` - requires `<sobjectType>`
- `AppPage` - no sobjectType
- `HomePage` - no sobjectType
---
## Validation Checklist
Before deploying:
- [ ] Used CLI to bootstrap (don't start from scratch)
- [ ] All field references use `Record.{Field}` format
- [ ] Each fieldInstance has `fieldInstanceProperties` with `uiBehavior`
- [ ] Each fieldInstance in own `<itemInstances>` wrapper
- [ ] Template regions use `<type>Region</type>`
- [ ] Component facets use `<type>Facet</type>`
- [ ] Property values with HTML/XML are manually encoded
- [ ] No `<mode>` tags in regions
- [ ] No `__c` suffix in page names
- [ ] Each Facet referenced by exactly one component property
---
## Quick Reference: CLI Command
```bash
# RecordPage with fields
sf template generate flexipage \
--name Account_Custom_Page \
--template RecordPage \
--sobject Account \
--primary-field Name \
--secondary-fields Phone,Industry,AnnualRevenue \
--detail-fields Street,City,State,Name,Phone,Email
# AppPage
sf template generate flexipage \
--name Sales_Dashboard \
--template AppPage \
--label "Sales Dashboard"
# HomePage
sf template generate flexipage \
--name Custom_Home \
--template HomePage \
--description "Custom home for sales team"
```
**All templates support:**
- `--output-dir` (default: current directory)
- `--api-version` (default: latest)
- `--label` (default: page name)
- `--description`

View File

@ -0,0 +1,339 @@
---
name: salesforce-flow
description: Use this skill when users need to generate Salesforce Flows using the 3-step pipeline (fetchGroundedObjectMetadata → flowElementSelection → flowElementGeneration). Trigger when users mention creating flows, Screen Flows, Autolaunched Flows, Record-Triggered Flows, Scheduled Flows, Platform Event-Triggered Flows, flow metadata, flow automation, process automation, workflow automation, or generating flow XML. This skill guides through the mandatory 3-step MCP pipeline and ensures proper inflightMetadata formatting. Always use this skill for any flow generation or automation requests.
---
## When to Use This Skill
Use this skill when you need to:
- Create any type of Flow (Screen, Autolaunched, Record-Triggered, Scheduled)
- Generate Flow metadata XML
- Automate business processes without code
- Build user-guided workflows or background automation
- Troubleshoot deployment errors related to Flows
## Specification
# Flow Metadata Specification
## 📋 Overview
Salesforce Flows are powerful automation tools that enable complex business process automation without code. Flows can collect and process data through interactive screens, execute logic and calculations, manipulate records, call external services, and trigger based on various events. Flow types include Screen Flows (user-guided), Autolaunched Flows (background processing), Record-Triggered Flows (database events), Scheduled Flows (time-based), and Platform Event-Triggered Flows (event-driven).
## 🎯 Purpose
- Automate complex business processes with declarative logic and branching
- Guide users through multi-step data collection and decision workflows via Screen Flows
- Perform CRUD operations on Salesforce records automatically
- Execute background processing and integrations via Autolaunched Flows
- React to record changes in real-time with Record-Triggered Flows
- Schedule recurring tasks and batch operations with Scheduled Flows
- Create reusable, maintainable automation that admins can modify without code
## ⚙️ Flow Generation Pipeline
**🚨 MANDATORY: You MUST follow this exact 3-step pipeline. No exceptions. No shortcuts. No skipping steps. Do NOT manually create flow metadata XML or attempt to generate flow metadata outside of this pipeline. Do NOT attempt to use any other tool, API, or method to generate flow metadata. This pipeline is the ONLY supported way to generate flows. Any deviation will produce invalid or broken metadata.**
Flow generation is a **strict 3-step pipeline**. ALL steps must be called in order. Every step is required. **There is no alternative approach — this is the only way to generate flow metadata:**
### Step 1 (REQUIRED): Fetch Grounded Object Metadata (`fetchGroundedObjectMetadata`)
Fetches org schema metadata relevant to the flow generation request. This step is **mandatory** and must always be called first.
**Inputs (all required):**
- **userPrompt** (STRING, REQUIRED): The user's natural language request
- **inflightMetadata** (ARRAY, REQUIRED): Custom objects/fields from local sfdx project. Use empty array `[]` if none needed.
**Outputs:**
- **groundingMetadata** (STRING): Grounded object metadata for org schema relevant to the request, returned as a JSON string. **You must pass this directly to Step 2 — it is already a string and does not need to be serialized again.**
### Step 2 (REQUIRED): Flow Element Selection (`flowElementSelection`)
Selects flow elements (assignments, decisions, record ops, etc.) and their connections based on the user prompt and grounded metadata. This step is **mandatory** and must be called after Step 1.
**Inputs (all required):**
- **userPrompt** (STRING, REQUIRED): The user's natural language request (**must be the same value as Step 1**)
- **groundingMetadata** (STRING, REQUIRED): Org schema metadata (**must be the exact string returned from Step 1 output** — pass it directly, do NOT serialize it again)
- **operationId** (STRING, REQUIRED): Operation ID (use empty string `""` for first call)
**Outputs:**
- **operationId** (STRING): Operation ID. **You must pass this to Step 3.**
- **userOutput** (STRING): Reasoning for next steps. You can show this to the user.
### Step 3 (REQUIRED): Flow Element Generation (`flowElementGeneration`)
Generates flow metadata element by element. This step is **mandatory** and must be called after Step 2. **Must be called repeatedly in a loop until `isComplete` is `true`.**
**Inputs (all required):**
- **operationId** (STRING, REQUIRED): Operation ID **from Step 2 output**
- **requestSource** (STRING, REQUIRED): The source of the request. Use **`"A4V"`** to get flow metadata in XML format.
**Outputs:**
- **isComplete** (BOOLEAN): Indicates if the flow generation is complete. **You must check this value.**
- **result** (STRING): Result of the flow element generation. Contains the final flow metadata **only when `isComplete` is `true`**.
**🚨 MANDATORY: Loop until complete.**
- Call `flowElementGeneration` with the `operationId` from Step 2 and `requestSource` (use `"A4V"` for XML output, empty string or other value for JSON).
- Check the `isComplete` output after each call.
- If `isComplete` is `false`, you **MUST** call `flowElementGeneration` again with the **same `operationId`** from Step 2.
- **Do NOT stop** until `isComplete` is `true`.
- When `isComplete` is `true`, extract the flow metadata from the `result` field.
## 📦 inflightMetadata Format
**DATA TYPE: ARRAY (not string)**
**⚠️ STRICT NAMING CONVENTION - MUST FOLLOW EXACTLY:**
| Property | Correct Name | ❌ Do NOT Use |
|----------|-------------|---------------|
| Object API name | `apiName` | `objectApiName`, `name`, `objectName` |
| Field API name | `apiName` | `fieldApiName`, `name`, `fieldName` |
| Field type | `type` | `fieldType`, `dataType` |
| Lookup target | `referenceTo` | `relatedTo`, `lookupTo`, `reference` |
When custom objects are needed (sample format showing multiple field data types):
```json
[
{
"type": "CustomObject",
"apiName": "CustomerRequest__c",
"label": "Customer Request",
"fields": [
{
"apiName": "Status__c",
"type": "Picklist",
"label": "Status",
"values": ["New", "In Progress", "Completed"]
},
{
"apiName": "Priority__c",
"type": "Number",
"label": "Priority"
},
{
"apiName": "AssignedTo__c",
"type": "Lookup",
"label": "Assigned To",
"referenceTo": "User"
},
{
"apiName": "Description__c",
"type": "Textarea",
"label": "Description"
},
{
"apiName": "Email__c",
"type": "Email",
"label": "Contact Email"
},
{
"apiName": "DueDate__c",
"type": "Date",
"label": "Due Date"
},
{
"apiName": "IsUrgent__c",
"type": "Boolean",
"label": "Is Urgent"
},
{
"apiName": "Amount__c",
"type": "Currency",
"label": "Amount"
}
],
"relationships": []
}
]
```
**Supported field types**: Text, Textarea, Number, Picklist, Lookup, Email, Phone, URL, Date, Datetime, Boolean, Checkbox, Currency, Percent
When no custom objects needed:
```json
[]
```
### ⚠️ MANDATORY Decision Logic for inflightMetadata (DATA TYPE: ARRAY)
1. **REQUIRED - First**: Scan the local sfdx project for custom objects and fields that are relevant to the user's flow request.
2. **If relevant custom objects ARE found**: You MUST extract and pass them as an array of structured objects (see format above)
3. **If NO relevant custom objects found**: You MUST pass an empty array `[]` (NOT the string `"[]"`)
4. **NEVER**: Pass text descriptions, instructions, or string representations in inflightMetadata
5. **MANDATORY**: The data type MUST be ARRAY, not STRING
**Instructions for Cline when custom objects ARE relevant:**
- Extract the object metadata and map to JSON properties:
- `apiName`: The object's API name (with `__c` suffix for custom objects)
- `label`: The object's display label
- `type`: Set to `"CustomObject"`
- `fields`: Array of field objects, each containing:
- `apiName`: The field's API name (with `__c` suffix for custom fields)
- `type`: The field type (Text, Number, Picklist, Lookup, etc.)
- `label`: The field's display label
- `values`: (Picklist only) Array of picklist values
- `referenceTo`: (Lookup only) The target object API name
- Include only objects and fields that are relevant to the flow being generated
## 🎯 Mandatory Enhancement Rules
- **userPrompt**: REQUIRED. Always use the exact user prompt without modification.
- **inflightMetadata**: REQUIRED. Always use ARRAY data type.
- MUST use `[]` (empty array) when no custom objects needed
- MUST use structured array of objects when custom objects are relevant
- NEVER use string `"[]"` - this is incorrect
- NEVER use text descriptions - only structured object metadata
### 🚨 MANDATORY: Multiple Flows = Multiple Separate Pipelines
**❌ NEVER club multiple flow prompts into a single `userPrompt` field.**
When the user requests multiple flows (e.g., for an app with several flows), each flow MUST be generated with a **separate 3-step pipeline** and a **separate payload**. This is mandatory and non-negotiable.
**❌ WRONG - Multiple flows clubbed into one userPrompt:**
```json
{
"userPrompt": "Generate the following flows: 1) Screen Flow - Tenant Onboarding... 2) Autolaunched Flow - Generate Checklist... 3) Record-Triggered Flow - Sync Unit...",
...
}
```
**✅ CORRECT - Separate call for EACH flow:**
**Flow 1 - Step 1 (fetchGroundedObjectMetadata):**
```json
{
"userPrompt": "Create a Screen Flow named Tenant_Onboarding that captures tenant details, selects a Unit__c with Status__c = 'Vacant', creates Lease__c...",
"inflightMetadata": [...]
}
```
Then call Step 2 (`flowElementSelection`) with the `groundingMetadata` from Step 1, then Step 3 (`flowElementGeneration`) with the `operationId` from Step 2.
**Flow 2 - Step 1 (fetchGroundedObjectMetadata):**
```json
{
"userPrompt": "Create an Autolaunched Flow named Generate_Onboarding_Checklist that given a Lease__c Id input, queries OnboardingTask__c...",
"inflightMetadata": [...]
}
```
Then call Step 2 and Step 3 for this flow.
**Flow 3 - Step 1 (fetchGroundedObjectMetadata):**
```json
{
"userPrompt": "Create a Record-Triggered Flow named Sync_Unit_On_Lease_Changes that on insert and update of Lease__c...",
"inflightMetadata": [...]
}
```
Then call Step 2 and Step 3 for this flow.
**Mandatory Rules:**
- If there are N flows to generate, there MUST be N separate 3-step pipelines. No exceptions.
- For each flow, you MUST scan the local sfdx project to populate `inflightMetadata` with custom objects/fields **specific to that flow prompt**.
- Each flow pipeline MUST have its own `inflightMetadata` containing only the objects/fields relevant to that particular flow.
## 🔧 Example Tool Calls
**Example 1: Standard objects only (no custom objects)**
**Step 1 - fetchGroundedObjectMetadata:**
```json
{
"userPrompt": "Create a scheduled-triggered Flow named Daily_Good_Morning that runs daily at 6:00 AM and sends an email to the running user saying good morning.",
"inflightMetadata": []
}
```
**Step 2 - flowElementSelection:**
```json
{
"userPrompt": "Create a scheduled-triggered Flow named Daily_Good_Morning that runs daily at 6:00 AM and sends an email to the running user saying good morning.",
"groundingMetadata": "<groundingMetadata string from Step 1 pass directly, do not serialize again>",
"operationId": ""
}
```
**Step 3 - flowElementGeneration (call in a loop):**
```json
{
"operationId": "<operationId from Step 2>",
"requestSource": "A4V"
}
```
Call repeatedly with the same `operationId` until `isComplete` is `true`. When `isComplete` is `true`, extract the flow metadata from the `result` field. Use `"requestSource": "A4V"` to get flow metadata in XML format.
**Example 2: With custom objects from local sfdx project**
**Step 1 - fetchGroundedObjectMetadata:**
```json
{
"userPrompt": "Create a flow that updates the status of a Customer Request when it's assigned",
"inflightMetadata": [
{
"type": "CustomObject",
"apiName": "CustomerRequest__c",
"label": "Customer Request",
"fields": [
{
"apiName": "Status__c",
"type": "Picklist",
"label": "Status",
"values": ["New", "In Progress", "Completed"]
},
{
"apiName": "AssignedTo__c",
"type": "Lookup",
"label": "Assigned To",
"referenceTo": "User"
}
],
"relationships": []
}
]
}
```
**Step 2 - flowElementSelection:**
```json
{
"userPrompt": "Create a flow that updates the status of a Customer Request when it's assigned",
"groundingMetadata": "<groundingMetadata string from Step 1 pass directly, do not serialize again>",
"operationId": ""
}
```
**Step 3 - flowElementGeneration (call in a loop):**
```json
{
"operationId": "<operationId from Step 2>",
"requestSource": "A4V"
}
```
Call repeatedly with the same `operationId` until `isComplete` is `true`. When `isComplete` is `true`, extract the flow metadata from the `result` field. Use `"requestSource": "A4V"` to get flow metadata in XML format
## ✅ Mandatory Best Practices
- **ALWAYS** follow the 3-step pipeline: fetchGroundedObjectMetadata → flowElementSelection → flowElementGeneration. This is the ONLY way to generate flow metadata. There are no alternatives.
- Do NOT manually create flow metadata XML, JSON, or any other format outside of this pipeline.
- Do NOT attempt to "optimize" by skipping steps or combining steps. Each step is atomic and required.
- **NEVER** skip any step in the pipeline. All 3 steps are required.
- **NEVER** try to generate flow metadata without calling all 3 steps.
- **NEVER** deviate from this pipeline under any circumstance — even if you think you know the flow structure.
- For single flow requests: you MUST use the user prompt as `userPrompt`.
- For multiple flow requests: you MUST run a separate 3-step pipeline for each flow.
- You MUST put flow requirements in `userPrompt`, NOT in `inflightMetadata`.
- `inflightMetadata` is ONLY for custom object/field metadata from local project (see above). No exceptions.
- Step 3 MUST be called in a loop with the same `operationId` from Step 2 until `isComplete` is `true`. Do NOT stop early.
- You MUST only extract the flow metadata from the `result` field when `isComplete` is `true`.
## 🚨 CRITICAL Verification Checklist (MUST VERIFY BEFORE AND AFTER EVERY FLOW GENERATION)
**Failure to follow this checklist exactly will result in broken or missing flow metadata.**
- [ ] **Pipeline**: ALL 3 steps are called in strict order (fetchGroundedObjectMetadata → flowElementSelection → flowElementGeneration). No step is skipped.
- [ ] **No manual metadata**: Flow metadata is NOT manually created, modified, or generated outside of this pipeline by any means
- [ ] **No deviation**: No alternative tools, APIs, or methods were used instead of or alongside this pipeline
- [ ] **userPrompt** contains a single flow prompt (split if user requested multiple flows)
- [ ] **userPrompt** is passed consistently to both Step 1 and Step 2 (same value)
- [ ] **inflightMetadata** is ARRAY data type (NOT string)
- [ ] **inflightMetadata** is `[]` when no custom objects needed
- [ ] **inflightMetadata** contains structured objects extracted by scanning the local sfdx project for relevant custom objects/fields
- [ ] **inflightMetadata** does NOT contain `"[]"` (string) - must be `[]` (array)
- [ ] **inflightMetadata** does NOT contain text descriptions or instructions
- [ ] **groundingMetadata** from Step 1 output is passed directly to Step 2 input (it is already a string — do NOT serialize it again)
- [ ] **operationId** from Step 2 output is passed to Step 3 input
- [ ] **requestSource** should be set to `"A4V"` always
- [ ] **Step 3** is called in a loop with the same `operationId` from Step 2 until `isComplete` is `true`
- [ ] **result** field is used to extract the XML flow metadata only when `isComplete` is `true`

View File

@ -0,0 +1,42 @@
---
name: salesforce-fragment
description: Use this skill when users need to create or edit Salesforce Fragments (reusable UI pieces). Trigger when users mention fragments, UEM blocks, reusable UI templates, structured rendering across Slack/Mobile/LEX, or block-based layouts. Also use when users want to create unified experience components. Always use this skill for any fragment work.
---
## When to Use This Skill
Use this skill when you need to:
- Create reusable UI fragments for Salesforce experiences
- Generate Fragment metadata following UEM structure
- Build fragments for Slack, Mobile, LEX, and other Salesforce experiences
- Troubleshoot deployment errors related to Fragments
## Specification
# Fragment Generation Guide
## 📋 Overview
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.
## 🎯 Purpose
Fragments render data in a structured and unified way across various Salesforce experiences like Slack, Mobile, LEX etc
## ⚙️ Composition
A fragment is a UEM (Unified Experience Model) tree of blocks and regions. The fragment you return must follow the Typescript interfaces below:
- **Block definition**: Follow `{namespace}}/{{blockName}` convention and use the same value as the block's definition when it appears in a fragment.
```ts
interface BlockType {
type: 'block'
definition: string // {namespace}/{blockName}, e.g. "bcx/heading"
attributes?: Record<string, any>
children?: (BlockType | RegionType)[]
}
interface RegionType {
type: 'region'
name: string
children: BlockType[]
}
```

View File

@ -0,0 +1,216 @@
---
name: salesforce-list-view
description: Use this skill when users need to create, generate, or validate Salesforce List View metadata. Trigger when users mention list views, filtered record lists, creating views, setting up record columns, filtering records by criteria, or ask about list view visibility. Also use when users say things like "I need a view that shows...", "filter records by...", "create a list view for...", or when they're working with ListView XML files and need validation or troubleshooting.
---
## When to Use This Skill
Use this skill when you need to:
- Create list views for objects
- Generate filtered, column-based record listings
- Configure list view visibility and sharing
- Troubleshoot deployment errors related to List Views
## Specification
# Salesforce List View Metadata Knowledge
## 📋 Overview
Salesforce List Views define filtered, column-based record listings on an object's tab.
## 🎯 Purpose
- Provide curated, role- or task-specific subsets of records
- Standardize commonly used filters and visible fields across teams
## 🔧 Configuration
Unless specifically requested to be generated inline, List Views are stored at:
- force-app/main/default/objects/<ObjectName>/listViews/<fullName>.listView-meta.xml
Only if the user requests are they to be included in the object's metadata file:
- fore-app/main/default/objects/<ObjectName>/<ObjectName>.object-meta.xml
Key elements:
- label: Human-friendly name shown in UI (must be under 40 characters in length)
- fullName (fullName): API identifier used in metadata and file name
- filterScope: Everything | Mine | Queue
- filters: field/operation/value triples
- booleanFilterLogic: Combine multiple filters logically with AND/OR (e.g., "1 AND (2 OR 3)")
- columns: Ordered list of field API names to display
References:
- listViews appear on the entity's tab
- listViews can be referenced by flexipages using the "filterListCard" component
### Critical Decision: Visibility Strategy
Choose how broadly the view should appear in the org.
**Choose "Visible to all users" when:**
- The view is useful across profiles/roles
- It's a governed, shared artifact to be managed via source control
- Data contained is appropriate for broad visibility
**Choose "Owner-only/Restricted" when:**
- It is experimental or niche during iteration
- It is specifically requested to be limited to Users, Groups or Roles
- There are governance/security reviews pending
**When in doubt:** Default to "Visible to all users".
### Critical Decision: Columns Density
**Choose minimal, high-signal columns when:**
- Users need at-a-glance scanning
- Mobile/responsive performance matters
**Choose richer column sets when:**
- Desktop heavy workflows need more context without opening records
- It serves as a work queue and extra fields reduce clicks
**When in doubt:** Start with 46 columns that directly support the primary task.
## Critical Rules (Read First)
### Rule 1: Custom Field API Names
For custom fields, use exact API names (e.g., Status__c), not labels.
Wrong:
- Status (label)
Right:
- Status__c (API name)
### Rule 2: Standard Field Names
For standard fields on Custom Objects, use already defined names:
Wrong:
- Name (API Name)
Right:
- NAME
The standard fields on Custom Objects are:
- NAME
- RECORDTYPE
- OWNER.ALIAS
- OWNER.FIRST_NAME
- OWNER.LAST_NAME
- CREATEDBY_USER.ALIAS
- CREATEDBY_USER
- CREATED_DATE
- UPDATEDBY_USER.ALIAS
- UPDATEDBY_USER
- LAST_UPDATE
- LAST_ACTIVITY
### Rule 3: Operations Must Match Field Types
Picklists require equals/notEqual; date fields require date operators; boolean values are 0 and 1; do not mix text-only operators with non-text fields.
Wrong:
- operation="contains" on a picklist
- value=True on a boolean
Right:
- operation="equals" with a valid picklist value
- value=1 on a boolean
### Rule 4: Name and Path Alignment
File name, fullName (also sometimes referred to as DeveloperName), and uniqueness must align.
Wrong:
- File: My_List.listView-meta.xml
- fullName: MyList
Right:
- File: MyList.listView-meta.xml
- fullName: MyList
### Rule 5: Folder Placement
Place files under the object's listViews directory or deployments will fail to resolve components. Only if a user
requests it, may the listView may be included inline in force-app/main/default/objects/<ObjectName>/<ObjectName>.object-meta.xml
Path:
- force-app/main/default/objects/<ObjectName>/listViews/<fullName>.listView-meta.xml
## Generation Workflow
### Step 1: Get Metadata Information
- Identify the target object API name (e.g., Object__c).
- Gather business requirements: purpose, audience, fields, filters.
- Validate values and operator compatibility with field types.
### Step 2: Examine Existing Examples
- Repo: force-app/main/default/objects/<Object>/listViews/ (unless otherwise required by end user)
- Org: retrieve existing list views for proven patterns (filters, logic, columns).
- Note what passed review/deployment and delivered expected UX.
### Step 3: Create Specification
Document before implementation:
- Name: fullName and Label
- Audience: Visibility scope ("all users" vs. shared)
- Filter scope: Everything | Mine | Queue
- Filter items: filter, operator, value; plus booleanFilterLogic if multiple
- Columns: Ordered list of field API names
- Acceptance criteria: Which records appear, paging behavior, key scenarios
### Step 4: Author Metadata File
Use a Lightning-compatible template and ensure valid XML:
```xml
<?xml version="1.0" encoding="UTF-8"?>
<ListView xmlns="http://soap.sforce.com/2006/04/metadata">
<fullName>OpenMine</fullName>
<label>Open - My Records</label>
<filterScope>Mine</filterScope>
<columns>NAME</columns>
<columns>Status__c</columns>
<columns>OWNER.ALIAS</columns>
<columns>LAST_UPDATE</columns>
<filters>
<field>Status__c</field>
<operation>equals</operation>
<value>Open</value>
</filters>
<sharedTo>
<role>CEO</role>
<roleAndSubordinatesInternal>COO</roleAndSubordinatesInternal>
</sharedTo>
</ListView>
```
Notes:
- For "My" views, use filterScope="Mine".
- Keep columns tight and purposeful.
- If intended for all users, omit the "sharedTo" section.
### Step 5: Validate Locally
- Well-formed XML; correct namespace
- Field names exist on the object; operators and values match field types
- Path and fullName alignment
- If multiple filters: set booleanFilterLogic correctly (e.g., "1 AND (2 OR 3)")
### Step 6: Deploy and Verify in Org
- Deploy the component path or the whole object.
- In the UI, open the object tab and:
- Confirm records match filters
- Confirm columns render correctly
- Confirm visibility matches audience
## Common Deployment Errors
| Error | Cause | Fix |
|-------|---------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------|
| "Invalid field Status" | Used label instead of API name, or used API Name instead of defined name for Standard Field | Use Status__c (or correct API name), or NAME instead of Name (for Standard Fields) |
| "Invalid filter operator" | Operator not valid for field type | Choose operation compatible with field type (e.g., equals for picklist) |
| "Component not found at path" | Wrong folder or file name | Place in objects/<Object>/listViews and align file name with fullName |
| "Malformed booleanFilterLogic" | Syntax or index mismatch | Use "1 AND 2" style, ensure filters index order matches |
## Verification Checklist
- [ ] All required fields populated (fullName, label, filterScope, columns)
- [ ] Property values are XML-encoded where needed
- [ ] Custom Field references use API names (e.g., Status__c)
- [ ] Standard Field references use defined names (e.g., NAME)
- [ ] Operations match field types; picklist values are valid
- [ ] booleanFilterLogic (if used) matches filters ordering and count
- [ ] File path and fullName/developerName are aligned
- [ ] No deprecated or Classic-only properties included
- [ ] Deployed successfully and visible as intended
- [ ] Records, columns, and filtering behave as specified

View File

@ -0,0 +1,69 @@
---
name: salesforce-validation-rule
description: Use this skill when users need to create, modify, or validate Salesforce Validation Rules. Trigger when users mention validation rules, field validation, data quality rules, formula validation, error messages, or validation logic. Also use when users encounter validation errors, need to update formulas, or want to enforce business rules at the data layer. Always use this skill for any validation rule work.
---
## When to Use This Skill
Use this skill when you need to:
- Create validation rules to enforce data quality
- Prevent invalid records from being saved
- Generate validation rule metadata with formulas
- Add business logic validation to objects
- Troubleshoot deployment errors related to validation rules
## Specification
# ValidationRule Metadata Specification
### 📋 Overview
Validation Rules are declarative metadata components used to enforce data quality and business logic in Salesforce. They evaluate a formula expression when a record is saved and prevent the save operation if the expression returns TRUE.
### 🎯 Purpose
-Enforce business rules at the data layer
-Prevent invalid or incomplete records from being saved
-Display meaningful error messages to guide users
### ⚙️ Required Properties
#### Core Validation Rule Properties
- **fullName**
- The unique API name of the validation rule
- Must start with a letter
- Can contain letters, numbers, and underscores
- Cannot end with an underscore
- Cannot contain consecutive underscores
- Cannot exceed 40 character.
- **active**
-Indicates whether the validation rule is enabled
true → Rule is enforced
false → Rule is inactive
- **errorConditionFormula**
- The logical formula that evaluates record data
- Must return TRUE or FALSE
- If TRUE, the validation rule triggers an error
- **errorMessage**
- The message displayed to the user when validation fails
- Maximum length: 255 characters
### Specific Function Guidelines
- TEXT - TEXT() function MUST NOT be used with Text fields, to fix this you can just remove the TEXT() function.
- CASE - In salesforce CASE() function, last parameter is the default value. Admins often miss to provide this and number of parameters to CASE() function are always even.
- VALUE - VALUE() function should only be used with Text fields. If a number is being used as a parameter to the VALUE() function, remove the VALUE() function.
- DAY - DAY() function should only be used with Date fields. If a Datetime field is being used as a parameter to the DAY() function, convert it into a Date first.
- MONTH - MONTH() function should only be used with Date fields. If a Datetime field is being used as a parameter to the MONTH() function, convert it into a Date first.
- DATEVALUE - DATEVALUE() function should only be used with DateTime fields. If a Date is being used as a parameter to the DATEVALUE() function, remove the DATEVALUE() function.
- ISPICKVAL - If checking equality of a picklist type field, the function ISPICKVAL() MUST be used.
- ISCHANGE - Use ISCHANGE() function to check the value of a record has changed.
### Critical Rules
1. Formula XML Handling(MOST COMMON ERROR)
- ANY errorConditionFormula containing XML tags MUST be inside a CDATA section in the metadata XML.
2. Interpretation of "Update" Instructions. When receiving instructions to modify a formula, distinguish between a replacement and an addition:
- "Update the formula to [Action]": Completely replace the existing formula logic with the new requirement.
- "Update the formula to also [Action]": Keep the existing logic and append the new requirement (usually by wrapping the logic in an AND() or OR() function).

View File

@ -0,0 +1,84 @@
---
name: salesforce-web-app-creating-records
description: Use this skill when users need to create Salesforce records from React web applications. Trigger when users mention createRecord, creating leads/contacts/custom objects from web apps, handling record IDs, form submissions to Salesforce, or Application__c custom objects. Always use this skill for any record creation from React apps.
---
## When to Use This Skill
Use this skill when you need to:
- Create Salesforce records from web applications
- Implement createRecord functionality for custom or standard objects
- Handle record ID extraction from create responses
- Troubleshoot deployment errors related to record creation
# Creating Salesforce records (webApplication)
## Overview
Implement list and create functionality for any custom object using GraphQL queries and createRecord API with automatic list refresh.
## API
- Use **createRecord** from `@salesforce/webapp-experimental/api`:
- `createRecord(objectApiName: string, fields: Record<string, unknown>)` → returns a result object that may contain the new record id in different shapes depending on the API version.
## Getting the new record id
The create response is not always a simple `{ id: string }`. Handle both common shapes so you don't get "Create succeeded but no record id returned":
- Prefer **result.id** when it's a string.
- Else read **result.fields.Id.value** (or equivalent) if the API returns the id inside a fields wrapper.
Example helper:
```ts
function getRecordIdFromResponse(result: Record<string, unknown>): string {
const id =
typeof result.id === "string"
? result.id
: (result.fields as Record<string, { value?: string }> | undefined)?.Id?.value;
if (!id) throw new Error("Create succeeded but no record id returned");
return id;
}
```
Use this after `createRecord()` and return `{ id }` to the caller so the UI can show success or navigate.
## Field set and org schema
- **Only send fields that exist in the org.** If you send a field that doesn't exist (e.g. custom field not deployed), the API can return POST body parse errors (e.g. "Field X does not exist").
- For **custom objects**, deploy the object and its fields (e.g. via SFDX/CLI or metadata API) before relying on them in the app.
- **Fallback:** If you need to capture data that might not have a custom field yet (e.g. contact details), store it in a long text area or similar (e.g. `Employment_Info__c`) as a blob (e.g. JSON or line-based text) so no data is lost and the create still succeeds.
## Custom objects (e.g. Application__c)
- Define the object and fields in the project's Salesforce metadata (e.g. `objects/Application__c/`, `fields/*.field-meta.xml`).
- In the app, build a `fields` object with only the API names and values you want to set; omit required fields only if they have defaults.
- Use a typed input interface and map it to the `fields` passed to `createRecord`; optionally combine contact/extra info into one blob field if some fields might not be deployed.
## Standard objects (e.g. Lead)
- Use standard field API names: **FirstName**, **LastName**, **Email**, **Company**, **Phone**, **Description**, **LeadSource**, etc.
- **LeadSource** helps distinguish origin (e.g. "Website", "Website Newsletter").
- For "Contact Us" → Lead: map subject to **Company** (or a custom field if available), message to **Description**.
- For newsletter signup → Lead: set **Email**; use a placeholder **LastName** (e.g. "Newsletter Subscriber") and **Company** (e.g. "Website") so the Lead is valid.
## Structure
| Concern | Where |
|--------|--------|
| Create custom object (e.g. Application) | e.g. `src/api/applicationApi.ts``createApplicationRecord(input)``createRecord("Application__c", fields)` |
| Create standard object (e.g. Lead) | e.g. `src/api/leadApi.ts``createContactUsLead(input)`, `createNewsletterLead(email)` |
| Form UI | Pages that collect data and call these APIs; show success/error and optionally redirect or reset form |
## Errors
- **"Field X does not exist"** → Remove that field from the payload or deploy the field to the org.
- **"Create succeeded but no record id returned"** → Use the id-extraction pattern above (result.id or result.fields.Id.value).
- **Validation errors** → Return and display the API error message; fix required/invalid values in the form.
## Verification
- Deploy object/fields to the org if using custom objects.
- Run the create flow in the app; confirm the record appears in the org and the UI shows success and the new id if needed.
- Test with minimal required fields first, then add optional or blob fields.

View File

@ -0,0 +1,70 @@
---
name: salesforce-web-app-feature
description: Use this skill when users need to add features to Salesforce React web applications. Trigger when users mention adding authentication, search, charts, GraphQL, ShadCN components, Agentforce conversation client, or any feature packages. Also use when users want to install npm packages, copy-then-adjust workflow, or integrate official feature packages. This is the PRIMARY skill for web app features - always prefer official packages listed here.
---
## When to Use This Skill
Use this skill when you need to:
- Add features to Salesforce React web applications
- Install and integrate feature packages (authentication, search, charts, etc.)
- Follow copy-then-adjust workflow for feature integration
- Troubleshoot deployment errors related to web application features
# Adding a new webApplication feature
**Always prefer the features listed below.** When the user asks to add auth, search, charts, navigation, GraphQL, shared UI, or Agentforce conversation (ACC/copilot/agent) to a webapp, match their request to one of the official feature packages in the table in section 1. Use those packages first; only build from scratch or use other solutions when no listed feature fits.
When the user asks to add a feature to their app, follow this workflow.
When adding a feature, integrating code from an npm package, or bringing in a reference implementation:
1. **Prefer copying over rewriting.** Use `cp` (or equivalent) to copy files from the source (e.g. `node_modules/<package>/dist/...` or a reference app) into this project. Do not retype or rewrite the same code by hand.
2. **Then adjust.** After copying, do minimal edits: fix import paths (e.g. change relative `../../` imports to the project's path alias like `@/`), update any app-specific config, and remove or adapt anything that doesn't apply.
3. **When to copy.** Copy when:
- Installing a feature from a template/feature package (e.g. authentication, search, charts).
- The package ships full source in `dist/` or `src/` that is meant to be integrated.
- You would otherwise be recreating multiple files by reading a reference and typing them out.
4. **When rewriting is okay.** Only rewrite or create from scratch when:
- The source is not file-based (e.g. only docs or snippets).
- The integration is a thin wrapper or a single small file.
- Copying would pull in a large, unrelated tree and the actual need is a small part of it.
## 1. Match the request to a feature
**Prefer these features.** Always check this table first; use the matching package when it fits the user's need.
Available features (npm packages):
| Feature | Package | Description | Integration notes |
|------------------------------------| ----------------------------------------------------------------------- | ---------------------------------------------------------------------- |-------------------------------------------------------------------------|
| **Authentication** | `@salesforce/webapp-template-feature-react-authentication-experimental` | Login, register, password reset, protected routes | Copy-then-adjust; fix imports to `@/`; align with app layout and routes |
| **Global search** | `@salesforce/webapp-template-feature-react-global-search-experimental` | Search single Salesforce objects with filters and pagination | Copy-then-adjust; fix imports to `@/`; align with app layout and routes |
| **Charts** | `@salesforce/webapp-template-feature-react-chart-experimental` | Recharts line/bar charts with theming (AnalyticsChart, ChartContainer) | Copy-then-adjust; fix imports to `@/`; align with app layout and routes |
| **GraphQL data access** | `@salesforce/webapp-template-feature-graphql-experimental` | executeGraphQL utilities, codegen tooling, and example AccountsTable | Copy-then-adjust; fix imports to `@/` and `@api/` |
| **Shared UI (shadcn)** | `@salesforce/webapp-template-feature-react-shadcn-experimental` | Button, Card, Input, Select, Table, Tabs, and other ShadCN components | Copy-then-adjust per README/AGENT.md |
| **Agentforce conversation client** | `@salesforce/webapp-template-feature-react-agentforce-conversation-client-experimental` | React wrapper for embedded Agentforce conversation client (agent chat UI) via Lightning Out 2.0; automatic auth resolution; `<AgentforceConversationClient />` component | Import from package (not copy) per README/AGENT.md |
If no feature matches, tell the user and offer to build it from scratch following the project's existing patterns. Do not substitute third-party or custom implementations when one of the features above matches—always prefer the listed packages.
## 2. Install the npm package
```bash
npm install <package-name>
```
## 3. Read the README.md / AGENT.md
The `node_modules` folder of the installed package contains a README.md and/or AGENT.md. Load it and follow its instructions.
## 4. Always validate
After integrating, **always validate** with:
```bash
npm i && npm run build && npm run dev
```

View File

@ -0,0 +1,36 @@
---
name: salesforce-web-app-list-and-create-records
description: Use this skill when users need to list and create records for Salesforce custom objects from React web apps. Trigger when users mention list and create patterns, GraphQL queries, refetch after create, form picklists matching object schema, or dashboard widgets showing record lists. Always use this skill for list+create patterns.
---
## When to Use This Skill
Use this skill when you need to:
- Implement list and create functionality for custom objects
- Build GraphQL queries for listing records
- Create records and update lists without page reload
- Troubleshoot deployment errors related to list and create operations
# List and create records (webApplication)
## Pattern
- **List:** Query the object via **GraphQL** (`executeGraphQL`, `uiapi.query.ObjectApiName__c`). Use **webApplicationFeature** (GraphQL) for the connection shape (first/after, edges.node, field `{ value, displayValue }`). Map nodes to a simple summary type; sort client-side by date or other field if needed.
- **Create:** Use **createRecord** from `@salesforce/webapp-experimental/api`. See **webApplicationCreatingRecords** for required/optional fields and id handling.
- **Hook:** One hook that fetches the list on mount and exposes `refetch`. After a successful create, call `refetch()` so the list updates without a full page reload.
- **Form:** Collect only fields that exist on the object. For picklist fields, use option values that **match the object's value set** (e.g. from the object's field metadata or a known value set). Default required picklists (e.g. Status to "New", Priority to "Standard") when the object defines defaults.
- **UI:** Table or cards for the list; form above or on a separate route. Show loading and error states for both list and submit. Optional: dashboard widget showing a slice of the list (e.g. first N items) with a "See all" link.
## Structure (generic)
| Concern | Where |
|--------|--------|
| API: list + create | e.g. `src/api/<objectName>Api.ts` — query function (GraphQL) and create function (createRecord) |
| Hook: list + refetch | e.g. `src/hooks/use<ObjectName>List.ts` — returns `{ items, loading, error, refetch }` |
| Page | Form (controlled inputs, submit → create → refetch) and table/list of items |
## Cross-references
- **webApplicationFeature** — Feature packages including GraphQL (connection shape, node shape, field value extraction).
- **webApplicationCreatingRecords** — createRecord, id extraction, only send existing fields, picklist/required handling.

View File

@ -0,0 +1,34 @@
---
name: salesforce-web-application
description: Directory of web application (React) sub-knowledges for Salesforce React BYO, feature packages, and copy-then-adjust workflow. Use when working with Salesforce web applications.
---
## When to Use This Skill
Use this skill when you need to:
- Work with Salesforce React web applications
- Understand available web application features and workflows
- Navigate web application knowledge resources
- Troubleshoot deployment errors related to web applications
## Specification
## Overview
This skill provides guidance for working with Salesforce React web applications (Salesforce BYO React template). It covers adding features, creating Salesforce records, and listing/creating custom object records.
## Web Applications — Directory
This is the **directory** of sub-knowledges for web applications (Salesforce React BYO, feature packages, copy-then-adjust workflow). **Call `get_expert_knowledge` again with one of the topic names below** to load the relevant knowledge.
## Sub-knowledges (use as `topic` in get_expert_knowledge)
| Topic name | Use when |
|-----------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| **webApplicationFeature** | Adding a feature to a webapp: authentication, search, charts, GraphQL, ShadCN, Agentforce conversation client. Feature table, npm install, copy-then-adjust workflow |
| **webApplicationCreatingRecords** | Creating Salesforce records: createRecord, custom/standard objects, id handling, Application__c, Lead |
| **webApplicationListAndCreateRecords** | List + create any custom object: GraphQL list, createRecord, hook with refetch, form picklists match object |
**Flow:** After reading this directory, call `get_expert_knowledge({ topic: "<subTopicName>" })` with the single sub-topic that best matches the user's request (e.g. `webApplicationFeature`, `webApplicationCreatingRecords`).
**Adding features:** Always prefer the feature packages listed in **webApplicationFeature** (authentication, search, charts, nav, GraphQL, ShadCN, Agentforce conversation) over building from scratch or other solutions when one of them matches the request.