When Automation Lies: Using AI to Diagnose and Fix Salesforce Trigger Conflicts
2026-02-25
A hands-on walkthrough: seeding a broken Salesforce org, letting Claude Code analyze the mess, and watching it push a fix β all from the CLI.
Prerequisites
Before following along, you’ll need three things set up. This section is brief β the screencast covers each step in detail.
1. A Trailhead Playground
Sign up for a free Salesforce developer account at trailhead.salesforce.com if you don’t already have one. From your Trailhead home page, create a new Trailhead Playground β this gives you a fresh, isolated Salesforce org you can safely break things in.
Make note of your playground’s username and login URL (something like https://curious-bear-abc123.trailblaze.lightning.force.com).
2. Salesforce CLI
Install the Salesforce CLI via npm:
npm install -g @salesforce/cli
Verify it’s working:
sf --version
3. Initialize a Salesforce DX Project
Before deploying any metadata, you need a Salesforce DX project in your working directory. This creates the sfdx-project.json file the CLI requires:
sf project generate --name casecounter
cd casecounter
All subsequent work happens inside this directory.
4. Authenticate to Your Playground
Connect the CLI to your Trailhead Playground:
sf org login web --alias trailhead
This opens a browser. Log in with your Trailhead Playground credentials. Once authenticated, confirm it worked:
sf org display --target-org trailhead
You should see your org’s details. You’re ready to go.
The Problem Nobody Warns You About
You’ve been there. A user creates a case. You close it. You pull up the Account and the open case count is wrong. You open another case, close it β still wrong. You check the Flow. Looks fine. You check the trigger. Also looks fine. But together, they’re quietly destroying each other’s work.
This kind of automation conflict is one of the most common and hardest-to-diagnose problems in mature Salesforce orgs. There’s no error. No log entry screaming at you. Just a field that’s silently off by one, or two, or sometimes zero β which is almost worse, because you can never tell when to trust it.
In this post I’m going to walk through a complete end-to-end scenario: deliberately creating this broken state in a Trailhead Playground, then using Claude Code to diagnose the conflict through static analysis of the org’s metadata, and finally watching it deploy a proper fix and verify the result.
There are two Claude Code sessions involved β one to set up the problem, one to solve it. The solving session doesn’t know what was planted. It just knows something’s wrong.
The Scenario: Open Case Count Gone Wrong
Our target field is Open_Case_Count__c β a custom Number field on Account that’s supposed to track how many open Cases the Account currently has. Simple enough.
The problem is that three different pieces of automation are all trying to maintain it, each written by a different developer at a different time, each perfectly reasonable in isolation:
- A Record-Triggered Flow on Case, firing on create and update. It reads the current
Open_Case_Count__cvalue and adjusts it β adding 1 on create, subtracting 1 on close, adding 1 on reopen. CaseInsertTriggerβ anafter insertApex trigger on Case that incrementsOpen_Case_Count__con the parent Account by 1 for each new Case.CaseStatusTriggerβ anafter updateApex trigger on Case that decrements the count when a Case is closed and increments when a closed Case is reopened.
Each one makes sense on its own. Together, they’re a disaster.
On case insert: Both CaseInsertTrigger and the Flow fire. The trigger increments the field by 1. The Flow also reads the current value and adds 1. The count goes up by 2 instead of 1. Create three Cases and you’re already off by 3.
On case close: CaseStatusTrigger decrements the field by 1. The Flow also fires and decrements by 1. Double-decrement. Reopen a Case? Double-increment.
The underlying problem is redundant incremental updates. All three automations use read-then-modify arithmetic β stateful, additive logic that assumes no one else is touching the same field in the same transaction. Since Salesforce fires triggers and Flows in the same transaction with no coordination between them, every Case operation applies its adjustment twice.
Phase 1: Seeding the Broken State
Before we can diagnose anything, we need to create the problem in the Trailhead Playground. This is what I’m calling a fixture β a deployable set of metadata that establishes a known, reproducible broken state.
Rather than manually clicking through Setup, we use Claude Code to generate and deploy the entire fixture from a single prompt. This makes it version-controlled, repeatable, and self-documenting.
The full Prompt 1 is at the bottom of this post. Paste it into a new Claude Code session in a local working directory with the Salesforce CLI available.
Claude Code creates a fixtures/ directory containing all the metadata, deploys it to your playground using sf project deploy start, then runs a verification script that confirms the broken state is active.
What Gets Deployed
The custom field: Open_Case_Count__c on Account β a plain Number field. Critically, this is not a Roll-Up Summary field. It’s custom-maintained by code, which is exactly what enables the conflict. The fixture also deploys a Permission Set granting field-level security and adds the field to the Account page layout so it’s visible in the UI.
The Flow β Update_Account_Open_Case_Count: A Record-Triggered Flow on Case, after-save, firing on create and update. It reads the parent Account’s current Open_Case_Count__c, adds 1 on create, subtracts 1 on close, adds 1 on reopen, and writes the result back. Looks totally reasonable β simple arithmetic, easy to follow.
CaseInsertTrigger: Fires after insert on Case. The handler groups new Cases by AccountId and increments Open_Case_Count__c by 1 for each. Simple, efficient, correct β in isolation.
CaseStatusTrigger: Fires after update on Case. The handler detects IsClosed flipping false->true (decrement) or true->false (increment) and updates the Account. Also reasonable.
Confirming It’s Broken
Claude Code runs verify_broken.apex β an anonymous Apex script that creates a test Account, inserts 3 open Cases one at a time (not as a bulk insert), closes 1, then checks whether Open_Case_Count__c equals 2.
The one-at-a-time insert is important: in a bulk insert, the trigger fires once for all records but the Flow may batch its interviews, partially offsetting the double-counting. Individual inserts force each Case to independently trigger both automations, compounding the error reliably.
The expected output is FAIL. That’s not a mistake β that’s the fixture working correctly. We’ve successfully manufactured a real problem.
Phase 2: Handing It to Claude Code
Now we open a fresh Claude Code session with no context from Phase 1. Just the diagnosis prompt.
The full Prompt 2 is at the bottom of this post.
The prompt tells Claude Code only that Open_Case_Count__c on Account is returning incorrect values and asks it to figure out why and fix it.
Step 1 β Pull the Metadata
Claude Code runs:
sf project retrieve start \
--metadata "ApexClass,ApexTrigger,Flow" \
--target-org trailhead \
--output-dir retrieved/
This dumps all Apex classes, triggers, and Flow metadata to disk as local files β ready for static analysis without any further org interaction.
Step 2 β Static Analysis
Claude Code reads through the retrieved metadata looking for everything touching the Case object and its parent Account. It finds:
CaseInsertTriggerβ after insert, writes to AccountCaseStatusTriggerβ after update, writes to AccountUpdate_Account_Open_Case_CountFlow β after-save on Case, also writes to Account
Then it identifies the conflict: two triggers and one Flow, all using increment/decrement arithmetic on the same field in the same transaction. Each Case operation fires both a trigger and the Flow, and both independently read the current value, adjust it, and write it back β doubling every change.
The diagnosis: redundant incremental updates on a shared field, with no coordination between automations.
Step 3 β The Fix
The canonical Salesforce solution is to pick one authoritative approach and eliminate the others. Claude Code’s recommendation:
- Deactivate the Flow β remove it from the equation entirely
- Consolidate the two triggers into one β a single
CaseTriggercovering all events - Use a proper trigger handler class β explicit methods per event, single point of control
- Use the aggregate query approach throughout β idempotent, can’t double-count, same philosophy the Flow was attempting but now without a competitor overwriting it
The consolidated trigger:
trigger CaseTrigger on Case (after insert, after update, after undelete, after delete) {
if (Trigger.isAfter) {
if (Trigger.isInsert || Trigger.isUndelete) {
CaseTriggerHandler.onAfterInsert(Trigger.new);
}
if (Trigger.isUpdate) {
CaseTriggerHandler.onAfterUpdate(Trigger.new, Trigger.oldMap);
}
if (Trigger.isDelete) {
CaseTriggerHandler.onAfterDelete(Trigger.old);
}
}
}
The handler recalculates Open_Case_Count__c with a fresh aggregate query whenever Cases change β no arithmetic, no state assumptions, no race conditions.
Step 4 β Deploy and Verify
sf project deploy start \
--source-dir fix/force-app \
--target-org trailhead \
--test-level RunLocalTests
Tests pass. Then Claude Code runs verify_fixed.apex:
sf apex run --file fixtures/verify_fixed.apex --target-org trailhead
Output: PASS: Open_Case_Count__c = 2 (expected 2)
Why This Pattern Matters
The specific conflict here β a Flow and multiple triggers on the same object β shows up in nearly every org that’s been around for more than a couple of years. Each piece was added by someone with good intentions. Nobody owned the full picture.
What’s interesting about the Claude Code approach is that it didn’t need runtime instrumentation, debug logs, or deep knowledge of the specific business logic. It pulled the metadata, read the code as text, and reasoned about execution order and conflicting field writes. That’s the same thing a good Salesforce architect would do in a code review β except it took about 90 seconds.
The fixture pattern is worth carrying forward. Having a deployable, version-controlled broken state that can be stood up in any fresh Trailhead Playground makes it easy to reproduce, demonstrate, and teach these scenarios. It’s the Salesforce equivalent of a failing unit test β and just like a failing test, its only job before the fix is to fail reliably.
Appendix A: The Two Claude Code Prompts
Paste these into Claude Code sessions in order. Each should be run in a fresh session in a local working directory where you have the Salesforce CLI available and have already authenticated to your Trailhead Playground with alias trailhead.
Prompt 1 β Setup: Seed the Broken State
I need you to set up a Trailhead Playground org (alias: trailhead) with a
deliberately broken automation configuration that we will use for a diagnosis
exercise.
Create all metadata in a fixtures/setup/force-app directory using Salesforce
DX project structure. Add fixtures/setup/force-app as a package directory
in sfdx-project.json. Then deploy it to the org and verify the broken state
is active.
Here is what needs to be deployed:
FIELD
- Object: Account
- Field: Open_Case_Count__c
- Type: Number, 18 digits, 0 decimal places
- Label: Open Case Count
- Ensure the field is visible to the System Administrator profile by
deploying a Permission Set that grants read/write FLS on the field
and assigning it to the running user.
- Add the field to the "Account Layout" page layout (Account Information
section, first column) so it is visible on Account record pages.
FLOW
- Name: Update_Account_Open_Case_Count
- Type: Record-Triggered Flow on Case object
- Trigger: After save, on Create and on Update (no entry filter needed)
- Action: Read the parent Account's current Open_Case_Count__c.
On create: add 1. On close (IsClosed falseβtrue): subtract 1.
On reopen (IsClosed trueβfalse): add 1.
Update the parent Account with the new value.
(This must use incremental arithmetic, NOT an aggregate COUNT() query.
The point is to duplicate the triggers' logic so both fire and
double-count.)
TRIGGER A
- Name: CaseInsertTrigger
- Object: Case
- Event: after insert
- Handler class: CaseInsertTriggerHandler
- Logic: For each inserted Case, increment Open_Case_Count__c by 1 on the
parent Account. Use a bulk-safe pattern (group by AccountId, single DML).
TRIGGER B
- Name: CaseStatusTrigger
- Object: Case
- Event: after update
- Handler class: CaseStatusTriggerHandler
- Logic: For each updated Case, detect when IsClosed flips falseβtrue
(decrement Open_Case_Count__c by 1) or trueβfalse (increment by 1).
Use a bulk-safe pattern.
VERIFICATION
After deploying all metadata, create fixtures/verify_broken.apex and run
it as anonymous Apex:
sf apex run --file fixtures/verify_broken.apex --target-org trailhead
The script should:
1. Create a test Account named "Conflict Demo Account"
2. Insert 3 Cases on that Account with Status = 'New',
one insert DML per Case (not bulk) to ensure each fires
its own trigger + flow cycle independently
3. Close the first Case by setting Status = 'Closed'
4. Query Open_Case_Count__c on the Account
5. Print "PASS: Open_Case_Count__c = {actual} (expected 2)" if the value
equals 2, otherwise print "FAIL: Open_Case_Count__c = {actual} (expected 2)"
The expected result is FAIL. This confirms the broken state is working
correctly. Do not attempt to fix it β the goal of this session is only
to seed the problem.
Prompt 2 β Diagnosis & Fix: Find and Resolve the Conflict
I have a Trailhead Playground org (alias: trailhead) with a known data
integrity problem. The field Open_Case_Count__c on the Account object is
supposed to track the number of open Cases for that Account, but it returns
incorrect values after Cases are created or their status changes.
Please do the following:
STEP 1 β PULL METADATA
Use the Salesforce CLI to retrieve all Apex classes, Apex triggers, and
Flow metadata from the org into a local retrieved/ directory:
sf project retrieve start \
--metadata "ApexClass,ApexTrigger,Flow" \
--target-org trailhead \
--output-dir retrieved/
STEP 2 β ANALYZE
Read the retrieved metadata files and identify:
- All Apex triggers on the Case object
- All Flows triggered by Case record changes
- Any Apex classes that read or write Open_Case_Count__c on Account
- Any ordering conflicts, incompatible logic approaches, or race conditions
between these automations
STEP 3 β DIAGNOSE
Write a clear explanation of the root cause. Describe what each piece of
automation is doing, how they interact in the same transaction, and why
the field ends up with incorrect values.
STEP 4 β FIX
Create the fix in a fix/force-app directory. The fix should:
- Remove or deactivate any automation contributing to the conflict
- Consolidate trigger logic into a single trigger with a handler class
following the one-trigger-per-object pattern
- Use an aggregate query approach (not increment/decrement arithmetic)
to maintain Open_Case_Count__c β this is idempotent and eliminates
race conditions
- Include an Apex test class with at least 75% coverage that tests
Case insert, Case close, and Case reopen scenarios
STEP 5 β DEPLOY
Deploy the fix with local tests required to pass:
sf project deploy start \
--source-dir fix/force-app \
--target-org trailhead \
--test-level RunLocalTests
STEP 6 β VERIFY
Create fixtures/verify_fixed.apex using the same scenario as the broken
verification (create Account, insert 3 Cases, close 1, assert
Open_Case_Count__c = 2) and run it:
sf apex run --file fixtures/verify_fixed.apex --target-org trailhead
The expected output is PASS. If it fails, investigate and iterate until
the verification passes.
Appendix B: Manual Test Steps in the Trailhead Org UI
These steps let you see the problem and the fix with your own eyes inside the Salesforce UI β no CLI required. This is especially useful for screencasts, demos, or sharing the issue with someone who isn’t comfortable on the command line.
Seeing the Problem (After Fixture Deploy, Before Fix)
1. Create a test Account
- Navigate to the Accounts tab and click New
- Name it
Conflict Demo Accountand save - On the Account record, find the Open Case Count field β it should show
0
2. Create three open Cases
- From the Related Cases section click New Case, or navigate to Cases > New
- Create Case 1: Subject =
Test Case 1, Status =New, Account =Conflict Demo Account - Create Case 2: Subject =
Test Case 2, Status =New, Account =Conflict Demo Account - Create Case 3: Subject =
Test Case 3, Status =New, Account =Conflict Demo Account - After each insert, navigate back to the Account and note the value of Open Case Count
You may already see unexpected values here β the count may jump by 2 instead of 1, or show an incorrect number after the first or second insert. This is the trigger + Flow conflict in action.
3. Close one Case
- Open
Test Case 1and change Status toClosed, then save - Navigate back to
Conflict Demo Account - Check Open Case Count β it should be
2but will likely show the wrong value
Take a screenshot of the wrong value for comparison after the fix.
Seeing the Fix (After Prompt 2 Deploys the Remediation)
1. Reset the test data
Delete the Cases and Account created above and start fresh with a new Conflict Demo Account.
2. Create three new open Cases using the same steps as above
- After each Case insert, navigate back to the Account
- Open Case Count should increment by exactly 1 each time:
1>2>3
3. Close one Case
- Set any Case’s Status to
Closedand save - Navigate back to the Account β Open Case Count should now show
2
4. Reopen the Case
- Set the closed Case’s Status back to
New - Navigate back to the Account β Open Case Count should return to
3
5. Confirm the automation changes in Setup
- In Setup, search Flows β find
Update_Account_Open_Case_Count, it should be inactive or deleted - In Setup, search Apex Triggers β you should see a single
CaseTriggerinstead of the originalCaseInsertTriggerandCaseStatusTrigger
What to Look For at a Glance
| Action | Before Fix | After Fix |
|---|---|---|
| Create 1st Case | Count may jump to 2 or stay at 0 | Count = 1 |
| Create 2nd Case | Count unpredictable | Count = 2 |
| Create 3rd Case | Count unpredictable | Count = 3 |
| Close 1 Case | Count wrong or unchanged | Count = 2 |
| Reopen closed Case | Count wrong | Count = 3 |
| Triggers on Case object | 2 (CaseInsertTrigger, CaseStatusTrigger) |
1 (CaseTrigger) |
| Flow active | Yes (Update_Account_Open_Case_Count) |
No |