How to build a win-loss analysis agent in Salesforce
Your closed-lost report says Timing and Price. Here's how to build a Salesforce agent that reads every closed deal and writes up what really happened.
Print it out and tick off each step as you go, or keep it open next to you while you work.
Table of contents
Salesforce Enterprise Edition or higher, with Closed Won and Closed Lost used for real deals and at least 30 closed deals in the last 12 months. Emails need to sync into Salesforce as native activity records. Call transcripts are optional.
Why did you lose your last ten deals? If your answer comes from the closed-lost dropdown, it's a one-word guess a rep picked on the way out. The real answer is already in Salesforce, in the stage history, the emails and the calls.
This guide shows you how to build a win-loss analysis agent: an AI that reads each closed deal in Salesforce and writes up why you won or lost it. It has three parts:
- The template: the same nine fields the agent fills in for every deal, like the main reason, the competitor and the objections. A filled-in template is called a card.
- Phase 1, learn from your last 12 months: you run the agent across your closed deals and turn what it finds into decisions.
- Phase 2, automate it going forward: you switch it on so it writes a card for every deal as it closes.
Here's what that gets you. Instead of "Timing" or "Price" on most of your lost deals, every closed deal gets the same card: why you won or lost it, who you lost to and what the buyer pushed back on. You read one table instead of hundreds of deals, and every finding traces back to named deals.
Check these three things first
If one of these fails, stop here and fix it, because everything after depends on it.
- You have at least 30 closed deals from the last 12 months. Run an Opportunity report filtered to closed deals in that window and read the count. Below 30, any pattern is noise, so come back when the count is there.
- Lost deals are really marked Closed Lost. If they get deleted or left open forever, there is nothing to analyze. Fix that process first. The closed-lost reason field setup is covered in our renewal management and win-loss reporting guide.
- Your org is Salesforce Enterprise Edition or higher. You can see your edition in Setup under Company Information. The agent reads your data through Salesforce's API (the way outside tools connect to it) and runs under an Integration User license (a license for automated connections, not a person). Professional lacks API access without the Web Services API add-on, and it lacks those licenses.
Phase 1: Learn from your last 12 months
Run these seven steps across your last 12 months of closed deals.
Phase 1 runs outside Salesforce. You export your closed deals, then run Claude on your own computer, either on the export files or reading your org through Salesforce's hosted MCP server. Nothing gets written back to Salesforce in this phase.
1. Set up the template
When this step is done, you'll have the prompt that fills in the nine fields for every closed deal.
Without consistent fields, every deal produces a different shape of data. It's like comparing restaurant reviews where one person rated the service and another only mentioned the parking. You can't line them up, so no pattern shows.
The template is a list of fields you give Claude, not something you build in Salesforce. You write the nine fields into your prompt as the labels Claude must fill in for every deal, and Claude returns each deal's answers in that fixed format. You save the answers in one file, one card per Opportunity. The nine fields are in the table below, and the prompt that uses them follows it.
Here are the nine fields, the same nine on every deal:
The confidence level matters most. A card that admits it had nothing to read is worth more than a confident one built on nothing. That's why the prompt requires "insufficient data" instead of a guess.
Here is the prompt that fills in the template. Replace the bracketed parts with your company's details and keep the keys exactly as written, because the pattern pass and Phase 2 depend on them. It returns a few keys beyond the nine fields: the Opportunity ID to match each card to its deal, the suggested closed-lost reason that Phase 2 reuses, the evidence dates behind the main reason, and a one-sentence note on the confidence level. You can't run it until you've exported your data in steps 2 and 3, so copy it now and come back to it in step 5.
2. Pull the baseline numbers
When this step is done, you'll have your baseline numbers and the data quality facts about your own records.
Before the agent runs, you need your baseline numbers.
To pull them, you first need read access to the org. Ask your Salesforce admin for a read-only user, then log in to the org with the Salesforce CLI by running sf org login web as that user. If you want Claude to read the org directly instead of working from exports, the admin also enables Salesforce's read-only hosted MCP server and sets up an External Client App for it. If you can't get access, ask the admin to run the reports below and send you the exports.
Export every Opportunity closed in your window along with its stage history. The simplest way is an export to CSV with the Salesforce CLI, Salesforce's command-line tool. Without it, run one report on Opportunities and a second on Opportunity History, and export both. Save them as closed_opps.csv and opp_history.csv, then ask Claude to calculate the following from them and save the result as a spreadsheet called baseline_cuts.xlsx, one sheet per cut:
- Overall win rate
- Win rate by segment, industry, deal size band, lead source, type and rep
- Average cycle length and time per stage, won against lost
- The stage each lost deal was in when it died
- The closed-lost reason breakdown, including blank and "Other"
- The competitor breakdown, from whatever competitor field your org has
Before you trust the numbers, run three checks. The closed deal count matches a Salesforce report. The overall win rate matches a report grouped by Won. One rep's numbers match what their manager expects. If any of them is off, the export filter or the won flag is the usual cause.
Then record the data quality facts as findings in their own right:
- The share of your closed-lost deals that carry no reason, or "Other"
- The share with zero logged activity
- The share with no contact role
- Whether emails and transcripts were visible at all
These usually turn into your first two or three recommendations, before the agent has read a single deal.
3. Pull the deal record and transcripts
When this step is done, you'll have a clear picture of which emails and call transcripts the agent can read.
Next comes the deal record itself. For each deal, the CRM record is the mandatory base:
Stage history is the one people skip. It's what tells you a deal died in technical validation rather than at pricing, and that difference changes the recommendation you end up making.
Emails only count when they live in Salesforce as native activity records. An agent can't read mail that sits outside the org, so if yours isn't syncing as EmailMessage records, run without it and flag the gap in the findings instead of treating the record as complete.
Export the activity layer and the contact roles the same way as in step 2, saved as tasks.csv, events.csv, emails.csv and contact_roles.csv. These files also let you finish the data quality facts from step 2: how many deals have no activity, no contact role or no emails.
Call transcripts are optional, and they roughly double the depth of the qualitative findings. If you already use Einstein Conversation Insights, your calls become call records inside Salesforce and you pull the text with the Get Conversation Transcript flow action. Salesforce's Einstein Conversation Insights requirements documentation lists the license allotments and processed-hour limits, which are worth reading before you plan a backfill of old calls.
Third-party recorders behave differently. None of their Salesforce integrations attach transcripts to closed deals. They write summaries, notes or events only, so you pull the transcripts from the tool by customer email domain and date range, then match them to Opportunities by account and date. Either way, save each transcript as a text file named after its Opportunity ID, in a folder called transcripts.
What each tool lets you pull:
- Fathom: API access is on every plan, including Free. Its Salesforce integration only gives new activity to open Opportunities, so it skips Closed Won and Closed Lost.
- Circleback: the API and MCP server (the connection that lets an AI tool read another system's data) are on every plan. Salesforce automations need the Pro plan.
- Gong: an admin can pull transcripts through its API. Gong's own MCP server returns call briefs and deal answers but no raw transcripts.
- Zoom: the connector for Claude returns transcripts and summaries, but only for meetings the connected user hosted or was granted access to, and only if Zoom's AI Companion recording or summary features are turned on.
4. Write the business questions
When this step is done, you'll have three to five business questions your sales leader has agreed on.
Start with the questions. Write down the three to five things the team wants to understand about why they win and lose. Typical ones: who are we losing to and where, does win rate differ by segment or lead source, what do the won deals have that the lost ones don't, is pricing the problem, which reps close what and why. The whole analysis organizes around these, so they go into the second prompt in step 5.
Don't ask the team to write them from scratch. Bring your sales leader three to five you recommend and ask what they want to add or remove.
5. Run the prompts
When this step is done, you'll have a card for every closed deal in cards.jsonl and a written answer to each business question.
You run two prompts, in order.
- One request per deal. The agent reads the full record for a single Opportunity and fills the nine-field card, using the prompt from step 1. Store the cards one row per Opportunity.
- The pattern pass. Once every card is written, hand the agent the full table of cards, the baseline cuts and your business questions from step 4 and have it answer each business question with evidence: which factors show up in lost deals far more often than in won ones for a given segment, which competitors appear and where, where the picklist reason disagrees with what the activity shows, and what the winning reps' deals have in common.
Run the card prompt from step 1. For up to about 150 deals, open a terminal in the folder with your exports, start Claude Code (Anthropic's command-line coding tool), paste the prompt and tell it: "For each row of closed_opps.csv, put together the material from tasks.csv, events.csv, emails.csv and the transcript file for that Opportunity, run the card prompt, and add each answer to cards.jsonl. Do the first 5, show them to me, then continue." Above 150 deals, or for a rerun, ask Claude to write a script that sends one request per deal through Anthropic's Message Batches API, which costs half as much and doesn't tie up your session.
The second prompt is separate. Paste your business questions from step 4 into it and attach cards.jsonl and baseline_cuts.xlsx.
Require specific deal examples behind every claim. A finding you can't trace back to named deals is a finding you can't defend in the room.
6. Check the agent's work
When this step is done, you'll have spot-checked 10 cards and know whether the prompt needs another pass.
Don't skip this one. Pick 10 deal cards at random and read the underlying activity yourself, the way an auditor pulls a sample of invoices instead of rereading all of them. More than 2 of them wrong or overstated means the prompt needs tightening and the per-deal requests need a rerun. Never present a finding you haven't spot-checked.
Two failure modes show up more than any others.
The first is a confident wrong summary on a thin deal. Three logged tasks and no transcript is still enough raw material for fluent prose, which is exactly why every card carries a confidence level and why the prompt requires "insufficient data" over a guess.
The second is a detected competitor being treated as confirmed. The agent infers a name from one line in an email and the reader takes it as established fact. Label the competitor as detected in the findings until someone confirms it.
7. Turn the patterns into decisions
When this step is done, you'll have your findings turned into decisions, ordered by revenue impact, with the deal count behind every claim.
Once the spot check passes, you have an answer to each business question. Present every finding as a decision somebody can actually make. Five kinds come up:
- Change pricing or packaging for a segment.
- Stop chasing a segment.
- Add something to the competitive battlecard.
- Coach reps on a specific objection.
- Rebuild the closed-lost picklist.
Order them by revenue impact, and let ease of implementation break the ties. Size each one by the lost Amount in the affected segment over your window. Mark any recommendation that rests on fewer than 10 deals as directional, and say how you'll measure the change after 90 days.
One finding deserves its own line in the document: the deals where the rep's closed-lost reason disagrees with what the activity shows. That gap is the clearest argument you have for running the agent on every deal from here on.
Name the deal count behind every segment claim. Segment cuts get thin quickly, and a confident deck makes a small sample look solid. Write the limits down as well: the sample size and any missing transcripts or fields.
Phase 1 ends with a findings document and a presentation to sales leadership, where you capture which recommendations they accept and who owns each one.
Phase 2: Automate it going forward
Phase 2 reuses the business questions, the prompts and the picklist values from Phase 1.
8. Clean up the picklist and choose where it runs
When this step is done, you'll have a closed-lost picklist the agent and the reps both use, and a decision on where the agent runs.
Before you go live, clean up the closed-lost picklist if Phase 1 showed it needs it. Usually that means fewer, clearer values and no "Other", so the agent and the reps are working from one vocabulary.
Then pick where the agent runs. A Prompt Builder template is a saved prompt that runs inside Salesforce itself, and it's the default. An Agentforce agent is Salesforce's own AI agent product, and it's worth it when the company already owns the add-on. Claude connected through Salesforce's hosted MCP servers (the connection that lets an AI tool work with Salesforce data) is the third option, and it gives you the most control over the prompts themselves.
9. Keep the agent inside its own fields
When this step is done, you'll have an agent that writes only to its own fields, with the rep confirming every suggested closed-lost reason.
The agent writes a summary onto the deal. Two parts of it need care: a suggested closed-lost reason that the rep confirms, and a detected competitor that stays separate from the confirmed one until a person verifies it. Think of a note-taker in a meeting who writes in their own notebook and never edits yours. The agent never edits stage, amount, close date or your own closed-lost reason picklist.
It writes to six fields on the Opportunity that it owns. Create them, put them in a Win-Loss Analysis section on the page layout, make them read-only for reps and managers, and set field-level security so only the integration user (the dedicated account the agent runs as) can edit them. If your org has no closed-lost reason or competitor fields of its own, create those too, as picklists, using the values you agreed with your sales leader in Phase 1.
10. Build the trigger and the template
When this step is done, you'll have a flow that flags each deal when it closes and a template that writes the card to the deal.
These steps build the default path, a Prompt Builder template. The other two options use the same flag and the same fields. They differ in what generates the card.
First, the trigger. In Setup, search for Flows, click New Flow and pick Record-Triggered Flow. Choose the Opportunity object and trigger it when A record is updated, with the condition Closed equals True and Only when a record is updated to meet the condition requirements selected. Set Optimize the Flow for to Actions and Related Records. Add an Update Triggering Record element that sets Needs Win-Loss Analysis to True. Test it by moving a test Opportunity to Closed Lost, then activate it. Because the flow only fires when a deal moves into Closed, the agent clearing the flag later won't trigger it again.
Next, the template. Confirm that Foundations, Data 360 and Einstein generative AI are turned on in your org. In Setup, search for Prompt Builder, click New Prompt Template and set the type to Flex, following Salesforce's guide to creating a Flex prompt template. Use your card prompt from Phase 1 as the instructions, with the same keys, and ground it on the Opportunity plus a small flow that gathers the deal's activity, emails, contact roles and transcript. The Default Workflow User, set in Process Automation Settings, needs the Prompt Template User permission.
Then connect them. In the record-triggered flow, on an asynchronous path, add the Prompt Template action to generate the card. After it, call a second flow, Write Win-Loss Fields, that saves the card into the six fields and clears the flag, then notify the rep and the manager through Send Slack Message or an email alert. To run the agent on deals that closed before the flow existed, tick the flag on them from a list view.
11. Review the first 20 deals
When this step is done, you'll have the cards for your last 20 closed deals read through with your sales leader, with the tone, length and suggested closed-lost reasons tuned.
Generate the cards for the last 20 closed deals with the sales leader in the room, read them together, tune the tone and length, and confirm the suggested closed-lost reason matches your picklist values exactly.
12. Run the pilot
When this step is done, you'll have 15 or more closed deals marked accurate, partially accurate or wrong, a clear read on whether you've reached 80%, and a first digest reviewed with leadership.
Run on one team or one segment for two to four weeks, long enough to catch 15 or more closed deals. After each batch the manager marks every card accurate, partially accurate or wrong. Target at least 80% accurate or partially accurate before you roll out any further.
Also compare the agent's suggested closed-lost reason with the one the rep picked. Wide disagreement is worth discussing with your sales leader, and the fix may be the picklist, the prompt or rep training. At the end of the pilot, produce the first digest and review it with leadership as a dry run of the monthly cadence.
13. Start the digests
When this step is done, you'll have both digests scheduled and an owner for acting on what they show.
The monthly digest goes to sales leadership. It covers that month's closed deals: the main reasons you won and lost, where the agent's suggested closed-lost reason disagrees with the rep's, the competitors that came up (confirmed and detected listed separately), and the key factors that keep coming up.
The quarterly digest goes to marketing and product. It covers the same things over three months, plus win rate by segment and cycle length for won against lost deals, and the first one also compares your numbers 90 days in with the baseline from Phase 1.
On the default path, a Scheduled Flow produces the digests. It uses the Prompt Template (Batch Generation) action with a second template that reads the period's AI fields. Put the delivery step on its Completed path and an error email on its Timed out path. Test it with a real scheduled run in a sandbox, because Run and Debug in Flow Builder don't work for this action.
Put both on the calendar and agree who owns turning a finding into an actual change.
Getting reps on board
The main rollout risk is reps reading the agent as surveillance. An AI writing "why you lost" onto someone's deal is the fastest way to lose the sales team. Every field on the card is addressed to the deal, and none of them grade the rep. The rep and the manager see the summary at the same moment. The agent never edits the deal, and the suggested closed-lost reason is a suggestion the rep confirms. Say all of that plainly when you announce it, and give your sales leader the wording before it goes out.
Frequently asked questions
What fields should my win-loss analysis template include?
Nine: outcome, deal story, primary reason won or lost, secondary factors, competitor mentioned, objections raised, pricing discussion, champion status at the end, and a confidence level.
Can I do this without call recordings?
Yes. The CRM record is the base, and the stage history, activity, contact roles and emails carry most of the story on their own. Transcripts add depth when you have them. When they aren't available the agent runs without them, and the confidence field shows you which cards were built on thin material.
How many closed deals do I need?
At least 30 closed deals in the window. Below that, any pattern you find is noise. More is better, and segment-level conclusions need more again, which is why you name the deal count behind every segment claim.
Can I do this in HubSpot?
Not yet. This runs on Salesforce Enterprise Edition or higher only.
What to do next
After Phase 1 you know who is taking your deals, where, and why. After the pilot, every closed deal gets its card automatically and a monthly digest keeps sales leadership current.
If your closed-lost report gives the same reasons every quarter, the deal record has more to tell you.
Not sure your Salesforce data is ready to be read? Request a free CRM audit and we’ll tell you what the agent could pull from your org today and what to fix first.

