commit e1a84710cd4b6527e156c7a5135b0b865a56457b Author: Zhongwei Li Date: Sun Nov 30 08:29:16 2025 +0800 Initial commit diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json new file mode 100644 index 0000000..9b0542b --- /dev/null +++ b/.claude-plugin/plugin.json @@ -0,0 +1,15 @@ +{ + "name": "salesforce-master", + "description": "Complete Salesforce expertise system across ALL platforms and integration scenarios with Windows/Git Bash compatibility. PROACTIVELY activate for: (1) ANY Salesforce task (API/data/Apex/Lightning/Flow), (2) SOQL/SOSL query design and optimization, (3) REST/SOAP API integration and authentication, (4) Apex development (classes/triggers/batch/scheduled) with Spring '25 features, (5) Lightning Web Components with lightning/graphql module and Aura development, (6) Data model design and schema management (objects/fields/relationships), (7) Integration patterns (source-to-Salesforce, Salesforce-to-target), (8) Deployment and metadata management (change sets/SFDX/CLI) with Windows/Git Bash path handling, (9) Security model implementation (profiles/permissions/sharing), (10) Flow/Process Builder/Flow Orchestrator automation, (11) Agentforce 2.0 AI agents and autonomous automation, (12) Data Cloud Vector Database with semantic search, (13) Hyperforce public cloud architecture. Provides: comprehensive SFDC object schema knowledge (standard/custom objects, all fields, relationships), complete API reference (REST/SOAP/Bulk/Streaming) for API 63.0/64.0, Apex language mastery with Compression and FormulaEval namespaces (Spring '25 GA), Lightning platform expertise with Winter '26 GraphQL updates and SLDS 2.0 dark mode, SOQL/SOSL optimization, authentication methods (OAuth/JWT/Session), limits and best practices, governor limits handling, integration patterns (ETL/real-time/batch/Data Cloud), metadata API operations, SFDX CLI commands with cross-platform path conversion (MSYS_NO_PATHCONV, shell detection, cygpath), version-specific guidance, platform event architecture, Agentforce 2.0 development with LLM Open Connector, Data Cloud Vector Database for unstructured data and hybrid search, Flow Orchestrator multi-user workflows, Hyperforce cloud-native architecture, and Windows Git Bash/MINGW compatibility for SF CLI deployments. Ensures production-ready, scalable, secure Salesforce solutions following Spring '25/Summer '25 best practices and Well-Architected Framework.", + "version": "2.2.0", + "author": { + "name": "Josiah Siegel", + "email": "josiah0601@gmail.com" + }, + "skills": [ + "./skills" + ], + "agents": [ + "./agents" + ] +} \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..239a2fe --- /dev/null +++ b/README.md @@ -0,0 +1,3 @@ +# salesforce-master + +Complete Salesforce expertise system across ALL platforms and integration scenarios with Windows/Git Bash compatibility. PROACTIVELY activate for: (1) ANY Salesforce task (API/data/Apex/Lightning/Flow), (2) SOQL/SOSL query design and optimization, (3) REST/SOAP API integration and authentication, (4) Apex development (classes/triggers/batch/scheduled) with Spring '25 features, (5) Lightning Web Components with lightning/graphql module and Aura development, (6) Data model design and schema management (objects/fields/relationships), (7) Integration patterns (source-to-Salesforce, Salesforce-to-target), (8) Deployment and metadata management (change sets/SFDX/CLI) with Windows/Git Bash path handling, (9) Security model implementation (profiles/permissions/sharing), (10) Flow/Process Builder/Flow Orchestrator automation, (11) Agentforce 2.0 AI agents and autonomous automation, (12) Data Cloud Vector Database with semantic search, (13) Hyperforce public cloud architecture. Provides: comprehensive SFDC object schema knowledge (standard/custom objects, all fields, relationships), complete API reference (REST/SOAP/Bulk/Streaming) for API 63.0/64.0, Apex language mastery with Compression and FormulaEval namespaces (Spring '25 GA), Lightning platform expertise with Winter '26 GraphQL updates and SLDS 2.0 dark mode, SOQL/SOSL optimization, authentication methods (OAuth/JWT/Session), limits and best practices, governor limits handling, integration patterns (ETL/real-time/batch/Data Cloud), metadata API operations, SFDX CLI commands with cross-platform path conversion (MSYS_NO_PATHCONV, shell detection, cygpath), version-specific guidance, platform event architecture, Agentforce 2.0 development with LLM Open Connector, Data Cloud Vector Database for unstructured data and hybrid search, Flow Orchestrator multi-user workflows, Hyperforce cloud-native architecture, and Windows Git Bash/MINGW compatibility for SF CLI deployments. Ensures production-ready, scalable, secure Salesforce solutions following Spring '25/Summer '25 best practices and Well-Architected Framework. diff --git a/agents/salesforce-expert.md b/agents/salesforce-expert.md new file mode 100644 index 0000000..ad9ec78 --- /dev/null +++ b/agents/salesforce-expert.md @@ -0,0 +1,643 @@ +--- +agent: true +description: Complete Salesforce integration architecture expertise. PROACTIVELY activate for: (1) ANY integration task (source-to-SF, SF-to-target, bidirectional), (2) Integration pattern selection, (3) Event-driven architecture, (4) Middleware/iPaaS design, (5) Real-time vs batch sync, (6) Authentication and security. Provides: comprehensive integration patterns, architecture recommendations, authentication strategies, error handling, and production-ready integration solutions. Ensures reliable, scalable integrations. +--- + +# Salesforce Integration Architecture Expert + +## 🚨 CRITICAL GUIDELINES + +### Windows File Path Requirements + +**MANDATORY: Always Use Backslashes on Windows for File Paths** + +When using Edit or Write tools on Windows, you MUST use backslashes (`\`) in file paths, NOT forward slashes (`/`). + +**Examples:** +- ❌ WRONG: `D:/repos/project/file.tsx` +- βœ… CORRECT: `D:\repos\project\file.tsx` + +This applies to: +- Edit tool file_path parameter +- Write tool file_path parameter +- All file operations on Windows systems + +### Documentation Guidelines + +**NEVER create new documentation files unless explicitly requested by the user.** + +- **Priority**: Update existing README.md files rather than creating new documentation +- **Repository cleanliness**: Keep repository root clean - only README.md unless user requests otherwise +- **Style**: Documentation should be concise, direct, and professional - avoid AI-generated tone +- **User preference**: Only create additional .md files when user specifically asks for documentation + + + +--- + +You are a Salesforce integration specialist with deep expertise in connecting Salesforce with external systems, whether Salesforce is the source, target, or both. You design event-driven architectures, implement middleware patterns, and ensure reliable data synchronization across platforms. + +## Your Expertise + +### Integration Patterns Mastery +You know all Salesforce integration patterns and when to use each: + +| Pattern | Direction | Timing | Volume | Use Case | +|---------|-----------|--------|--------|----------| +| **Request-Response** | Bidirectional | Synchronous | Low | Real-time lookups, validation | +| **Fire-and-Forget** | SF β†’ External | Asynchronous | Medium | Non-critical notifications | +| **Batch Sync** | Bidirectional | Scheduled | High | Nightly data sync, ETL | +| **Remote Call-In** | External β†’ SF | Synchronous | Low-Medium | Create/update records from external | +| **UI Update** | SF β†’ External | Real-time | Low | User-triggered actions | +| **Data Virtualization** | External β†’ SF | On-demand | Low | OData, External Objects | +| **Pub/Sub (Events)** | Bidirectional | Near real-time | High | Event-driven architecture | +| **Change Data Capture** | SF β†’ External | Real-time | High | Data replication, analytics | + +### Authentication Methods Expertise +- OAuth 2.0 (Web Server, User-Agent, JWT Bearer, Device) +- SAML SSO Integration +- Named Credentials (Salesforce β†’ External) +- Connected Apps (External β†’ Salesforce) +- API Keys and Session IDs +- Mutual TLS (mTLS) + +### Technology Stack Knowledge +- **Middleware/iPaaS**: MuleSoft, Dell Boomi, Informatica, Jitterbit, Workato +- **Message Queues**: RabbitMQ, Apache Kafka, AWS SQS, Azure Service Bus +- **Event Streaming**: Apache Kafka, AWS Kinesis, Azure Event Hubs +- **ETL Tools**: Talend, Pentaho, SSIS, Fivetran +- **API Gateways**: Apigee, AWS API Gateway, Azure API Management + +## Your Approach + +### Step 1: Requirements Gathering +Before designing integration, always clarify: + +**Data Flow**: +- Direction: External β†’ SF, SF β†’ External, or bidirectional? +- Objects/entities involved: Which Salesforce objects? Which external entities? +- Field mappings: What fields need to sync? + +**Timing**: +- Real-time (immediate) or batch (scheduled)? +- Frequency: Continuous, hourly, daily, on-demand? +- Latency tolerance: Seconds, minutes, hours? + +**Volume**: +- Records per transaction: <10, 10-2K, >2K? +- Daily volume: Hundreds, thousands, millions? +- Peak load: What's the maximum concurrent load? + +**Error Handling**: +- Retry strategy: Exponential backoff, fixed retry, manual? +- Failure notifications: Email, logging, monitoring? +- Data consistency: Strong vs eventual consistency? + +**Security**: +- Authentication method: OAuth, API key, mTLS? +- Data encryption: In-transit, at-rest? +- Compliance: GDPR, HIPAA, SOC 2? + +### Step 2: Pattern Selection +Choose the optimal integration pattern: + +**External System β†’ Salesforce (Inbound)** + +**Pattern 1: REST API Direct Integration** (Real-time, <2K records) +``` +External System β†’ Salesforce REST API β†’ Salesforce Objects +``` + +**Use when**: +- Real-time updates needed +- Low-medium volume (<2K records per operation) +- Source can implement OAuth authentication +- Direct API calls acceptable + +**Implementation**: +```javascript +// Node.js example +const axios = require('axios'); + +async function createSalesforceAccount(data) { + const response = await axios.post( + `${instanceUrl}/services/data/v60.0/sobjects/Account`, + { + Name: data.name, + Industry: data.industry, + ExternalId__c: data.id + }, + { + headers: { + 'Authorization': `Bearer ${accessToken}`, + 'Content-Type': 'application/json' + } + } + ); + return response.data; +} +``` + +**Pattern 2: Bulk API Integration** (Batch, >2K records) +``` +External System β†’ CSV/JSON β†’ Bulk API β†’ Salesforce Objects +``` + +**Use when**: +- Large data volumes (>2K records) +- Batch processing acceptable +- Initial data migration +- Nightly synchronization + +**Implementation**: +``` +1. Create Job: POST /services/data/v60.0/jobs/ingest +2. Upload CSV: PUT /services/data/v60.0/jobs/ingest/{jobId}/batches +3. Close Job: PATCH /services/data/v60.0/jobs/ingest/{jobId} +4. Monitor: Poll job status until complete +5. Download Results: Successful/failed records +``` + +**Pattern 3: Middleware/iPaaS Integration** (Complex logic, transformations) +``` +External System β†’ Middleware (MuleSoft/Boomi) β†’ Salesforce API +``` + +**Use when**: +- Complex data transformations needed +- Multiple source/target systems +- Business logic required (validation, enrichment) +- Need visual workflow design +- Error handling and retry logic required + +**Salesforce β†’ External System (Outbound)** + +**Pattern 4: Platform Events** (Event-driven, pub/sub) +``` +Salesforce Trigger β†’ Platform Event β†’ CometD Subscriber β†’ External System +``` + +**Use when**: +- Event-driven architecture +- Decoupled systems +- Multiple subscribers +- Near real-time (<1 second latency) +- High volume (up to 100K events/day) + +**Implementation**: +```apex +// Salesforce: Publish event +public class OrderEventPublisher { + public static void publishOrderCreated(Id orderId) { + OrderCreatedEvent__e event = new OrderCreatedEvent__e( + OrderId__c = orderId, + EventTimestamp__c = System.now() + ); + EventBus.publish(event); + } +} + +// Trigger +trigger OrderTrigger on Order (after insert) { + OrderEventPublisher.publishOrderCreated(Trigger.new[0].Id); +} +``` + +```javascript +// External: Subscribe via CometD +const cometd = require('cometd'); +const client = new cometd.CometD(); + +client.configure({ + url: `${instanceUrl}/cometd/60.0`, + requestHeaders: { Authorization: `Bearer ${accessToken}` } +}); + +client.handshake((reply) => { + if (reply.successful) { + client.subscribe('/event/OrderCreatedEvent__e', (message) => { + console.log('Received:', message.data.payload); + processOrder(message.data.payload); + }); + } +}); +``` + +**Pattern 5: Change Data Capture** (Automatic replication) +``` +Salesforce Objects β†’ CDC Channel β†’ CometD Subscriber β†’ Data Warehouse +``` + +**Use when**: +- Need to replicate all changes +- Building analytics data warehouse +- Audit trail requirements +- No custom code desired +- Track create, update, delete, undelete + +**Enable CDC**: +``` +Setup β†’ Change Data Capture β†’ Select objects (Account, Contact, etc.) +``` + +**Subscribe**: +```javascript +// Subscribe to Account changes +client.subscribe('/data/AccountChangeEvent', (message) => { + const payload = message.data.payload; + console.log('Change Type:', payload.ChangeEventHeader.changeType); + console.log('Changed Fields:', payload.ChangeEventHeader.changedFields); + console.log('Record IDs:', payload.ChangeEventHeader.recordIds); + + // Replicate to data warehouse + replicateToWarehouse(payload); +}); +``` + +**Pattern 6: Outbound Messages** (SOAP workflow) +``` +Workflow Rule β†’ Outbound Message β†’ External SOAP Endpoint +``` + +**Use when**: +- Legacy SOAP integrations +- Simple workflow-triggered notifications +- No custom code desired + +**Pattern 7: Scheduled Apex + Callout** (Batch sync) +``` +Scheduled Apex β†’ Batch/Queueable β†’ HTTP Callout β†’ External API +``` + +**Use when**: +- Scheduled batch sync (nightly, hourly) +- Complex business logic needed +- Custom error handling required + +**Implementation**: +```apex +global class AccountSyncScheduled implements Schedulable { + global void execute(SchedulableContext sc) { + Database.executeBatch(new AccountSyncBatch(), 200); + } +} + +global class AccountSyncBatch implements Database.Batchable, Database.AllowsCallouts { + global Database.QueryLocator start(Database.BatchableContext bc) { + return Database.getQueryLocator( + 'SELECT Id, Name, ExternalId__c FROM Account WHERE LastModifiedDate = TODAY' + ); + } + + global void execute(Database.BatchableContext bc, List scope) { + HttpRequest req = new HttpRequest(); + req.setEndpoint('callout:ExternalSystem/api/accounts'); + req.setMethod('POST'); + req.setHeader('Content-Type', 'application/json'); + req.setBody(JSON.serialize(scope)); + + Http http = new Http(); + HttpResponse res = http.send(req); + + if (res.getStatusCode() != 200) { + // Error handling + IntegrationLogger.logError('Account Sync', res.getBody()); + } + } + + global void finish(Database.BatchableContext bc) { + // Send completion email + } +} +``` + +### Step 3: Bidirectional Sync Architecture +**Design conflict resolution strategy**: + +**Conflict Resolution Strategies**: +1. **Last Write Wins**: Use SystemModstamp/timestamp to determine winner +2. **Source of Truth**: Salesforce or external always wins +3. **Field-Level Merge**: Merge non-conflicting fields +4. **Manual Resolution**: Flag conflicts for user review + +**Implementation Pattern**: +``` +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ Salesforce │←───────→│ Middleware β”‚ +β”‚ β”‚ Events β”‚ (Sync Engine) β”‚ +β”‚ ExternalId__c │←───────→│ β”‚ +β”‚ SyncHash__c β”‚ API β”‚ Conflict DB β”‚ +β”‚ LastSyncDate__c β”‚ β”‚ Error Queue β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + ↕ + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”‚ External System β”‚ + β”‚ β”‚ + β”‚ SalesforceId β”‚ + β”‚ LastSyncDate β”‚ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +``` + +**Key Components**: +- **External ID**: Both systems store each other's IDs +- **Sync Hash**: Detect changes without comparing all fields +- **Last Sync Timestamp**: Track last synchronization time +- **Conflict Database**: Store conflicts for resolution +- **Error Queue**: Retry failed syncs + +**Sync Hash Pattern**: +```apex +public class SyncHashUtil { + public static String generateHash(Account acc) { + String dataString = String.valueOf(acc.Name) + + String.valueOf(acc.Industry) + + String.valueOf(acc.AnnualRevenue); + Blob hash = Crypto.generateDigest('SHA-256', Blob.valueOf(dataString)); + return EncodingUtil.base64Encode(hash); + } + + public static Boolean hasChanged(Account acc, String previousHash) { + return generateHash(acc) != previousHash; + } +} +``` + +### Step 4: Error Handling and Retry Logic +**Implement robust error handling**: + +**Retry Strategy Pattern**: +```apex +public class RetryHandler { + private static final Integer MAX_RETRIES = 3; + private static final Integer[] BACKOFF_INTERVALS = new Integer[]{1000, 2000, 4000}; + + public static HttpResponse makeCalloutWithRetry(HttpRequest req) { + Http http = new Http(); + HttpResponse res; + Integer attempt = 0; + + while (attempt < MAX_RETRIES) { + try { + res = http.send(req); + + // Success + if (res.getStatusCode() >= 200 && res.getStatusCode() < 300) { + return res; + } + + // Retry on 429 (rate limit) or 5xx (server error) + if (res.getStatusCode() == 429 || + res.getStatusCode() >= 500) { + attempt++; + if (attempt < MAX_RETRIES) { + // Wait before retry (in real implementation, use Platform Events for async retry) + System.debug('Retrying in ' + BACKOFF_INTERVALS[attempt-1] + 'ms'); + } + } else { + // Don't retry on 4xx (client errors) + throw new CalloutException('Callout failed: ' + res.getStatusCode()); + } + + } catch (Exception e) { + attempt++; + if (attempt >= MAX_RETRIES) { + throw e; + } + } + } + + throw new CalloutException('Max retries exceeded'); + } +} +``` + +**Error Logging Pattern**: +```apex +public class IntegrationLogger { + public static void logError(String integration, String endpoint, String payload, String response, Integer statusCode) { + IntegrationLog__c log = new IntegrationLog__c( + Integration__c = integration, + Endpoint__c = endpoint, + Request__c = payload, + Response__c = response, + StatusCode__c = statusCode, + Success__c = false, + ErrorTimestamp__c = System.now() + ); + insert log; + + // Send alert if critical + if (statusCode >= 500) { + sendAlert(integration, response); + } + } + + private static void sendAlert(String integration, String errorMessage) { + // Send email or Platform Event for monitoring + } +} +``` + +### Step 5: Security and Authentication +**Implement secure authentication**: + +**OAuth 2.0 JWT Bearer Flow** (Server-to-Server): +```javascript +// Node.js implementation (cross-platform) +const jwt = require('jsonwebtoken'); +const axios = require('axios'); +const fs = require('fs'); +const path = require('path'); + +// Cross-platform path handling +function getPrivateKeyPath() { + // Use path.resolve for cross-platform compatibility + const keyPath = path.resolve(__dirname, 'private.key'); + + // For Windows Git Bash: Convert if needed + if (process.env.MSYSTEM && process.platform === 'win32') { + // Running in Git Bash on Windows + console.log('Git Bash detected, path:', keyPath); + } + + return keyPath; +} + +async function getAccessToken() { + const keyPath = getPrivateKeyPath(); + const privateKey = fs.readFileSync(keyPath, 'utf8'); + + const jwtToken = jwt.sign({ + iss: process.env.CONSUMER_KEY, + sub: process.env.USERNAME, + aud: 'https://login.salesforce.com', + exp: Math.floor(Date.now() / 1000) + (3 * 60) // 3 minutes + }, privateKey, { algorithm: 'RS256' }); + + const response = await axios.post('https://login.salesforce.com/services/oauth2/token', null, { + params: { + grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer', + assertion: jwtToken + } + }); + + return response.data.access_token; +} + +// Shell detection helper for integration scripts +function detectShellEnvironment() { + return { + isGitBash: !!process.env.MSYSTEM, + isWSL: !!process.env.WSL_DISTRO_NAME, + isPowerShell: process.env.PSModulePath?.split(';').length >= 3, + platform: process.platform, + msystem: process.env.MSYSTEM // MINGW64, MINGW32, MSYS + }; +} +``` + +**Named Credentials** (Salesforce β†’ External): +```apex +// No credentials in code! +public class ExternalAPIClient { + public static String callExternalAPI() { + HttpRequest req = new HttpRequest(); + req.setEndpoint('callout:ExternalSystem/api/data'); + req.setMethod('GET'); + + Http http = new Http(); + HttpResponse res = http.send(req); + + return res.getBody(); + } +} +``` + +**Setup Named Credential**: +``` +Setup β†’ Named Credentials β†’ New Named Credential +- Label: External System +- URL: https://external-api.com +- Identity Type: Named Principal / Per User +- Authentication Protocol: OAuth 2.0 / Password / JWT +``` + +### Step 6: Monitoring and Observability +**Implement comprehensive monitoring**: + +**Monitoring Strategy**: +``` +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ Monitoring Layer β”‚ +β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ +β”‚ β€’ API Usage Metrics β”‚ +β”‚ β€’ Integration Logs β”‚ +β”‚ β€’ Error Rates β”‚ +β”‚ β€’ Latency Tracking β”‚ +β”‚ β€’ Data Quality Metrics β”‚ +β”‚ β€’ Alert Thresholds β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +``` + +**Event Monitoring** (Salesforce): +``` +Setup β†’ Event Monitoring +- Track API usage, limits, performance +- API Total Usage (daily limits) +- API Anomaly Event (unusual patterns) +- Bulk API Result Event +- Login Event +``` + +**Custom Monitoring Dashboard**: +```apex +public class IntegrationMetrics { + public static void trackIntegrationCall(String integration, Integer responseTime, Boolean success) { + IntegrationMetric__c metric = new IntegrationMetric__c( + Integration__c = integration, + ResponseTime__c = responseTime, + Success__c = success, + Timestamp__c = System.now() + ); + insert metric; + + // Alert if response time > SLA + if (responseTime > 5000) { // 5 seconds + sendSLAAlert(integration, responseTime); + } + } +} +``` + +## Common Integration Scenarios You Excel At + +### 1. ERP β†’ Salesforce (Products, Orders) +**Architecture**: +``` +ERP System β†’ Scheduled Job β†’ Transform β†’ Bulk API β†’ Salesforce +``` + +**Implementation**: +- Nightly batch via Bulk API 2.0 +- External ID on Salesforce objects (ERPProductId__c) +- Upsert operation (create if new, update if exists) +- Error handling: Log failures, email report + +### 2. Salesforce β†’ Marketing Automation (Leads, Contacts) +**Architecture**: +``` +Salesforce Trigger β†’ Platform Event β†’ Middleware β†’ Marketing Platform API +``` + +**Implementation**: +- Real-time sync via Platform Events +- Field mapping: Salesforce fields β†’ Marketing fields +- Bidirectional sync for campaign responses +- Deduplication logic + +### 3. E-commerce β†’ Salesforce (Orders, Customers) +**Architecture**: +``` +E-commerce β†’ Webhook β†’ API Gateway β†’ Salesforce REST API +``` + +**Implementation**: +- Real-time order creation via REST API +- Customer matching via Email as External ID +- Order line items via composite API +- Inventory sync (Salesforce β†’ E-commerce) + +### 4. Salesforce β†’ Data Warehouse (Analytics) +**Architecture**: +``` +Salesforce CDC β†’ Kafka β†’ ETL β†’ Data Warehouse (Snowflake/Redshift) +``` + +**Implementation**: +- Change Data Capture for all changes +- Kafka for reliable event streaming +- Star schema in warehouse (fact/dimension tables) +- Historical tracking (Type 2 SCD) + +## You DON'T + +- Hardcode credentials (use Named Credentials, environment variables) +- Skip error handling (production integrations must handle all errors) +- Ignore API limits (monitor usage, implement throttling) +- Use synchronous calls for large volumes (>2K records) +- Skip conflict resolution strategy (bidirectional sync) +- Forget to log integration activity +- Implement without retry logic +- Skip authentication token refresh +- Ignore data encryption (HTTPS, encryption at rest) +- Design without monitoring/alerting + +## Documentation You Reference + +- Integration Patterns: https://developer.salesforce.com/docs/atlas.en-us.integration_patterns_and_practices.meta/integration_patterns_and_practices/ +- Platform Events: https://developer.salesforce.com/docs/atlas.en-us.platform_events.meta/platform_events/ +- Change Data Capture: https://developer.salesforce.com/docs/atlas.en-us.change_data_capture.meta/change_data_capture/ +- Named Credentials: https://help.salesforce.com/s/articleView?id=sf.named_credentials_about.htm +- OAuth Flows: https://help.salesforce.com/s/articleView?id=sf.remoteaccess_oauth_flows.htm + +You ensure every integration is reliable, secure, performant, and production-ready following Salesforce and industry best practices. diff --git a/plugin.lock.json b/plugin.lock.json new file mode 100644 index 0000000..356ec61 --- /dev/null +++ b/plugin.lock.json @@ -0,0 +1,65 @@ +{ + "$schema": "internal://schemas/plugin.lock.v1.json", + "pluginId": "gh:JosiahSiegel/claude-code-marketplace:plugins/salesforce-master", + "normalized": { + "repo": null, + "ref": "refs/tags/v20251128.0", + "commit": "81fd101c5b5a6dee8c40337f7519b950a6aab215", + "treeHash": "fe58c724d161c7eaa06e2f012430ad59fd819b2d6bded178abd671a2e36bc01e", + "generatedAt": "2025-11-28T10:11:51.616964Z", + "toolVersion": "publish_plugins.py@0.2.0" + }, + "origin": { + "remote": "git@github.com:zhongweili/42plugin-data.git", + "branch": "master", + "commit": "aa1497ed0949fd50e99e70d6324a29c5b34f9390", + "repoRoot": "/Users/zhongweili/projects/openmind/42plugin-data" + }, + "manifest": { + "name": "salesforce-master", + "description": "Complete Salesforce expertise system across ALL platforms and integration scenarios with Windows/Git Bash compatibility. PROACTIVELY activate for: (1) ANY Salesforce task (API/data/Apex/Lightning/Flow), (2) SOQL/SOSL query design and optimization, (3) REST/SOAP API integration and authentication, (4) Apex development (classes/triggers/batch/scheduled) with Spring '25 features, (5) Lightning Web Components with lightning/graphql module and Aura development, (6) Data model design and schema management (objects/fields/relationships), (7) Integration patterns (source-to-Salesforce, Salesforce-to-target), (8) Deployment and metadata management (change sets/SFDX/CLI) with Windows/Git Bash path handling, (9) Security model implementation (profiles/permissions/sharing), (10) Flow/Process Builder/Flow Orchestrator automation, (11) Agentforce 2.0 AI agents and autonomous automation, (12) Data Cloud Vector Database with semantic search, (13) Hyperforce public cloud architecture. Provides: comprehensive SFDC object schema knowledge (standard/custom objects, all fields, relationships), complete API reference (REST/SOAP/Bulk/Streaming) for API 63.0/64.0, Apex language mastery with Compression and FormulaEval namespaces (Spring '25 GA), Lightning platform expertise with Winter '26 GraphQL updates and SLDS 2.0 dark mode, SOQL/SOSL optimization, authentication methods (OAuth/JWT/Session), limits and best practices, governor limits handling, integration patterns (ETL/real-time/batch/Data Cloud), metadata API operations, SFDX CLI commands with cross-platform path conversion (MSYS_NO_PATHCONV, shell detection, cygpath), version-specific guidance, platform event architecture, Agentforce 2.0 development with LLM Open Connector, Data Cloud Vector Database for unstructured data and hybrid search, Flow Orchestrator multi-user workflows, Hyperforce cloud-native architecture, and Windows Git Bash/MINGW compatibility for SF CLI deployments. Ensures production-ready, scalable, secure Salesforce solutions following Spring '25/Summer '25 best practices and Well-Architected Framework.", + "version": "2.2.0" + }, + "content": { + "files": [ + { + "path": "README.md", + "sha256": "b7831334367b5e52afdcd071f2073d53d6eb0c2191380e9eaa2fc01f6f6f8269" + }, + { + "path": "agents/salesforce-expert.md", + "sha256": "7f21769aedf68e04142a367ffa45dc19cf7525e081b7615a0083bacfef0a16dd" + }, + { + "path": ".claude-plugin/plugin.json", + "sha256": "0fced84fc74c53cb5200b86878af536b278708267979f95fc6b97907ec62dd05" + }, + { + "path": "skills/flow-orchestrator-2025.md", + "sha256": "75ba811be42f6a30982985e5cf8ebf36f9b6bb70cf11f1e704176f1bae0151aa" + }, + { + "path": "skills/lightning-2025-features.md", + "sha256": "92f87a0c6bab2511de6299d80f6650e3a8b944a18d9db38914a5b5c7b387c839" + }, + { + "path": "skills/agentforce-2025.md", + "sha256": "4ac0057b0c8b735edb02701c79b4c8dcd2ec5cd29402ad3ba7f64ca51830a213" + }, + { + "path": "skills/data-cloud-2025.md", + "sha256": "821f64dd3b4934a275a8a2a7c2f39e13defbbe9b7180e15ef7d1117f019461ab" + }, + { + "path": "skills/hyperforce-2025.md", + "sha256": "99909f2b668f33574ba1ece5d08cfd1fa9bac835b6281230b9f672dc9797d8a8" + } + ], + "dirSha256": "fe58c724d161c7eaa06e2f012430ad59fd819b2d6bded178abd671a2e36bc01e" + }, + "security": { + "scannedAt": null, + "scannerVersion": null, + "flags": [] + } +} \ No newline at end of file diff --git a/skills/agentforce-2025.md b/skills/agentforce-2025.md new file mode 100644 index 0000000..2b21526 --- /dev/null +++ b/skills/agentforce-2025.md @@ -0,0 +1,604 @@ +--- +name: agentforce-2025 +description: Salesforce Agentforce AI agents and autonomous automation (2025) +--- + +## 🚨 CRITICAL GUIDELINES + +### Windows File Path Requirements + +**MANDATORY: Always Use Backslashes on Windows for File Paths** + +When using Edit or Write tools on Windows, you MUST use backslashes (`\`) in file paths, NOT forward slashes (`/`). + +**Examples:** +- ❌ WRONG: `D:/repos/project/file.tsx` +- βœ… CORRECT: `D:\repos\project\file.tsx` + +This applies to: +- Edit tool file_path parameter +- Write tool file_path parameter +- All file operations on Windows systems + + +### Documentation Guidelines + +**NEVER create new documentation files unless explicitly requested by the user.** + +- **Priority**: Update existing README.md files rather than creating new documentation +- **Repository cleanliness**: Keep repository root clean - only README.md unless user requests otherwise +- **Style**: Documentation should be concise, direct, and professional - avoid AI-generated tone +- **User preference**: Only create additional .md files when user specifically asks for documentation + + +--- + +# Agentforce: AI Agents for Salesforce (2025) + +## What is Agentforce? + +Agentforce is Salesforce's enterprise AI agent platform that enables autonomous, proactive applications to execute specialized tasks for employees and customers. Agentforce agents use large language models (LLMs) with the Atlas Reasoning Engine to analyze context, reason through decisions, and take action autonomously. + +**Key Distinction**: Agentforce represents the evolution from Einstein Copilot (conversational assistant) to autonomous agents that can complete tasks without human prompting. + +## Core Architecture + +### Atlas Reasoning Engine + +The Atlas Reasoning Engine is the brain of Agentforce, enabling agents to: +- **Understand**: Analyze full context of customer interactions or automated triggers +- **Decide**: Reason through decisions using LLMs and business logic +- **Act**: Execute actions autonomously across any system +- **Learn**: Improve over time based on outcomes and feedback + +### Agent Components + +``` +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ Agentforce Agent β”‚ +β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ +β”‚ 1. Topics (what agent handles) β”‚ +β”‚ 2. Actions (what agent can do) β”‚ +β”‚ 3. Instructions (how agent behaves) β”‚ +β”‚ 4. Channel Integrations (where agent works) β”‚ +β”‚ 5. Data Sources (what agent knows) β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +``` + +## Agentforce 2.0 (GA December 2024) + +Agentforce 2.0 is the digital labor platform for enterprises, enabling a limitless workforce through AI agents. Key enhancements: + +- **Pre-built Skills Library**: Rapid agent customization with out-of-the-box capabilities +- **Workflow Integrations**: MuleSoft for Flow, MuleSoft API Catalog, Topic Center (Q1 2025) +- **Slack Deployment**: Native Slack integration for collaboration agents +- **Enhanced RAG**: Improved retrieval augmented generation for accurate responses +- **Advanced Reasoning**: More sophisticated Atlas Reasoning Engine capabilities +- **Pricing**: $2 per conversation (GA October 25, 2024) + +## Building Agents with Agentforce Builder (GA December 2024) + +### Step 1: Define Agent Purpose + +Identify what the agent should accomplish: +- **Service Agent**: Handle support cases, answer FAQs, resolve issues (4 new actions in Spring '25) +- **Sales Development Agent**: Qualify leads, answer product questions, book meetings +- **Personal Shopper Agent**: Recommend products, handle orders, track shipments +- **Operations Agent**: Automate approvals, process requests, manage workflows +- **Slack Agent**: Proactive notifications and collaboration assistance + +### Step 2: Configure Agent Topics + +Topics define what the agent can help with: + +```apex +// Example: Service Agent Topics +Topic: Password Reset +- Intent: User wants to reset password +- Required Data: Email, Username +- Connected Action: PasswordResetFlow + +Topic: Order Status +- Intent: User wants order status +- Required Data: Order Number or Email +- Connected Action: GetOrderStatus + +Topic: Escalate to Human +- Intent: User needs human assistance +- Required Data: Case context +- Connected Action: CreateCase + NotifyAgent +``` + +### Step 3: Define Agent Actions + +Actions are what the agent can execute. These can be: +- **Standard Actions**: Pre-built Salesforce actions (create/update records) +- **Flow Actions**: Custom Flow automations +- **Apex Actions**: Custom Apex invocable methods +- **MuleSoft Actions**: API integrations via MuleSoft connectors +- **External API Actions**: REST/SOAP callouts + +**Example Apex Action**: +```apex +public class AgentActions { + @InvocableMethod(label='Get Order Status' description='Retrieves order status for customer') + public static List getOrderStatus(List requests) { + List results = new List(); + + for (OrderRequest req : requests) { + Order order = [SELECT Id, Status, EstimatedDelivery__c + FROM Order + WHERE OrderNumber = :req.orderNumber + LIMIT 1]; + + OrderStatus status = new OrderStatus(); + status.orderNumber = req.orderNumber; + status.status = order.Status; + status.estimatedDelivery = order.EstimatedDelivery__c; + results.add(status); + } + + return results; + } + + public class OrderRequest { + @InvocableVariable(required=true) + public String orderNumber; + } + + public class OrderStatus { + @InvocableVariable + public String orderNumber; + @InvocableVariable + public String status; + @InvocableVariable + public Date estimatedDelivery; + } +} +``` + +### Step 4: Write Agent Instructions + +Instructions guide the agent's behavior and tone: + +``` +You are a helpful customer service agent for Acme Corp. + +Personality: +- Friendly, professional, and empathetic +- Patient with customers who are frustrated +- Proactive in offering solutions + +Guidelines: +- Always greet customers by name if available +- Verify customer identity before sharing account information +- Offer alternatives if the requested action cannot be completed +- Escalate to human agent for: refunds >$500, legal issues, abusive customers +- Use simple language, avoid jargon +- Provide order numbers and case numbers in responses + +Security: +- Never share: passwords, credit card numbers, SSN +- Always verify identity using: email, phone, or account number +- Log all interactions for compliance + +Response Format: +- Keep responses under 3 sentences when possible +- Use bullet points for multiple items +- Include next steps or call-to-action +``` + +### Step 5: Connect Data Sources + +Agentforce agents can access: +- **Salesforce Objects**: Standard and custom objects +- **Data Cloud**: Unified customer data from all sources +- **Knowledge Base**: Salesforce Knowledge articles +- **External Systems**: Via APIs and MuleSoft connectors + +**Data Cloud Integration**: +```apex +// Query Data Cloud from Agentforce +public class AgentDataCloudActions { + @InvocableMethod(label='Get Customer 360 View') + public static List getCustomer360(List customerIds) { + // Query Data Cloud for unified customer data + List results = new List(); + + for (String customerId : customerIds) { + // Data Cloud connector provides unified view + DataCloudConnector.QueryRequest req = new DataCloudConnector.QueryRequest(); + req.sql = 'SELECT * FROM Unified_Customer WHERE customer_id = \'' + customerId + '\''; + + DataCloudConnector.QueryResponse res = DataCloudConnector.query(req); + + Customer360 customer = new Customer360(); + customer.customerId = customerId; + customer.totalPurchases = (Decimal)res.data.get('total_purchases'); + customer.preferredChannel = (String)res.data.get('preferred_channel'); + customer.lifetimeValue = (Decimal)res.data.get('lifetime_value'); + results.add(customer); + } + + return results; + } +} +``` + +### Step 6: Configure Channels + +Deploy agents across multiple channels: +- **Web Chat**: Embedded on website +- **Mobile App**: In Salesforce Mobile or custom apps +- **SMS/WhatsApp**: Messaging platforms +- **Slack/Teams**: Collaboration tools +- **Voice**: Phone support with voice-to-text +- **Email**: Email case management + +## Agent Types and Use Cases + +### 1. Service Agent (Customer Support) + +**Capabilities**: +- Answer FAQs from Knowledge Base +- Retrieve order/account status +- Process returns and exchanges +- Reset passwords and unlock accounts +- Create and route cases to specialists +- Provide troubleshooting steps + +**Example Flow**: +``` +Customer: "Where is my order #12345?" +↓ +Agent: Validates order number +↓ +Agent: Queries Order object +↓ +Agent: Retrieves tracking information +↓ +Agent: "Your order #12345 shipped yesterday and will arrive Thursday. + Tracking: UPS 1Z999AA10123456784. Need anything else?" +``` + +### 2. Sales Development Agent (SDR) + +**Capabilities**: +- Qualify inbound leads +- Answer product questions +- Handle objections with sales playbooks +- Book meetings with sales reps +- Send follow-up emails +- Update lead scores based on engagement + +**Example Flow**: +``` +Lead: "Tell me about your enterprise plan" +↓ +Agent: Retrieves product information +↓ +Agent: Explains features, pricing +↓ +Agent: Detects buying intent +↓ +Agent: "Would you like to schedule a demo with our sales team?" +↓ +Agent: Creates meeting, updates lead status to "Meeting Scheduled" +``` + +### 3. Personal Shopper Agent (E-commerce) + +**Capabilities**: +- Recommend products based on preferences +- Answer product questions +- Check inventory and availability +- Process orders and payments +- Apply discounts and promotions +- Handle cart abandonment + +### 4. Operations Agent (Internal Automation) + +**Capabilities**: +- Process employee requests (PTO, equipment) +- Automate approvals based on rules +- Onboard new employees +- Generate reports and insights +- Monitor system health +- Trigger workflows based on events + +## Integrating Agentforce with Platform Events + +Publish events to trigger Agentforce actions: + +```apex +// Publish event when order status changes +public class OrderEventPublisher { + public static void publishOrderUpdate(Id orderId, String newStatus) { + OrderStatusChangeEvent__e event = new OrderStatusChangeEvent__e( + OrderId__c = orderId, + NewStatus__c = newStatus, + Timestamp__c = System.now() + ); + + EventBus.publish(event); + + // Agentforce subscribes to this event + // Triggers proactive customer notification + } +} + +// Trigger +trigger OrderTrigger on Order (after update) { + for (Order ord : Trigger.new) { + if (ord.Status != Trigger.oldMap.get(ord.Id).Status) { + OrderEventPublisher.publishOrderUpdate(ord.Id, ord.Status); + } + } +} +``` + +**Agentforce Flow** (subscribed to OrderStatusChangeEvent__e): +``` +1. Receive event +2. Query order and customer details +3. Determine notification channel (email, SMS, push) +4. Generate personalized message using LLM +5. Send notification via preferred channel +6. Log interaction in Customer timeline +``` + +## Agentforce with External AI Systems + +Integrate Agentforce with external AI providers: + +### OpenAI GPT Integration + +```apex +public class AgentOpenAIIntegration { + @InvocableMethod(label='Generate Response with GPT-4') + public static List generateResponse(List requests) { + List responses = new List(); + + for (AIRequest req : requests) { + HttpRequest httpReq = new HttpRequest(); + httpReq.setEndpoint('callout:OpenAI/v1/chat/completions'); + httpReq.setMethod('POST'); + httpReq.setHeader('Content-Type', 'application/json'); + + Map payload = new Map{ + 'model' => 'gpt-4', + 'messages' => new List{ + new Map{ + 'role' => 'system', + 'content' => req.systemPrompt + }, + new Map{ + 'role' => 'user', + 'content' => req.userMessage + } + }, + 'temperature' => 0.7, + 'max_tokens' => 500 + }; + + httpReq.setBody(JSON.serialize(payload)); + + Http http = new Http(); + HttpResponse httpRes = http.send(httpReq); + + if (httpRes.getStatusCode() == 200) { + Map result = (Map)JSON.deserializeUntyped(httpRes.getBody()); + List choices = (List)result.get('choices'); + Map choice = (Map)choices[0]; + Map message = (Map)choice.get('message'); + responses.add((String)message.get('content')); + } + } + + return responses; + } + + public class AIRequest { + @InvocableVariable(required=true) + public String systemPrompt; + @InvocableVariable(required=true) + public String userMessage; + } +} +``` + +### Anthropic Claude Integration + +```apex +public class AgentClaudeIntegration { + @InvocableMethod(label='Generate Response with Claude') + public static List generateResponse(List requests) { + List responses = new List(); + + for (AIRequest req : requests) { + HttpRequest httpReq = new HttpRequest(); + httpReq.setEndpoint('callout:Anthropic/v1/messages'); + httpReq.setMethod('POST'); + httpReq.setHeader('Content-Type', 'application/json'); + httpReq.setHeader('anthropic-version', '2023-06-01'); + + Map payload = new Map{ + 'model' => 'claude-3-5-sonnet-20241022', + 'max_tokens' => 1024, + 'system' => req.systemPrompt, + 'messages' => new List{ + new Map{ + 'role' => 'user', + 'content' => req.userMessage + } + } + }; + + httpReq.setBody(JSON.serialize(payload)); + + Http http = new Http(); + HttpResponse httpRes = http.send(httpReq); + + if (httpRes.getStatusCode() == 200) { + Map result = (Map)JSON.deserializeUntyped(httpRes.getBody()); + List content = (List)result.get('content'); + Map contentBlock = (Map)content[0]; + responses.add((String)contentBlock.get('text')); + } + } + + return responses; + } +} +``` + +## Monitoring and Analytics + +### Agent Performance Metrics + +Track agent effectiveness: +- **Resolution Rate**: % of interactions resolved without escalation +- **Average Handle Time**: Time to resolve customer request +- **Customer Satisfaction**: Post-interaction survey scores +- **Containment Rate**: % of interactions handled by agent vs human +- **Action Success Rate**: % of successful action executions + +**Custom Reporting Object**: +```apex +public class AgentInteractionLogger { + public static void logInteraction(String agentName, String topic, + Boolean resolved, Decimal duration) { + AgentInteraction__c interaction = new AgentInteraction__c( + AgentName__c = agentName, + Topic__c = topic, + Resolved__c = resolved, + Duration__c = duration, + Timestamp__c = System.now() + ); + insert interaction; + } +} +``` + +### Analytics Dashboard Queries + +```sql +-- Resolution rate by agent +SELECT AgentName__c, + COUNT(Id) as TotalInteractions, + SUM(CASE WHEN Resolved__c = true THEN 1 ELSE 0 END) as Resolved, + AVG(Duration__c) as AvgDuration +FROM AgentInteraction__c +WHERE CreatedDate = LAST_N_DAYS:30 +GROUP BY AgentName__c + +-- Top topics requiring human escalation +SELECT Topic__c, + COUNT(Id) as Escalations +FROM AgentInteraction__c +WHERE Resolved__c = false + AND CreatedDate = LAST_N_DAYS:30 +GROUP BY Topic__c +ORDER BY COUNT(Id) DESC +LIMIT 10 +``` + +## Best Practices + +### Security and Compliance +- **Field-Level Security**: Always use WITH SECURITY_ENFORCED in SOQL +- **Data Access**: Respect sharing rules with `with sharing` keywords +- **PII Protection**: Never log sensitive data (SSN, credit cards, passwords) +- **Audit Trail**: Log all agent actions for compliance +- **Human Oversight**: Require approval for high-impact actions + +### Performance Optimization +- **Batch Processing**: Group similar actions to reduce API calls +- **Caching**: Cache frequently accessed data (product catalogs, FAQs) +- **Async Execution**: Use @future or Queueable for non-critical actions +- **Rate Limiting**: Implement throttling for external API calls +- **Timeout Handling**: Set appropriate timeouts and retry logic + +### User Experience +- **Response Time**: Aim for <3 second responses +- **Personalization**: Use customer data for personalized responses +- **Transparency**: Clearly identify agent vs human interactions +- **Escalation**: Provide easy path to human agent when needed +- **Feedback Loop**: Collect user feedback to improve agent + +### Testing +- **Unit Tests**: Test individual actions in isolation +- **Integration Tests**: Test end-to-end agent flows +- **Load Tests**: Simulate high volume to test scalability +- **User Acceptance Tests**: Validate with real users in sandbox +- **A/B Testing**: Compare different agent configurations + +## Agentforce Pricing and Licensing (2025) + +- **Agentforce Service Agent**: $2 per conversation (GA October 2024) +- **Agentforce Sales Development Agent**: $2 per conversation +- **Custom Agents**: Available with Einstein 1 Edition or add-on +- **Agent Runs**: 600 free orchestration runs per year (Enterprise+) +- **Consumption Model**: Pay-per-use based on conversations +- **Vision**: One billion agents with Agentforce by end of 2025 + +## Spring '25 and Summer '25 Updates + +### Spring '25 (API 63.0) - Available Q2 2025 +- **Enhanced Service Agent**: 4 new agent actions + 1 new topic +- **Salesforce LLM Open Connector**: Connect any LLM (OpenAI, Claude, custom models) +- **Conversation Context Testing**: Specify language, app, page type for precise testing +- **Einstein Decision Element**: Automate flow paths based on email engagement metrics +- **Einstein-Powered Flow Creation**: New Einstein Panel in Flow Builder + +### Summer '25 (API 64.0) - Available Q3 2025 +- **Hybrid Search**: Combines semantic search with keyword search for accuracy +- **Multi-language Semantic Search**: Cross-language case similarity (e.g., French β†’ English) +- **Report Formula Generation**: Plain language descriptions create complex formulas +- **AI-driven Account Summarization**: Automated insights for service agents + +## Resources + +- **Agentforce Platform**: https://www.salesforce.com/agentforce/ +- **Agentforce Builder Documentation**: https://help.salesforce.com/s/articleView?id=sf.einstein_studio.htm +- **Einstein 1 Studio**: https://help.salesforce.com/s/articleView?id=sf.einstein_studio.htm +- **Atlas Reasoning Engine**: Technical documentation in Winter '26 release notes +- **Agentforce Trailhead**: Search "Agentforce" on Trailhead for modules +- **LLM Open Connector**: Spring '25 release notes + +## Migration from Einstein Copilot + +**IMPORTANT**: Einstein Copilot was retired in January 2025 and renamed to "Agentforce (Default)". It is now one of the Agentforce agents. + +If you have Einstein Copilot (now Agentforce Assistant), migration path: + +``` +Einstein Copilot β†’ Agentforce (Default) +- Automatically migrated in January 2025 +- Conversational UI remains the same +- Add autonomous triggers and workflows +- Convert Copilot Actions to Agent Actions +- Add proactive agent behaviors +- Enable multi-channel deployment (including Slack in 2.0) +``` + +**Action Migration Example**: +```apex +// Einstein Copilot Action (reactive) +@InvocableMethod(label='Copilot: Get Account Info') +public static List getAccountInfo(List accountIds) { + return [SELECT Id, Name, Industry FROM Account WHERE Id IN :accountIds]; +} + +// Agentforce Action (proactive + reactive) +@InvocableMethod(label='Agent: Monitor and Alert on Account Changes') +public static void monitorAccounts(List accountIds) { + // Not only retrieve data, but also: + // 1. Monitor for changes + // 2. Detect anomalies (sudden revenue drop) + // 3. Proactively alert account manager + // 4. Suggest next best actions +} +``` + +Agentforce represents a paradigm shift from conversational assistants to autonomous agents that can complete complex, multi-step tasks without human intervention while maintaining trust and security. diff --git a/skills/data-cloud-2025.md b/skills/data-cloud-2025.md new file mode 100644 index 0000000..ba214ef --- /dev/null +++ b/skills/data-cloud-2025.md @@ -0,0 +1,1022 @@ +--- +name: data-cloud-2025 +description: Salesforce Data Cloud integration patterns and architecture (2025) +--- + +## 🚨 CRITICAL GUIDELINES + +### Windows File Path Requirements + +**MANDATORY: Always Use Backslashes on Windows for File Paths** + +When using Edit or Write tools on Windows, you MUST use backslashes (`\`) in file paths, NOT forward slashes (`/`). + +**Examples:** +- ❌ WRONG: `D:/repos/project/file.tsx` +- βœ… CORRECT: `D:\repos\project\file.tsx` + +This applies to: +- Edit tool file_path parameter +- Write tool file_path parameter +- All file operations on Windows systems + + +### Documentation Guidelines + +**NEVER create new documentation files unless explicitly requested by the user.** + +- **Priority**: Update existing README.md files rather than creating new documentation +- **Repository cleanliness**: Keep repository root clean - only README.md unless user requests otherwise +- **Style**: Documentation should be concise, direct, and professional - avoid AI-generated tone +- **User preference**: Only create additional .md files when user specifically asks for documentation + + +--- + +# Salesforce Data Cloud Integration Patterns (2025) + +## What is Salesforce Data Cloud? + +Salesforce Data Cloud is a real-time customer data platform (CDP) that unifies data from any source to create a complete, actionable view of every customer. It powers AI, automation, and analytics across the entire Customer 360 platform. + +**Key Capabilities**: +- **Data Ingestion**: Connect 200+ sources (Salesforce, external systems, data lakes) +- **Data Harmonization**: Map disparate data to unified data model +- **Identity Resolution**: Match and merge customer records across sources +- **Real-Time Activation**: Trigger actions based on streaming data +- **Zero Copy Architecture**: Query data in place without moving it +- **AI/ML Ready**: Powers Einstein, Agentforce, and predictive models +- **Vector Database** (GA March 2025): Store and query unstructured data with semantic search +- **Hybrid Search** (Pilot 2025): Combine semantic and keyword search for accuracy + +## Data Cloud Architecture + +``` +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ Data Sources β”‚ +β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ +β”‚ Salesforce CRM β”‚ External Apps β”‚ Data Warehouses β”‚ APIs β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”˜ + β”‚ β”‚ β”‚ β”‚ + β”Œβ”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β” + β”‚ Data Cloud Connectors & Ingestion β”‚ + β”‚ β”œβ”€ Real-time Streaming (Change Data Capture) β”‚ + β”‚ β”œβ”€ Batch Import (scheduled/on-demand) β”‚ + β”‚ └─ Zero Copy (Snowflake, Databricks, BigQuery) β”‚ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”‚ Data Model & Harmonization β”‚ + β”‚ β”œβ”€ Map to Common Data Model (DMO objects) β”‚ + β”‚ β”œβ”€ Identity Resolution (match & merge) β”‚ + β”‚ └─ Data Transformation (calculated insights) β”‚ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”‚ Unified Customer Profile (360Β° View) β”‚ + β”‚ β”œβ”€ Demographics, Transactions, Behavior, Events β”‚ + β”‚ └─ Real-time Profile API for instant access β”‚ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”‚ Activation & Actions β”‚ + β”‚ β”œβ”€ Salesforce Flow (real-time automation) β”‚ + β”‚ β”œβ”€ Marketing Cloud (segmentation/journeys) β”‚ + β”‚ β”œβ”€ Agentforce (AI agents) β”‚ + β”‚ β”œβ”€ Einstein AI (predictions/recommendations) β”‚ + β”‚ └─ External Systems (reverse ETL) β”‚ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +``` + +## Data Ingestion Patterns + +### Pattern 1: Real-Time Streaming with Change Data Capture + +**Use Case**: Keep Data Cloud synchronized with Salesforce objects in real-time + +```apex +// Enable Change Data Capture for objects +// Setup β†’ Change Data Capture β†’ Select: Account, Contact, Opportunity + +// Data Cloud automatically subscribes to CDC channels +// No code needed - configure in Data Cloud UI + +// Optional: Custom streaming logic +public class DataCloudStreamHandler { + public static void publishCustomEvent(Id recordId, String changeType) { + // Publish custom platform event for Data Cloud + DataCloudChangeEvent__e event = new DataCloudChangeEvent__e( + RecordId__c = recordId, + ObjectType__c = 'Custom_Object__c', + ChangeType__c = changeType, + Timestamp__c = System.now(), + PayloadJson__c = JSON.serialize(getRecordData(recordId)) + ); + + EventBus.publish(event); + } + + private static Map getRecordData(Id recordId) { + // Retrieve and return record data + String objectType = recordId.getSObjectType().getDescribe().getName(); + String query = 'SELECT FIELDS(ALL) FROM ' + objectType + + ' WHERE Id = :recordId LIMIT 1'; + SObject record = Database.query(query); + return (Map)JSON.deserializeUntyped(JSON.serialize(record)); + } +} +``` + +### Pattern 2: Batch Import from External Systems + +**Use Case**: Import data from ERP, e-commerce, or other business systems + +**Data Cloud Configuration**: +``` +1. Create Data Source (Setup β†’ Data Cloud β†’ Data Sources) + - Type: Amazon S3, SFTP, Azure Blob, Google Cloud Storage + - Authentication: API key, OAuth, IAM role + - Schedule: Hourly, Daily, Weekly + +2. Map to Data Model Objects (DMO) + - Source Field β†’ DMO Field mapping + - Data type conversions + - Formula fields and transformations + +3. Configure Identity Resolution + - Match rules (email, customer ID, phone) + - Reconciliation rules (which source wins) +``` + +**API-Based Batch Import**: +```python +# Python example: Push data to Data Cloud via API +import requests +import pandas as pd + +def upload_to_data_cloud(csv_file, object_name, access_token, instance_url): + """Upload CSV to Data Cloud via Bulk API""" + + # Step 1: Create ingestion job + job_url = f"{instance_url}/services/data/v62.0/jobs/ingest" + job_payload = { + "object": object_name, + "operation": "upsert", + "externalIdFieldName": "ExternalId__c" + } + + response = requests.post( + job_url, + headers={ + "Authorization": f"Bearer {access_token}", + "Content-Type": "application/json" + }, + json=job_payload + ) + + job_id = response.json()["id"] + + # Step 2: Upload CSV data + with open(csv_file, 'rb') as f: + csv_data = f.read() + + upload_url = f"{job_url}/{job_id}/batches" + requests.put( + upload_url, + headers={ + "Authorization": f"Bearer {access_token}", + "Content-Type": "text/csv" + }, + data=csv_data + ) + + # Step 3: Close job + close_url = f"{job_url}/{job_id}" + requests.patch( + close_url, + headers={ + "Authorization": f"Bearer {access_token}", + "Content-Type": "application/json" + }, + json={"state": "UploadComplete"} + ) + + return job_id +``` + +### Pattern 3: Zero Copy Integration (Snowflake, Databricks) + +**Use Case**: Access data warehouse data without copying to Salesforce + +**Benefits**: +- No data duplication (single source of truth) +- No data transfer costs +- Real-time access to warehouse data +- Maintain data governance in warehouse + +**Snowflake Zero Copy Setup**: +```sql +-- In Snowflake: Grant access to Salesforce +GRANT USAGE ON DATABASE customer_data TO ROLE salesforce_role; +GRANT USAGE ON SCHEMA customer_data.public TO ROLE salesforce_role; +GRANT SELECT ON TABLE customer_data.public.orders TO ROLE salesforce_role; + +-- Create secure share +CREATE SHARE salesforce_data_share; +GRANT USAGE ON DATABASE customer_data TO SHARE salesforce_data_share; +ALTER SHARE salesforce_data_share ADD ACCOUNTS = 'SALESFORCE_ORG_ID'; +``` + +**Data Cloud Configuration**: +``` +1. Add Zero Copy Connector (Data Cloud β†’ Data Sources) + - Type: Snowflake Zero Copy + - Connection: Account URL, username, private key + - Database/Schema selection + +2. Create Data Stream (virtual tables) + - Select Snowflake tables to expose + - Map to DMO or keep as is + - Configure refresh (real-time or scheduled) + +3. Query in Salesforce + - Use SOQL-like syntax to query Snowflake data + - Join with Salesforce data + - No data movement required +``` + +**Query Zero Copy Data**: +```apex +// Query Snowflake data from Apex (via Data Cloud) +public class DataCloudZeroCopyQuery { + public static List> querySnowflakeOrders(String customerId) { + // Data Cloud Query API + String query = 'SELECT order_id, total_amount, order_date ' + + 'FROM snowflake_orders ' + + 'WHERE customer_id = \'' + customerId + '\' ' + + 'ORDER BY order_date DESC LIMIT 10'; + + HttpRequest req = new HttpRequest(); + req.setEndpoint('callout:DataCloud/v1/query'); + req.setMethod('POST'); + req.setHeader('Content-Type', 'application/json'); + req.setBody(JSON.serialize(new Map{'query' => query})); + + Http http = new Http(); + HttpResponse res = http.send(req); + + if (res.getStatusCode() == 200) { + Map result = (Map)JSON.deserializeUntyped(res.getBody()); + return (List>)result.get('data'); + } + + return new List>(); + } +} +``` + +## Identity Resolution + +### Matching Rules + +**Configure identity resolution to create unified profiles**: + +``` +Match Rules Configuration: +β”œβ”€ Primary Match (exact match on email) +β”‚ └─ IF email matches THEN merge profiles +β”œβ”€ Secondary Match (fuzzy match on name + phone) +β”‚ └─ IF firstName + lastName similar AND phone matches THEN merge +└─ Tertiary Match (external ID) + └─ IF ExternalCustomerId matches THEN merge + +Reconciliation Rules (conflict resolution): +β”œβ”€ Most Recent: Use most recently updated value +β”œβ”€ Source Priority: Salesforce > ERP > Website +└─ Field-Level Rules: Email from Salesforce, Revenue from ERP +``` + +**Custom Matching Logic**: +```apex +// Custom matching for complex scenarios +public class DataCloudMatchingService { + public static Boolean shouldMatch(Map profile1, + Map profile2) { + // Custom matching logic beyond standard rules + + String email1 = (String)profile1.get('email'); + String email2 = (String)profile2.get('email'); + + // Exact email match + if (email1 != null && email1.equalsIgnoreCase(email2)) { + return true; + } + + // Fuzzy name + address match + String name1 = (String)profile1.get('fullName'); + String name2 = (String)profile2.get('fullName'); + String address1 = (String)profile1.get('address'); + String address2 = (String)profile2.get('address'); + + if (isNameSimilar(name1, name2) && isSameAddress(address1, address2)) { + return true; + } + + return false; + } + + private static Boolean isNameSimilar(String name1, String name2) { + // Implement Levenshtein distance or phonetic matching + return calculateSimilarity(name1, name2) > 0.85; + } +} +``` + +## Real-Time Activation Patterns + +### Pattern 1: Flow Automation Based on Data Cloud Events + +**Use Case**: Trigger Flow when customer behavior detected in Data Cloud + +``` +Data Cloud Calculated Insight: "High-Value Customer at Risk" +- Logic: Purchase frequency decreased by 50% in last 30 days +- Trigger: When insight calculated +↓ +Platform Event: HighValueCustomerRisk__e +↓ +Salesforce Flow: "Retain High-Value Customer" +- Create Task for Account Manager +- Send personalized offer via Marketing Cloud +- Add to "At-Risk" campaign +- Log activity timeline +``` + +**Apex Implementation**: +```apex +// Subscribe to Data Cloud insights +trigger DataCloudInsightTrigger on HighValueCustomerRisk__e (after insert) { + List tasks = new List(); + + for (HighValueCustomerRisk__e event : Trigger.new) { + // Create retention task + Task task = new Task( + Subject = 'Urgent: High-value customer at risk', + Description = 'Customer ' + event.CustomerName__c + + ' shows declining engagement. Take action.', + WhatId = event.AccountId__c, + Priority = 'High', + Status = 'Open', + ActivityDate = Date.today().addDays(1) + ); + tasks.add(task); + + // Trigger retention campaign + RetentionCampaignService.addToRetentionCampaign( + event.CustomerId__c, + event.RiskScore__c + ); + } + + if (!tasks.isEmpty()) { + insert tasks; + } +} +``` + +### Pattern 2: Agentforce with Data Cloud + +**Use Case**: AI agent uses Data Cloud for complete customer context + +```apex +// Agentforce action: Get unified customer view +public class AgentforceDataCloudActions { + @InvocableMethod(label='Get Customer 360 Profile') + public static List getCustomer360(List customerIds) { + List profiles = new List(); + + for (String customerId : customerIds) { + // Query Data Cloud unified profile + HttpRequest req = new HttpRequest(); + req.setEndpoint('callout:DataCloud/v1/profile/' + customerId); + req.setMethod('GET'); + + Http http = new Http(); + HttpResponse res = http.send(req); + + if (res.getStatusCode() == 200) { + Map data = (Map) + JSON.deserializeUntyped(res.getBody()); + + CustomerProfile profile = new CustomerProfile(); + profile.customerId = customerId; + + // Demographics + profile.name = (String)data.get('name'); + profile.email = (String)data.get('email'); + profile.segment = (String)data.get('segment'); + + // Behavioral + profile.totalPurchases = (Decimal)data.get('total_purchases'); + profile.avgOrderValue = (Decimal)data.get('avg_order_value'); + profile.lastPurchaseDate = Date.valueOf((String)data.get('last_purchase_date')); + profile.preferredChannel = (String)data.get('preferred_channel'); + + // Engagement + profile.emailEngagement = (Decimal)data.get('email_engagement_score'); + profile.websiteVisits = (Integer)data.get('website_visits_30d'); + profile.supportCases = (Integer)data.get('support_cases_90d'); + + // Predictive + profile.churnRisk = (Decimal)data.get('churn_risk_score'); + profile.lifetimeValue = (Decimal)data.get('predicted_lifetime_value'); + profile.nextBestAction = (String)data.get('next_best_action'); + + profiles.add(profile); + } + } + + return profiles; + } + + public class CustomerProfile { + @InvocableVariable public String customerId; + @InvocableVariable public String name; + @InvocableVariable public String email; + @InvocableVariable public String segment; + @InvocableVariable public Decimal totalPurchases; + @InvocableVariable public Decimal avgOrderValue; + @InvocableVariable public Date lastPurchaseDate; + @InvocableVariable public String preferredChannel; + @InvocableVariable public Decimal emailEngagement; + @InvocableVariable public Integer websiteVisits; + @InvocableVariable public Integer supportCases; + @InvocableVariable public Decimal churnRisk; + @InvocableVariable public Decimal lifetimeValue; + @InvocableVariable public String nextBestAction; + } +} +``` + +### Pattern 3: Reverse ETL (Data Cloud β†’ External Systems) + +**Use Case**: Push enriched Data Cloud data back to external systems + +**Configuration**: +``` +Data Cloud β†’ Data Actions β†’ Create Data Action +- Target: External API endpoint +- Trigger: Segment membership change, insight calculated +- Payload: Customer profile fields +- Authentication: Named Credential +- Schedule: Real-time or batch +``` + +**Apex Outbound Sync**: +```apex +public class DataCloudReverseETL { + @InvocableMethod(label='Sync Enriched Profile to External System') + public static void syncToExternalSystem(List customerIds) { + for (String customerId : customerIds) { + // Get enriched profile from Data Cloud + Map profile = DataCloudService.getProfile(customerId); + + // Transform for external system + Map payload = new Map{ + 'customer_id' => customerId, + 'segment' => profile.get('segment'), + 'lifetime_value' => profile.get('ltv'), + 'churn_risk' => profile.get('churn_risk'), + 'next_best_product' => profile.get('next_best_product') + }; + + // Send to external system + HttpRequest req = new HttpRequest(); + req.setEndpoint('callout:ExternalCRM/api/customers/' + customerId); + req.setMethod('PUT'); + req.setHeader('Content-Type', 'application/json'); + req.setBody(JSON.serialize(payload)); + + Http http = new Http(); + HttpResponse res = http.send(req); + + // Log result + DataCloudSyncLog__c log = new DataCloudSyncLog__c( + CustomerId__c = customerId, + Direction__c = 'Outbound', + Success__c = res.getStatusCode() == 200, + Timestamp__c = System.now() + ); + insert log; + } + } +} +``` + +## Calculated Insights and Segmentation + +### Create Calculated Insights + +**Use Case**: Define metrics and KPIs on unified data + +```sql +-- Example: Customer Lifetime Value +CREATE CALCULATED INSIGHT customer_lifetime_value AS +SELECT + customer_id, + SUM(order_total) as total_revenue, + COUNT(order_id) as total_orders, + AVG(order_total) as avg_order_value, + DATEDIFF(day, first_order_date, CURRENT_DATE) as customer_age_days, + SUM(order_total) / NULLIF(DATEDIFF(day, first_order_date, CURRENT_DATE), 0) * 365 as annual_revenue, + (SUM(order_total) / NULLIF(DATEDIFF(day, first_order_date, CURRENT_DATE), 0) * 365) * 5 as predicted_ltv_5yr +FROM unified_orders +GROUP BY customer_id, first_order_date +``` + +### Dynamic Segmentation + +**Use Case**: Create segments that update in real-time + +```sql +-- Segment: High-Value Active Customers +CREATE SEGMENT high_value_active_customers AS +SELECT customer_id +FROM customer_360_profile +WHERE + predicted_ltv_5yr > 10000 + AND last_purchase_date >= CURRENT_DATE - INTERVAL '30' DAY + AND email_engagement_score > 0.7 + AND churn_risk_score < 0.3 +``` + +**Use in Salesforce**: +```apex +// Query segment membership +List highValueContacts = [ + SELECT Id, Name, Email + FROM Contact + WHERE Id IN ( + SELECT ContactId__c + FROM DataCloudSegmentMember__c + WHERE SegmentName__c = 'high_value_active_customers' + ) +]; +``` + +## Data Cloud Vector Database (GA March 2025) + +### What is Vector Database? + +Data Cloud Vector Database ingests, stores, unifies, indexes, and allows semantic queries of unstructured data using generative AI techniques. It creates embeddings that enable semantic querying and seamless integration with structured data in the Einstein platform. + +**Supported Unstructured Data**: +- Emails and email threads +- Text documents (PDFs, Word, etc.) +- Social media content +- Web content and chat transcripts +- Call transcripts and recordings +- Knowledge base articles +- Customer reviews and feedback + +### How Vector Database Works + +``` +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ Unstructured Data Sources β”‚ +β”‚ Emails β”‚ Documents β”‚ Transcripts β”‚ Social β”‚ Knowledge β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”‚ Text Embedding Generation β”‚ + β”‚ Uses LLM to convert text β†’ vector embeddings β”‚ + β”‚ (768-dimensional numeric representations) β”‚ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”‚ Vector Database Storage & Indexing β”‚ + β”‚ Stores embeddings with metadata β”‚ + β”‚ Creates high-performance vector index β”‚ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”‚ Semantic Search Queries β”‚ + β”‚ Natural language query β†’ embedding β†’ similarity β”‚ + β”‚ Returns most semantically similar content β”‚ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +``` + +### Semantic Search with Einstein Copilot Search + +Semantic search understands the meaning and intent of queries, going beyond keyword matching: + +**Example**: +- **Query**: "How do I return a defective product?" +- **Traditional Keyword Search**: Matches documents containing exact words "return", "defective", "product" +- **Semantic Search**: Finds documents about: + - Return policies + - Warranty claims + - Product exchanges + - Refund procedures + - RMA processes + - *Even if they use different wording* + +### Implementing Vector Database + +**Step 1: Configure Unstructured Data Sources** + +``` +Setup β†’ Data Cloud β†’ Data Sources β†’ Create +- Source Type: Unstructured Data +- Options: + β”œβ”€ Salesforce Knowledge + β”œβ”€ EmailMessage object + β”œβ”€ External documents (S3, Azure Blob, Google Drive) + β”œβ”€ API-based ingestion + └─ ContentDocument/File objects +``` + +**Step 2: Enable Vector Indexing** + +```apex +// API to index unstructured content +public class VectorDatabaseService { + public static void indexDocument(String documentId, String content, Map metadata) { + // Create vector embedding request + HttpRequest req = new HttpRequest(); + req.setEndpoint('callout:DataCloud/v1/vector/index'); + req.setMethod('POST'); + req.setHeader('Content-Type', 'application/json'); + + Map payload = new Map{ + 'documentId' => documentId, + 'content' => content, + 'metadata' => metadata, + 'source' => 'Salesforce', + 'timestamp' => System.now().getTime() + }; + + req.setBody(JSON.serialize(payload)); + + Http http = new Http(); + HttpResponse res = http.send(req); + + if (res.getStatusCode() == 200) { + System.debug('Document indexed: ' + documentId); + } else { + System.debug('Indexing failed: ' + res.getBody()); + } + } +} + +// Trigger to auto-index Knowledge articles +trigger KnowledgeArticleTrigger on Knowledge__kav (after insert, after update) { + for (Knowledge__kav article : Trigger.new) { + if (article.PublishStatus == 'Online') { + Map metadata = new Map{ + 'articleNumber' => article.ArticleNumber, + 'title' => article.Title, + 'category' => article.Category__c, + 'language' => article.Language + }; + + VectorDatabaseService.indexDocument( + article.Id, + article.Body__c, + metadata + ); + } + } +} +``` + +**Step 3: Perform Semantic Search** + +```apex +public class SemanticSearchService { + @InvocableMethod(label='Semantic Search' description='Search unstructured data semantically') + public static List semanticSearch(List requests) { + List results = new List(); + + for (SearchRequest req : requests) { + HttpRequest httpReq = new HttpRequest(); + httpReq.setEndpoint('callout:DataCloud/v1/vector/search'); + httpReq.setMethod('POST'); + httpReq.setHeader('Content-Type', 'application/json'); + + Map payload = new Map{ + 'query' => req.query, + 'topK' => req.maxResults, + 'filters' => req.filters, + 'includeMetadata' => true + }; + + httpReq.setBody(JSON.serialize(payload)); + + Http http = new Http(); + HttpResponse httpRes = http.send(httpReq); + + if (httpRes.getStatusCode() == 200) { + Map response = (Map) + JSON.deserializeUntyped(httpRes.getBody()); + + List hits = (List)response.get('results'); + + SearchResult result = new SearchResult(); + result.query = req.query; + result.matches = new List(); + + for (Object hit : hits) { + Map doc = (Map)hit; + result.matches.add((String)doc.get('content')); + } + + results.add(result); + } + } + + return results; + } + + public class SearchRequest { + @InvocableVariable(required=true) + public String query; + @InvocableVariable + public Integer maxResults = 10; + @InvocableVariable + public Map filters; + } + + public class SearchResult { + @InvocableVariable + public String query; + @InvocableVariable + public List matches; + } +} +``` + +### Hybrid Search (Pilot 2025) + +Hybrid search combines semantic search with traditional keyword search for improved accuracy: + +**Benefits**: +- Understands semantic similarities and context (semantic search) +- Recognizes company-specific words and concepts (keyword search) +- Higher accuracy than either method alone +- Handles acronyms, product codes, and technical terms better + +**Use Case Example**: +``` +Service agent searches: "customer wants refund for SKU-12345" + +Semantic Search finds: +- Return policy documents +- Refund procedures +- Customer satisfaction articles + +Keyword Search finds: +- Specific SKU-12345 product documentation +- Previous cases mentioning SKU-12345 +- Product-specific return windows + +Hybrid Search combines both: +- Return procedures specifically for SKU-12345 +- Previous refund cases for this product +- Product warranty terms +``` + +**Implementation**: +```apex +public class HybridSearchService { + public static List> hybridSearch(String query, Map filters) { + HttpRequest req = new HttpRequest(); + req.setEndpoint('callout:DataCloud/v1/search/hybrid'); + req.setMethod('POST'); + req.setHeader('Content-Type', 'application/json'); + + Map payload = new Map{ + 'query' => query, + 'semantic' => new Map{ + 'enabled' => true, + 'weight' => 0.6 // 60% semantic + }, + 'keyword' => new Map{ + 'enabled' => true, + 'weight' => 0.4 // 40% keyword + }, + 'filters' => filters, + 'topK' => 20 + }; + + req.setBody(JSON.serialize(payload)); + + Http http = new Http(); + HttpResponse res = http.send(req); + + if (res.getStatusCode() == 200) { + Map response = (Map)JSON.deserializeUntyped(res.getBody()); + return (List>)response.get('results'); + } + + return new List>(); + } +} +``` + +### Multi-Language Semantic Search + +Vector database supports cross-language semantic search: + +**Example**: +- Service agent types case subject in French: "ProblΓ¨me de connexion" +- Semantic search finds similar cases in English: + - "Login issues" + - "Connection problems" + - "Unable to access account" +- Returns relevant solutions regardless of language + +**Configuration**: +``` +Data Cloud β†’ Vector Database β†’ Settings +- Enable multi-language support +- Supported languages: 100+ languages via multilingual embeddings +- Automatic language detection +- Cross-language similarity matching +``` + +### Use Cases for Vector Database + +**1. Customer Service Knowledge Retrieval** +```apex +// Agentforce action: Find relevant knowledge articles +@InvocableMethod(label='Find Relevant Articles') +public static List findRelevantArticles(List customerQueries) { + List articles = new List(); + + for (String query : customerQueries) { + // Semantic search finds conceptually similar articles + List results = SemanticSearchService.semanticSearch( + new List{new SearchRequest(query, 5)} + ); + + if (!results.isEmpty()) { + articles.addAll(results[0].matches); + } + } + + return articles; +} +``` + +**2. Case Similarity Detection** +```apex +// Find similar past cases to suggest solutions +public class CaseSimilarityService { + public static List findSimilarCases(String caseDescription) { + // Semantic search in past cases + List results = SemanticSearchService.semanticSearch( + new List{new SearchRequest(caseDescription, 10)} + ); + + // Extract case IDs from metadata + Set caseIds = new Set(); + // ... extract IDs from results + + return [SELECT Id, Subject, Description, Status, Resolution__c + FROM Case + WHERE Id IN :caseIds + AND Status = 'Closed' + ORDER BY ClosedDate DESC]; + } +} +``` + +**3. Lead Scoring from Unstructured Data** +```apex +// Analyze email content and web behavior for lead scoring +public class LeadScoringService { + public static Decimal scoreLeadFromContent(Id leadId) { + // Get all email interactions + List emails = [SELECT Id, TextBody + FROM EmailMessage + WHERE RelatedToId = :leadId]; + + Decimal score = 0; + + // Semantic search for buying intent keywords + String allContent = ''; + for (EmailMessage email : emails) { + allContent += email.TextBody + ' '; + } + + // Check semantic similarity to high-intent phrases + List intentPhrases = new List{ + 'ready to purchase', + 'need pricing quote', + 'schedule demo', + 'implementation timeline' + }; + + for (String phrase : intentPhrases) { + // Semantic similarity score + Decimal similarity = calculateSemanticSimilarity(allContent, phrase); + score += similarity * 10; + } + + return score; + } +} +``` + +## Data Cloud SQL (ANSI SQL Support) + +Query Data Cloud using standard SQL: + +```sql +-- Complex analytical query across multiple sources +SELECT + c.customer_id, + c.name, + c.segment, + COUNT(DISTINCT o.order_id) as total_orders, + SUM(o.order_total) as revenue, + AVG(s.satisfaction_score) as avg_satisfaction, + MAX(o.order_date) as last_order_date +FROM + unified_customer c + INNER JOIN unified_orders o ON c.customer_id = o.customer_id + LEFT JOIN support_interactions s ON c.customer_id = s.customer_id +WHERE + o.order_date >= CURRENT_DATE - INTERVAL '90' DAY +GROUP BY + c.customer_id, c.name, c.segment +HAVING + COUNT(DISTINCT o.order_id) >= 3 +ORDER BY + revenue DESC +LIMIT 100 +``` + +## Authentication Patterns + +### OAuth 2.0 JWT Bearer Flow (Server-to-Server) + +```python +# External system β†’ Data Cloud authentication +import jwt +import time +import requests + +def get_data_cloud_access_token(client_id, private_key, username, instance_url): + """Get access token for Data Cloud API""" + + # Create JWT + payload = { + 'iss': client_id, + 'sub': username, + 'aud': instance_url, + 'exp': int(time.time()) + 180 # 3 minutes + } + + encoded_jwt = jwt.encode(payload, private_key, algorithm='RS256') + + # Exchange JWT for access token + token_url = f"{instance_url}/services/oauth2/token" + response = requests.post(token_url, data={ + 'grant_type': 'urn:ietf:params:oauth:grant-type:jwt-bearer', + 'assertion': encoded_jwt + }) + + return response.json()['access_token'] +``` + +## Best Practices + +### Performance +- **Use Zero Copy** for large datasets (>10M records) +- **Batch imports** outside business hours +- **Index frequently queried fields** in Data Cloud +- **Limit real-time triggers** to critical events +- **Cache unified profiles** when possible + +### Security +- **Field-level security** applies to Data Cloud queries from Salesforce +- **Data masking** for PII in non-production environments +- **Encryption at rest** and in transit (TLS 1.2+) +- **Audit logging** for all data access +- **Role-based access control** (RBAC) for Data Cloud users + +### Data Quality +- **Data validation** before ingestion +- **Deduplication rules** at source and in Data Cloud +- **Data lineage tracking** (know source of each field) +- **Quality scores** for unified profiles +- **Regular data audits** and cleansing + +## Resources + +- **Data Cloud Documentation**: https://developer.salesforce.com/docs/data/data-cloud-int/guide +- **Zero Copy Partner Network**: https://www.salesforce.com/data/zero-copy/ +- **Data Cloud Pricing**: Part of Customer 360 platform, usage-based pricing +- **Trailhead**: "Data Cloud Basics" and "Data Cloud for Developers" diff --git a/skills/flow-orchestrator-2025.md b/skills/flow-orchestrator-2025.md new file mode 100644 index 0000000..a0ec2a7 --- /dev/null +++ b/skills/flow-orchestrator-2025.md @@ -0,0 +1,605 @@ +--- +name: flow-orchestrator-2025 +description: Salesforce Flow Orchestrator multi-user automation best practices (2025) +--- + +## 🚨 CRITICAL GUIDELINES + +### Windows File Path Requirements + +**MANDATORY: Always Use Backslashes on Windows for File Paths** + +When using Edit or Write tools on Windows, you MUST use backslashes (`\`) in file paths, NOT forward slashes (`/`). + +**Examples:** +- ❌ WRONG: `D:/repos/project/file.tsx` +- βœ… CORRECT: `D:\repos\project\file.tsx` + +This applies to: +- Edit tool file_path parameter +- Write tool file_path parameter +- All file operations on Windows systems + + +### Documentation Guidelines + +**NEVER create new documentation files unless explicitly requested by the user.** + +- **Priority**: Update existing README.md files rather than creating new documentation +- **Repository cleanliness**: Keep repository root clean - only README.md unless user requests otherwise +- **Style**: Documentation should be concise, direct, and professional - avoid AI-generated tone +- **User preference**: Only create additional .md files when user specifically asks for documentation + + +--- + +# Salesforce Flow Orchestrator (2025) + +## What is Flow Orchestrator? + +Flow Orchestrator enables you to orchestrate multi-user, multi-step, and multi-stage business processes without code. It allows different users to complete sequential tasks within a unified workflow, with built-in approvals, conditional logic, and error handling. + +**Key Capabilities**: +- **Multi-User Workflows**: Assign tasks to different users/teams across stages +- **Stage-Based Execution**: Organize work into logical stages +- **Background Automation**: Combine user tasks with automated steps +- **Visual Progress Tracking**: Users see their position in the workflow +- **Fault Paths**: Handle errors gracefully (Summer '25) +- **No-Code**: Build complex processes without Apex + +## When to Use Flow Orchestrator + +| Use Case | Flow Orchestrator? | Why | +|----------|-------------------|-----| +| Employee Onboarding (HR β†’ IT β†’ Manager) | βœ… Yes | Multi-user, sequential stages | +| Quote-to-Cash (Sales β†’ Finance β†’ Operations) | βœ… Yes | Cross-functional approval process | +| Case Escalation (L1 β†’ L2 β†’ L3 Support) | βœ… Yes | Tiered assignment with SLAs | +| Simple record automation (create/update) | ❌ No | Use Record-Triggered Flow | +| Single-user process | ❌ No | Use Screen Flow | +| Batch data processing | ❌ No | Use Scheduled Flow or Apex Batch | + +## Orchestration Architecture + +``` +Orchestration = Stages β†’ Steps β†’ Background Automations + +Stage 1: "HR Review" +β”œβ”€ Step 1.1: Interactive Step (HR Manager reviews) +β”œβ”€ Step 1.2: Background Automation (create records) +└─ Decision: Approved? β†’ Next Stage : End + +Stage 2: "IT Provisioning" +β”œβ”€ Step 2.1: Interactive Step (IT assigns equipment) +β”œβ”€ Step 2.2: Background Automation (provision accounts) +└─ Step 2.3: Interactive Step (IT confirms completion) + +Stage 3: "Manager Onboarding" +β”œβ”€ Step 3.1: Interactive Step (Manager schedules 1:1) +└─ Step 3.2: Background Automation (send welcome email) +``` + +## Building an Orchestration (Step-by-Step) + +### Example: Employee Onboarding Process + +**Requirements**: +- HR reviews new hire documents β†’ Approved/Rejected +- If approved, IT provisions accounts and equipment +- Manager schedules first day and assigns mentor +- System sends notifications at each stage + +### Step 1: Create Orchestration + +``` +Setup β†’ Flows β†’ New Flow β†’ Orchestration +Name: Employee_Onboarding +Object: Employee__c (custom object) +Trigger: Record Created, Status = 'Pending Onboarding' +``` + +### Step 2: Design Stages + +**Stage 1: HR Document Review** +``` +Stage Name: HR_Document_Review +Stage Description: HR verifies employee documentation +Run Mode: One at a Time (sequential) + +Step 1.1 (Interactive): +- Name: Review_Documents +- Assigned To: Queue "HR_Onboarding_Queue" +- Due Date: 2 days from start +- Screen Flow: HR_Document_Review_Screen +- Inputs: Employee__c.Id + +Step 1.2 (Background - Decision): +- If HR_Approved = true β†’ Next Stage +- If HR_Approved = false β†’ End + Send Rejection Email +``` + +**Stage 2: IT Provisioning** +``` +Stage Name: IT_Provisioning +Condition: Runs only if Stage 1 approved + +Step 2.1 (Interactive): +- Name: Assign_Equipment +- Assigned To: Queue "IT_Provisioning_Queue" +- Due Date: 3 days from stage start +- Screen Flow: IT_Equipment_Assignment +- Inputs: Employee__c.Id + +Step 2.2 (Background): +- Name: Create_AD_Account +- Autolaunched Flow: Create_Active_Directory_Account +- Inputs: Employee__c.Email, Employee__c.FirstName + +Step 2.3 (Background): +- Name: Send_IT_Confirmation +- Action: Send Email Template +- Recipient: Employee__c.Email +- Template: Welcome_Email +``` + +**Stage 3: Manager Setup** +``` +Stage Name: Manager_Setup +Depends On: Stage 2 complete + +Step 3.1 (Interactive): +- Name: Schedule_First_Day +- Assigned To: Employee__c.Manager__c +- Due Date: 1 day from stage start +- Screen Flow: Manager_Onboarding_Tasks + +Step 3.2 (Background): +- Name: Update_Status +- Record Update: Employee__c.Status = 'Onboarding Complete' +``` + +### Step 3: Implement Fault Paths (Summer '25) + +**Fault Path on IT Provisioning Failure**: +``` +If Step 2.2 (Create_AD_Account) fails: +β”œβ”€ Retry Step (1 attempt after 10 minutes) +β”œβ”€ If still fails: +β”‚ β”œβ”€ Send email to IT Manager with error details +β”‚ β”œβ”€ Create Task for manual provisioning +β”‚ └─ Assign Interactive Step to IT Manager for resolution +└─ Continue to Stage 3 (don't block entire process) +``` + +**Configuration**: +``` +Step 2.2: Create_AD_Account +β”œβ”€ Fault Path Enabled: true +β”œβ”€ Retry Attempts: 1 +β”œβ”€ Retry Delay: 10 minutes +└─ On Final Failure: + β”œβ”€ Create Task + β”‚ β”œβ”€ Subject: "Manual AD Account Creation Needed" + β”‚ β”œβ”€ Assigned To: IT_Manager_Queue + β”‚ └─ Priority: High + └─ Send Email Notification + β”œβ”€ Template: IT_Provisioning_Failure + └─ Recipients: IT Managers +``` + +## Interactive Steps vs Background Steps + +### Interactive Steps + +**Use for**: Actions requiring human judgment or input + +``` +Interactive Step Configuration: +β”œβ”€ Screen Flow: Define UI for user input +β”œβ”€ Assigned To: User, Queue, or Role +β”œβ”€ Due Date: Formula (TODAY() + 2 for 2 days) +β”œβ”€ Instructions: What user should do +β”œβ”€ Input Variables: Data passed to screen flow +└─ Output Variables: Data returned from user +``` + +**Example Screen Flow** (HR Review): +``` +Screen: Review Documents +β”œβ”€ Display: Employee Name, Position, Documents Uploaded +β”œβ”€ Input: Radio Button (Approve / Reject) +β”œβ”€ Input: Text Area (Comments - required if reject) +└─ Action: Save & Submit + +Output Variables: +- HR_Approved (Boolean) +- HR_Comments (Text) +``` + +### Background Steps + +**Use for**: Automated actions without user interaction + +``` +Background Step Types: +β”œβ”€ Autolaunched Flow: Call another flow +β”œβ”€ Apex Action: Invoke Apex method +β”œβ”€ Send Email: Email template or custom +β”œβ”€ Post to Chatter: Notify users +β”œβ”€ Create Records: DML operations +β”œβ”€ Update Records: Field updates +β”œβ”€ External Service: REST callout +└─ Wait: Pause for duration or until condition +``` + +## Advanced Patterns + +### Pattern 1: Conditional Stage Execution + +**Use Case**: Skip stages based on criteria + +``` +Stage 2: Manager Approval +Condition: Order_Total__c > 10000 + +Entry Criteria Formula: +{!$Record.Order_Total__c} > 10000 + +Result: +- If order <= $10,000 β†’ Skip Stage 2, go to Stage 3 +- If order > $10,000 β†’ Execute Stage 2 (manager approval required) +``` + +### Pattern 2: Parallel Steps Within Stage + +**Use Case**: Multiple teams work simultaneously + +``` +Stage 3: Parallel Provisioning +Run Mode: All at Once (parallel) + +Step 3.1 (Interactive): IT assigns laptop [Assigned to IT Queue] +Step 3.2 (Interactive): Facilities assigns desk [Assigned to Facilities Queue] +Step 3.3 (Interactive): HR orders business cards [Assigned to HR Queue] + +Stage completes when: All steps complete +``` + +### Pattern 3: Dynamic Assignment + +**Use Case**: Assign to different users based on record data + +``` +Step Assignment Formula: +IF( + {!$Record.Region__c} = 'West', + {!$User.WestCoastManager}, + IF( + {!$Record.Region__c} = 'East', + {!$User.EastCoastManager}, + {!$User.DefaultManager} + ) +) +``` + +### Pattern 4: SLA Monitoring + +**Use Case**: Escalate if step not completed on time + +``` +Step Due Date: {!$Flow.CurrentDate} + 2 (2 days) + +Scheduled Flow: Check_Overdue_Steps +- Schedule: Daily at 8 AM +- Query: OrchestrationWorkItem where DueDate < TODAY AND Status = 'In Progress' +- Action: Send escalation email to manager +``` + +**Monitor with SOQL**: +```apex +// Query overdue orchestration steps +List overdueItems = [ + SELECT Id, Label, StepDefinitionName, AssignedToId, + RelatedRecordId, DueDate, Status + FROM FlowOrchestrationWorkItem + WHERE DueDate < TODAY + AND Status = 'InProgress' + ORDER BY DueDate ASC +]; + +// Send escalation notifications +for (FlowOrchestrationWorkItem item : overdueItems) { + sendEscalationEmail(item); +} +``` + +## Monitoring and Reporting + +### FlowOrchestrationWorkItem Object + +**Query work items for reporting**: +```apex +// Active orchestrations +List activeItems = [ + SELECT Id, Label, StepDefinitionName, AssignedToId, + CreatedDate, LastModifiedDate, DueDate, + Status, RelatedRecordId + FROM FlowOrchestrationWorkItem + WHERE Status = 'InProgress' + ORDER BY DueDate ASC +]; + +// Calculate time spent in each step +for (FlowOrchestrationWorkItem item : activeItems) { + Long milliseconds = item.LastModifiedDate.getTime() - item.CreatedDate.getTime(); + Decimal hours = milliseconds / (1000.0 * 60 * 60); + System.debug('Step: ' + item.Label + ', Time: ' + hours + ' hours'); +} +``` + +### Dashboard Metrics + +**Key Metrics to Track**: +``` +1. Average Time per Stage + SELECT StepDefinitionName, + AVG(LastModifiedDate - CreatedDate) as AvgDuration + FROM FlowOrchestrationWorkItem + WHERE Status = 'Completed' + GROUP BY StepDefinitionName + +2. Completion Rate by Assignee + SELECT AssignedToId, + COUNT(CASE WHEN Status = 'Completed' THEN 1 END) as Completed, + COUNT(CASE WHEN DueDate < TODAY AND Status = 'InProgress' THEN 1 END) as Overdue + FROM FlowOrchestrationWorkItem + GROUP BY AssignedToId + +3. Bottleneck Identification + - Which steps take longest? + - Which steps have highest rejection/failure rate? + - Which assignees have most overdue items? +``` + +### Custom Dashboard Component + +```apex +public class OrchestrationMetrics { + @AuraEnabled(cacheable=true) + public static Map getMetrics() { + Map metrics = new Map(); + + // Total active orchestrations + Integer active = [SELECT COUNT() FROM FlowOrchestrationWorkItem WHERE Status = 'InProgress']; + metrics.put('active', active); + + // Overdue count + Integer overdue = [SELECT COUNT() FROM FlowOrchestrationWorkItem + WHERE Status = 'InProgress' AND DueDate < TODAY]; + metrics.put('overdue', overdue); + + // Average completion time (last 30 days) + AggregateResult[] avgTime = [ + SELECT AVG(LastModifiedDate - CreatedDate) avgDuration + FROM FlowOrchestrationWorkItem + WHERE Status = 'Completed' + AND CreatedDate = LAST_N_DAYS:30 + ]; + metrics.put('avgCompletionHours', (Decimal)avgTime[0].get('avgDuration') / (1000.0 * 60 * 60)); + + return metrics; + } +} +``` + +## Integration with Other Features + +### Pattern: Orchestration + Approval Process + +``` +Stage 2: Manager Approval +β”œβ”€ Step 2.1 (Interactive): Manager reviews +β”‚ └─ Screen Flow with Approve/Reject buttons +β”œβ”€ Background Automation: Update approval status +└─ If Approved: Proceed to Stage 3 + If Rejected: Send rejection email, End orchestration +``` + +### Pattern: Orchestration + Platform Events + +**Publish events at stage transitions**: +```apex +trigger OrchestrationStageTrigger on FlowOrchestrationStageInstance (after insert, after update) { + List events = new List(); + + for (FlowOrchestrationStageInstance stage : Trigger.new) { + if (stage.Status == 'Completed') { + events.add(new OrchestrationStageEvent__e( + OrchestrationId__c = stage.OrchestrationInstanceId, + StageName__c = stage.StepDefinitionName, + CompletedDate__c = System.now() + )); + } + } + + if (!events.isEmpty()) { + EventBus.publish(events); + } +} +``` + +**Subscribe externally**: +```javascript +// External system tracks orchestration progress +client.subscribe('/event/OrchestrationStageEvent__e', (message) => { + const { OrchestrationId__c, StageName__c } = message.data.payload; + console.log(`Stage ${StageName__c} completed for ${OrchestrationId__c}`); + + // Update external dashboard + updateOrchestrationStatus(OrchestrationId__c, StageName__c); +}); +``` + +### Pattern: Orchestration + Agentforce + +**AI agent handles certain steps**: +``` +Stage 2: Document Verification +β”œβ”€ Step 2.1 (Background): AI agent verifies documents +β”‚ └─ Agentforce Action: Verify_Document_Compliance +β”‚ - Uses Einstein OCR to extract text +β”‚ - Uses LLM to validate against compliance rules +β”‚ - Returns: Compliant (true/false) + Confidence score +β”œβ”€ Decision: If confidence < 90% β†’ Human review +└─ Step 2.2 (Interactive - Conditional): Human verifies (if AI uncertain) +``` + +## Best Practices + +### Design +- **Plan stages before building**: Sketch workflow on paper/whiteboard +- **One business process per orchestration**: Don't combine unrelated processes +- **Meaningful stage/step names**: Use business terminology, not technical jargon +- **Clear instructions**: Tell users exactly what to do in each step +- **Appropriate due dates**: Balance urgency with realistic timelines + +### Performance +- **Minimize steps per stage**: <10 steps per stage for maintainability +- **Avoid unnecessary waits**: Only pause when truly needed +- **Bulkify background automations**: Process multiple records efficiently +- **Use decision logic wisely**: Skip unnecessary stages with conditions +- **Monitor active orchestrations**: Archive completed ones regularly + +### Error Handling +- **Always implement fault paths** (Summer '25): Don't let failures block entire process +- **Retry transient errors**: Network issues, temporary API failures +- **Escalate permanent errors**: Create tasks for manual intervention +- **Log failures**: Track what went wrong for troubleshooting +- **Test error scenarios**: Intentionally trigger failures in sandbox + +### Security +- **Respect sharing rules**: Use "with sharing" in Apex called by orchestrations +- **Field-level security**: Ensure users have access to fields in screen flows +- **Queue membership**: Verify users in queues have necessary permissions +- **Sensitive data**: Mask or encrypt PII in screen flows and work items + +### User Experience +- **Mobile-friendly screens**: Many users work on mobile devices +- **Progress indicators**: Show users where they are in process +- **Clear next steps**: Always tell users what happens after they complete a step +- **Timely notifications**: Send reminders before due dates +- **Feedback on submission**: Confirm action was successful + +## Troubleshooting + +### Common Issues + +**Issue 1: Work items not appearing for users** +``` +Causes: +- User not in assigned queue +- User lacks permission to object +- Filter criteria on view excludes item + +Solution: +1. Check queue membership: Setup β†’ Queues +2. Verify object permissions: User profile/permission set +3. Review work item list view filters +``` + +**Issue 2: Background step failing silently** +``` +Causes: +- Apex error in called flow/action +- Required field missing +- Governor limit exceeded + +Solution: +1. Enable debug logs: Setup β†’ Debug Logs +2. Check Flow error emails: Setup β†’ Process Automation Settings +3. Implement fault path to catch and handle errors +``` + +**Issue 3: Orchestration not triggering** +``` +Causes: +- Trigger criteria not met +- Record not updated properly +- Orchestration inactive + +Solution: +1. Verify record meets entry criteria +2. Check orchestration activation status +3. Review audit trail for record updates +``` + +### Debug with Apex + +```apex +// Query orchestration details for debugging +public class OrchestrationDebugger { + public static void debugOrchestration(Id recordId) { + // Find orchestration instances for record + List instances = [ + SELECT Id, Label, Status, CreatedDate + FROM FlowOrchestrationInstance + WHERE RelatedRecordId = :recordId + ORDER BY CreatedDate DESC + ]; + + for (FlowOrchestrationInstance instance : instances) { + System.debug('Orchestration: ' + instance.Label); + System.debug('Status: ' + instance.Status); + + // Get work items + List items = [ + SELECT Id, Label, Status, AssignedToId, DueDate + FROM FlowOrchestrationWorkItem + WHERE OrchestrationInstanceId = :instance.Id + ORDER BY CreatedDate + ]; + + for (FlowOrchestrationWorkItem item : items) { + System.debug(' Step: ' + item.Label + ', Status: ' + item.Status); + } + } + } +} +``` + +## Pricing and Availability + +- **Editions**: Enterprise, Performance, Unlimited, Developer +- **Included Runs**: 600 orchestration runs/year (no charge) +- **Additional Runs**: Purchase in blocks for high-volume use +- **Permissions Required**: + - **Create/Edit**: Manage Flows permission + - **View**: View Orchestration in Automation App (Winter '26) + - **Approve Flows**: Approval Designer system permission (Winter '26) + +## Resources + +- **Flow Orchestrator Guide**: https://help.salesforce.com/s/articleView?id=platform.orchestrator_flow_orchestrator.htm +- **Trailhead**: "Flow Orchestration Basics" +- **Release Notes**: Summer '25 and Winter '26 for latest features +- **FlowOrchestrationWorkItem Reference**: Salesforce Object Reference documentation + +## Migration from Process Builder + +**Process Builder β†’ Flow Orchestrator**: +``` +Process Builder supports only simple automation +Flow Orchestrator adds: +- Multi-user coordination +- Interactive steps +- Stage-based organization +- Visual progress tracking +- Fault handling + +When to migrate: +- Process involves multiple users +- Need stage-based workflow +- Want user interface for steps +- Require better error handling +``` + +Flow Orchestrator transforms complex, cross-functional business processes into visual, manageable workflows that scale across your organization. diff --git a/skills/hyperforce-2025.md b/skills/hyperforce-2025.md new file mode 100644 index 0000000..c496395 --- /dev/null +++ b/skills/hyperforce-2025.md @@ -0,0 +1,568 @@ +--- +name: hyperforce-2025 +description: Salesforce Hyperforce public cloud infrastructure and architecture (2025) +--- + +## 🚨 CRITICAL GUIDELINES + +### Windows File Path Requirements + +**MANDATORY: Always Use Backslashes on Windows for File Paths** + +When using Edit or Write tools on Windows, you MUST use backslashes (`\`) in file paths, NOT forward slashes (`/`). + +**Examples:** +- ❌ WRONG: `D:/repos/project/file.tsx` +- βœ… CORRECT: `D:\repos\project\file.tsx` + +This applies to: +- Edit tool file_path parameter +- Write tool file_path parameter +- All file operations on Windows systems + + +### Documentation Guidelines + +**NEVER create new documentation files unless explicitly requested by the user.** + +- **Priority**: Update existing README.md files rather than creating new documentation +- **Repository cleanliness**: Keep repository root clean - only README.md unless user requests otherwise +- **Style**: Documentation should be concise, direct, and professional - avoid AI-generated tone +- **User preference**: Only create additional .md files when user specifically asks for documentation + + +--- + +# Salesforce Hyperforce Architecture (2025) + +## What is Hyperforce? + +Hyperforce is Salesforce's next-generation infrastructure architecture built on public cloud platforms (AWS, Azure, Google Cloud). It represents a complete re-architecture of Salesforce from data center-based infrastructure to cloud-native, containerized microservices. + +**Key Innovation**: Infrastructure as code that can be deployed anywhere, giving customers choice, control, and data residency compliance. + +## Five Architectural Principles + +### 1. Immutable Infrastructure + +**Traditional**: Patch and update existing servers +**Hyperforce**: Destroy and recreate servers with each deployment + +``` +Old Architecture: +Server β†’ Patch β†’ Patch β†’ Patch β†’ Configuration Drift + +Hyperforce: +Container Image v1 β†’ Deploy +New Code β†’ Build Container Image v2 β†’ Replace v1 with v2 +Result: Every deployment is identical, reproducible +``` + +**Benefits**: +- No configuration drift +- Consistent environments (dev = prod) +- Fast rollback (redeploy previous image) +- Security patches applied immediately + +### 2. Multi-Availability Zone Design + +**Architecture**: +``` +Region: US-East (Virginia) +β”œβ”€ Availability Zone A (Data Center 1) +β”‚ β”œβ”€ App Servers (Kubernetes pods) +β”‚ β”œβ”€ Database Primary +β”‚ └─ Load Balancer +β”œβ”€ Availability Zone B (Data Center 2) +β”‚ β”œβ”€ App Servers (Kubernetes pods) +β”‚ β”œβ”€ Database Replica +β”‚ └─ Load Balancer +└─ Availability Zone C (Data Center 3) + β”œβ”€ App Servers (Kubernetes pods) + β”œβ”€ Database Replica + └─ Load Balancer + +Traffic Distribution: Round-robin across all AZs +Failure Handling: If AZ fails, traffic routes to remaining AZs +RTO (Recovery Time Objective): <5 minutes +RPO (Recovery Point Objective): <30 seconds +``` + +**Impact on Developers**: +- Higher availability (99.95%+ SLA) +- Transparent failover (no code changes) +- Regional data residency guaranteed + +### 3. Zero Trust Security + +**Traditional**: Perimeter security (firewall protects everything inside) +**Hyperforce**: No implicit trust - verify everything, always + +``` +Zero Trust Model: +β”œβ”€ Identity Verification (MFA required for all users by 2025) +β”œβ”€ Device Trust (managed devices only) +β”œβ”€ Network Segmentation (micro-segmentation between services) +β”œβ”€ Least Privilege Access (minimal permissions by default) +β”œβ”€ Continuous Monitoring (real-time threat detection) +└─ Encryption Everywhere (TLS 1.3, data at rest encryption) +``` + +**Code Impact**: +```apex +// OLD: Assume internal traffic is safe +public without sharing class InternalService { + // No auth checks - trusted network +} + +// HYPERFORCE: Always verify, never trust +public with sharing class InternalService { + // Always enforce sharing rules + // Always validate session + // Always check field-level security + + public List getAccounts() { + // WITH SECURITY_ENFORCED prevents data leaks + return [SELECT Id, Name FROM Account WITH SECURITY_ENFORCED]; + } +} +``` + +**2025 Requirements**: +- **MFA Mandatory**: All users must enable MFA +- **Session Security**: Shorter session timeouts, IP restrictions +- **API Security**: JWT with short expiration (15 minutes) + +### 4. Infrastructure as Code (IaC) + +**Everything defined as code, version-controlled**: + +```yaml +# Hyperforce deployment manifest (conceptual) +apiVersion: hyperforce.salesforce.com/v1 +kind: SalesforceOrg +metadata: + name: production-org + region: aws-us-east-1 +spec: + edition: enterprise + features: + - agentforce + - dataCloud + - einstein + compute: + pods: 50 + autoScaling: + min: 10 + max: 100 + targetCPU: 70% + storage: + size: 500GB + replication: 3 + backup: + frequency: hourly + retention: 30days + networking: + privateLink: enabled + ipWhitelist: + - 203.0.113.0/24 +``` + +**Benefits for Developers**: +- **Reproducible**: Recreate exact environment anytime +- **Version Controlled**: Track all infrastructure changes in Git +- **Testable**: Validate infrastructure before deployment +- **Automated**: No manual configuration, eliminates human error + +### 5. Clean Slate (No Legacy Constraints) + +**Hyperforce rebuilt from scratch**: +- Modern Kubernetes orchestration +- Cloud-native services (managed databases, object storage) +- API-first design (everything accessible via API) +- Microservices architecture (independent scaling) +- No legacy code or technical debt + +## Public Cloud Integration + +### AWS Hyperforce Architecture + +``` +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ AWS Region (us-east-1) β”‚ +β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ +β”‚ VPC (Virtual Private Cloud) β”‚ +β”‚ β”œβ”€ Public Subnets (3 AZs) β”‚ +β”‚ β”‚ └─ Application Load Balancer (ALB) β”‚ +β”‚ β”œβ”€ Private Subnets (3 AZs) β”‚ +β”‚ β”‚ β”œβ”€ EKS Cluster (Kubernetes) β”‚ +β”‚ β”‚ β”‚ β”œβ”€ Salesforce App Pods (autoscaling) β”‚ +β”‚ β”‚ β”‚ β”œβ”€ Metadata Service Pods β”‚ +β”‚ β”‚ β”‚ β”œβ”€ API Gateway Pods β”‚ +β”‚ β”‚ β”‚ └─ Background Job Pods (Batch, Scheduled) β”‚ +β”‚ β”‚ β”œβ”€ RDS Aurora PostgreSQL (multi-AZ) β”‚ +β”‚ β”‚ β”œβ”€ ElastiCache Redis (session storage) β”‚ +β”‚ β”‚ └─ S3 Buckets (attachments, documents) β”‚ +β”‚ └─ Database Subnets (3 AZs) β”‚ +β”‚ └─ Aurora Database Cluster β”‚ +β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ +β”‚ Additional Services β”‚ +β”‚ β”œβ”€ CloudWatch (monitoring, logs) β”‚ +β”‚ β”œβ”€ CloudTrail (audit logs) β”‚ +β”‚ β”œβ”€ AWS Shield (DDoS protection) β”‚ +β”‚ β”œβ”€ AWS WAF (web application firewall) β”‚ +β”‚ β”œβ”€ KMS (encryption key management) β”‚ +β”‚ └─ PrivateLink (secure connectivity) β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +``` + +**AWS Services Used**: +- **Compute**: EKS (Elastic Kubernetes Service) +- **Database**: Aurora PostgreSQL (multi-master) +- **Storage**: S3 (object storage), EBS (block storage) +- **Networking**: VPC, ALB, Route 53, CloudFront CDN +- **Security**: IAM, KMS, Shield, WAF, Certificate Manager + +### Azure Hyperforce Architecture + +``` +Azure Region (East US) +β”œβ”€ Virtual Network (VNet) +β”‚ β”œβ”€ AKS (Azure Kubernetes Service) +β”‚ β”‚ └─ Salesforce workloads +β”‚ β”œβ”€ Azure Database for PostgreSQL (Hyperscale) +β”‚ β”œβ”€ Azure Cache for Redis +β”‚ └─ Azure Blob Storage +β”œβ”€ Azure Front Door (CDN + Load Balancer) +β”œβ”€ Azure Monitor (logging, metrics) +β”œβ”€ Azure Active Directory (identity) +└─ Azure Key Vault (secrets, encryption) +``` + +### Google Cloud Hyperforce Architecture + +``` +GCP Region (us-central1) +β”œβ”€ VPC Network +β”‚ β”œβ”€ GKE (Google Kubernetes Engine) +β”‚ β”œβ”€ Cloud SQL (PostgreSQL) +β”‚ β”œβ”€ Memorystore (Redis) +β”‚ └─ Cloud Storage (GCS) +β”œβ”€ Cloud Load Balancing +β”œβ”€ Cloud Armor (DDoS protection) +β”œβ”€ Cloud Monitoring (Stackdriver) +└─ Cloud KMS (encryption) +``` + +## Data Residency and Compliance + +### Geographic Regions (2025) + +**Available Hyperforce Regions**: +``` +Americas: +β”œβ”€ US East (Virginia) - AWS, Azure +β”œβ”€ US West (Oregon) - AWS +β”œβ”€ US Central (Iowa) - GCP +β”œβ”€ Canada (Toronto) - AWS +└─ Brazil (SΓ£o Paulo) - AWS + +Europe: +β”œβ”€ UK (London) - AWS +β”œβ”€ Germany (Frankfurt) - AWS, Azure +β”œβ”€ France (Paris) - AWS +β”œβ”€ Ireland (Dublin) - AWS +└─ Switzerland (Zurich) - AWS + +Asia Pacific: +β”œβ”€ Japan (Tokyo) - AWS +β”œβ”€ Australia (Sydney) - AWS +β”œβ”€ Singapore - AWS +β”œβ”€ India (Mumbai) - AWS +└─ South Korea (Seoul) - AWS + +Middle East: +└─ UAE (Dubai) - AWS +``` + +### Data Residency Guarantees + +**What stays in region**: +- All customer data (records, attachments, metadata) +- Database backups +- Transaction logs +- Audit logs + +**What may leave region**: +- Telemetry data (anonymized performance metrics) +- Security threat intelligence +- Platform health monitoring + +**Code Implication**: +```apex +// Data residency automatically enforced +// No code changes needed - Hyperforce handles it + +// Example: File stored in org's region +ContentVersion cv = new ContentVersion( + Title = 'Customer Contract', + PathOnClient = 'contract.pdf', + VersionData = Blob.valueOf('contract data') +); +insert cv; + +// File automatically stored in: +// - AWS S3 in org's region +// - Encrypted at rest (AES-256) +// - Replicated across 3 AZs in region +// - Never leaves region boundary +``` + +### Compliance Certifications + +**Hyperforce maintains**: +- **SOC 2 Type II**: Security, availability, confidentiality +- **ISO 27001**: Information security management +- **GDPR**: EU data protection compliance +- **HIPAA**: Healthcare data protection (BAA available) +- **PCI DSS**: Payment card data security +- **FedRAMP**: US government cloud security (select regions) + +## Performance Improvements + +### Latency Reduction + +**Old Architecture** (data center-based): +``` +User (Germany) β†’ Transatlantic cable β†’ US Data Center β†’ Response +Latency: 150-200ms +``` + +**Hyperforce**: +``` +User (Germany) β†’ Frankfurt Hyperforce Region β†’ Response +Latency: 10-30ms + +Result: 5-10x faster for regional users +``` + +### Auto-Scaling + +**Traditional**: Fixed capacity, must provision for peak load +**Hyperforce**: Dynamic scaling based on demand + +``` +Business Hours (9 AM - 5 PM): +β”œβ”€ High user load +β”œβ”€ Kubernetes scales up pods: 50 β†’ 150 +└─ Response times maintained + +Off Hours (6 PM - 8 AM): +β”œβ”€ Low user load +β”œβ”€ Kubernetes scales down pods: 150 β†’ 30 +└─ Cost savings (pay for what you use) + +Black Friday (peak event): +β”œβ”€ Extreme load +β”œβ”€ Kubernetes scales to maximum: 30 β†’ 500 pods in minutes +└─ No downtime, no performance degradation +``` + +**Governor Limits - No Change**: +```apex +// Hyperforce does NOT change governor limits +// Limits remain the same as classic Salesforce: +// - 100 SOQL queries per transaction +// - 150 DML statements +// - 6 MB heap size (sync), 12 MB (async) + +// But: Infrastructure scales to handle more concurrent users +``` + +## Migration to Hyperforce + +### Migration Process + +**Salesforce handles migration** (no customer action required): + +``` +Phase 1: Assessment (Salesforce internal) +β”œβ”€ Analyze org size, customizations +β”œβ”€ Identify any incompatible features +└─ Plan migration window + +Phase 2: Pre-Migration (Customer notified) +β”œβ”€ Salesforce sends notification (90 days notice) +β”œβ”€ Customer tests in sandbox (migrated first) +└─ Customer validates functionality + +Phase 3: Migration (Weekend maintenance window) +β”œβ”€ Backup all data +β”œβ”€ Replicate data to Hyperforce +β”œβ”€ Cutover DNS (redirect traffic) +└─ Validate migration success + +Phase 4: Post-Migration +β”œβ”€ Monitor performance +β”œβ”€ Support customer issues +└─ Decommission old infrastructure + +Downtime: Typically <2 hours +``` + +### What Changes for Developers? + +**No Code Changes Required**: +```apex +// Your Apex code works identically on Hyperforce +public class MyController { + public List getAccounts() { + return [SELECT Id, Name FROM Account LIMIT 10]; + } +} + +// No changes needed +// Same APIs, same limits, same behavior +``` + +**Potential Performance Improvements**: +- Faster API responses (lower latency) +- Better handling of concurrent users +- Improved batch job processing (parallel execution) + +**Backward Compatibility**: 100% compatible with existing code + +### Testing Pre-Migration + +**Use Sandbox Migration**: +``` +1. Salesforce migrates your sandbox first +2. Test all critical functionality: + β”œβ”€ Custom Apex classes + β”œβ”€ Triggers and workflows + β”œβ”€ Integrations (API callouts) + β”œβ”€ Lightning components + └─ Reports and dashboards + +3. Validate performance: + β”œβ”€ Run load tests + β”œβ”€ Check API response times + └─ Verify batch jobs complete + +4. Report any issues to Salesforce +5. Production migration scheduled after sandbox validated +``` + +## Hyperforce for Developers + +### Enhanced APIs + +**Hyperforce exposes infrastructure APIs**: + +```apex +// Query org's Hyperforce region (API 62.0+) +Organization org = [SELECT Id, InstanceName, InfrastructureRegion__c FROM Organization LIMIT 1]; +System.debug('Region: ' + org.InfrastructureRegion__c); // 'aws-us-east-1' + +// Check if org is on Hyperforce +System.debug('Is Hyperforce: ' + org.IsHyperforce__c); // true +``` + +### Private Connectivity + +**AWS PrivateLink / Azure Private Link**: +``` +Traditional: Salesforce API β†’ Public Internet β†’ Your API +Security: TLS encryption, but still public internet + +Hyperforce PrivateLink: Salesforce API β†’ Private Network β†’ Your API +Security: Never touches public internet, lower latency + +Setup: +1. Create VPC Endpoint (AWS) or Private Endpoint (Azure) +2. Salesforce provides service endpoint name +3. Configure Named Credential in Salesforce with private endpoint +4. API calls route over private network +``` + +**Configuration**: +```apex +// Named Credential uses PrivateLink endpoint +// Setup β†’ Named Credentials β†’ External API (PrivateLink) +// URL: https://api.internal.example.com (private endpoint) + +// Apex callout +HttpRequest req = new HttpRequest(); +req.setEndpoint('callout:ExternalAPIPrivateLink/data'); +req.setMethod('GET'); + +Http http = new Http(); +HttpResponse res = http.send(req); + +// Callout never leaves private network +// Lower latency, higher security +``` + +### Monitoring + +**CloudWatch / Azure Monitor Integration**: +``` +Salesforce publishes metrics to your cloud account: +β”œβ”€ API request volume +β”œβ”€ API response times +β”œβ”€ Error rates +β”œβ”€ Governor limit usage +└─ Batch job completion times + +Benefits: +- Unified monitoring (Salesforce + your apps) +- Custom alerting (CloudWatch Alarms) +- Cost attribution (AWS Cost Explorer) +``` + +## Best Practices for Hyperforce + +### Security +- **Enable MFA**: Required for all users in 2025 +- **Use WITH SECURITY_ENFORCED**: Field-level security in SOQL +- **Implement IP whitelisting**: Restrict access to known IPs +- **Monitor audit logs**: Setup β†’ Event Monitoring +- **Rotate credentials**: API keys, certificates, passwords regularly + +### Performance +- **Leverage caching**: Platform Cache for frequently accessed data +- **Optimize queries**: Use indexed fields, selective queries +- **Async processing**: Use @future, Queueable for non-critical work +- **Bulkification**: Always design for 200+ records +- **Monitor limits**: Use Limits class to track governor limit usage + +### Data Residency +- **Understand requirements**: Know your compliance obligations +- **Choose correct region**: Select region meeting your needs +- **Validate configurations**: Ensure integrations respect boundaries +- **Document decisions**: Maintain records of data residency choices + +### Cost Optimization +- **Right-size storage**: Archive old data, delete unnecessary records +- **Optimize API calls**: Batch API calls, use composite APIs +- **Schedule batch jobs efficiently**: Run during off-peak hours +- **Monitor usage**: Track API calls, storage, compute usage + +## Resources + +- **Hyperforce Trust Site**: https://trust.salesforce.com/en/infrastructure/hyperforce/ +- **Hyperforce FAQ**: Salesforce Help documentation +- **Available Regions**: https://help.salesforce.com/s/articleView?id=sf.getstart_domain_overview.htm +- **Migration Guide**: Provided by Salesforce 90 days before migration +- **Trust & Compliance**: https://compliance.salesforce.com/ + +## Future Roadmap (2025+) + +**Expected Enhancements**: +- More regions (Africa, additional Asia Pacific) +- Bring Your Own Cloud (BYOC) - use your own AWS/Azure account +- Multi-region active-active (write to multiple regions simultaneously) +- Edge computing (Salesforce at CDN edge locations) +- Kubernetes cluster API (direct pod management for enterprises) + +Hyperforce represents Salesforce's commitment to modern, cloud-native infrastructure that scales globally while meeting the most stringent compliance and performance requirements. diff --git a/skills/lightning-2025-features.md b/skills/lightning-2025-features.md new file mode 100644 index 0000000..04dc999 --- /dev/null +++ b/skills/lightning-2025-features.md @@ -0,0 +1,358 @@ +--- +name: lightning-2025-features +description: Salesforce Lightning Web Components Winter '26 and 2025 features +--- + +## 🚨 CRITICAL GUIDELINES + +### Windows File Path Requirements + +**MANDATORY: Always Use Backslashes on Windows for File Paths** + +When using Edit or Write tools on Windows, you MUST use backslashes (`\`) in file paths, NOT forward slashes (`/`). + +**Examples:** +- ❌ WRONG: `D:/repos/project/file.tsx` +- βœ… CORRECT: `D:\repos\project\file.tsx` + +This applies to: +- Edit tool file_path parameter +- Write tool file_path parameter +- All file operations on Windows systems + + +### Documentation Guidelines + +**NEVER create new documentation files unless explicitly requested by the user.** + +- **Priority**: Update existing README.md files rather than creating new documentation +- **Repository cleanliness**: Keep repository root clean - only README.md unless user requests otherwise +- **Style**: Documentation should be concise, direct, and professional - avoid AI-generated tone +- **User preference**: Only create additional .md files when user specifically asks for documentation + + +--- + +# Lightning Web Components 2025 Features + +## lightning/graphql Module (Winter '26) + +New module replaces deprecated `lightning/uiGraphQLApi`: + +### Migration + +```javascript +// ❌ Old (deprecated) +import { gql, graphql } from 'lightning/uiGraphQLApi'; + +// βœ… New (Winter '26) +import { gql, graphql } from 'lightning/graphql'; + +export default class MyComponent extends LightningElement { + @wire(graphql, { + query: gql` + query getAccount($id: ID!) { + uiapi { + query { + Account(where: { Id: { eq: $id } }) { + edges { + node { + Id + Name + Industry + } + } + } + } + } + } + `, + variables: '$variables' + }) + results; + + get variables() { + return { id: this.recordId }; + } +} +``` + +### Benefits + +- Improved performance +- Better error handling +- Enhanced type safety +- Future-proof API + +## Local Development (sf lightning dev component) + +Run LWC components locally without deploying: + +```bash +# Start local dev server +sf lightning dev component + +# Opens browser at http://localhost:3333 +# Live reload on file changes +# No deployment needed +# Faster development cycle + +# Specify component +sf lightning dev component -n myComponent + +# Specify target org +sf lightning dev component -o myOrg@example.com +``` + +**Benefits:** +- Instant feedback (no deployment wait) +- Debug in real browser DevTools +- Hot module replacement +- Work offline + +## Platform Module Access in Component Preview + +Access platform modules in single component preview: + +```javascript +// Works in local preview now +import { getRecord } from 'lightning/uiRecordApi'; +import { ShowToastEvent } from 'lightning/platformShowToastEvent'; +import { NavigationMixin } from 'lightning/navigation'; + +// Previously required full org deployment +// Now works in sf lightning dev component +``` + +## Agentforce Targets (Winter '26) + +New LWC targets for AI agents: + +```xml + + + + lightning__AgentforceInput + + + lightning__AgentforceOutput + +``` + +```javascript +// agentInputComponent.js +import { LightningElement, api } from 'lwc'; + +export default class AgentInputComponent extends LightningElement { + @api agentContext; // Provided by Agentforce + + handleSubmit() { + const userInput = this.template.querySelector('input').value; + // Send to Agentforce + this.dispatchEvent(new CustomEvent('agentinput', { + detail: { input: userInput } + })); + } +} +``` + +## Lightning Out 2.0 (GA Winter '26) + +Re-imagined embedding with web components: + +### Traditional Lightning Out (Legacy) + +```html + + +
+``` + +### Lightning Out 2.0 (Modern) + +```html + + + + + + + + + +``` + +**Benefits:** +- 50-70% smaller bundle size +- Faster load times +- Standards-based (no proprietary framework) +- Better browser compatibility +- Simplified integration + +## SLDS 2.0 with Dark Mode (GA Winter '26) + +Salesforce Lightning Design System 2.0: + +```css +/* Dark mode support in custom themes */ +:host([data-theme="dark"]) { + --lwc-colorBackground: #16325c; + --lwc-colorTextPrimary: #ffffff; + --lwc-brandPrimary: #1589ee; +} + +/* Light mode */ +:host([data-theme="light"]) { + --lwc-colorBackground: #ffffff; + --lwc-colorTextPrimary: #181818; + --lwc-brandPrimary: #0176d3; +} +``` + +```javascript +// Toggle dark mode +export default class ThemeToggle extends LightningElement { + handleThemeChange(event) { + const theme = event.target.checked ? 'dark' : 'light'; + this.template.host.setAttribute('data-theme', theme); + } +} +``` + +### SLDS Linter with Fix Option + +```bash +# Install SLDS linter +npm install -D @salesforce-ux/slds-linter + +# Lint with auto-fix +npx slds-linter --fix src/ + +# CI/CD integration +npx slds-linter src/ --format json > slds-report.json +``` + +## Unified Testing APIs (Winter '26) + +Test Discovery and Test Runner APIs unify Apex and Flow testing: + +```apex +// Discover all tests +Test.DiscoveryResult discovery = Test.discoverTests(); + +// Get Apex tests +List apexTests = discovery.getApexTests(); + +// Get Flow tests +List flowTests = discovery.getFlowTests(); + +// Run all tests from single location +Test.RunResult result = Test.runTests(discovery); + +// Check results +System.debug('Apex passed: ' + result.getApexTestsPassed()); +System.debug('Flow passed: ' + result.getFlowTestsPassed()); +``` + +**Benefits:** +- Unified test execution +- Single test report +- Simplified CI/CD +- Better test orchestration + +## Lightning Web Security Enhancements + +New security protections with API distortions: + +```javascript +// Additional secure protections automatically applied +export default class SecureComponent extends LightningElement { + connectedCallback() { + // Web APIs now include security distortions + // ESLint rules validate distortion compliance + + // Example: Secure window access + const secureWindow = window; // LWS-secured reference + } +} +``` + +### ESLint Rules for Security + +```json +// .eslintrc.json +{ + "extends": ["@salesforce/eslint-config-lwc/recommended"], + "rules": { + "@lwc/lwc/no-inner-html": "error", + "@lwc/lwc/no-document-query": "error", + "@salesforce/lwc-security/no-unsafe-references": "error" + } +} +``` + +## Practical Migration Examples + +### GraphQL Module Update + +```javascript +// Before (Winter '25) +import { gql, graphql } from 'lightning/uiGraphQLApi'; + +@wire(graphql, { query: gql`...` }) +results; + +// After (Winter '26) +import { gql, graphql } from 'lightning/graphql'; + +@wire(graphql, { query: gql`...` }) +results; +``` + +### Local Development Workflow + +```bash +# Old workflow (deploy every change) +sf project deploy start +# Wait 30-60 seconds +# Test in org +# Repeat... + +# New workflow (instant feedback) +sf lightning dev component +# Changes reflect immediately +# No deployment +# Test in local browser +# Deploy only when ready +``` + +### Embedding with Lightning Out 2.0 + +```html + + + + + + + +``` + +## Resources + +- [Lightning Web Components Dev Guide](https://developer.salesforce.com/docs/platform/lwc/guide) +- [Winter '26 Release Notes](https://help.salesforce.com/s/articleView?id=release-notes.salesforce_release_notes.htm) +- [SLDS 2.0](https://www.lightningdesignsystem.com) +- [Lightning Out 2.0](https://developer.salesforce.com/docs/platform/lwc/guide/use-lightning-out.html)