Back to Blog
AI Builds

AI Loops in Salesforce: How to Make AI Agents Finish the Job

PS

Piyush Kumar Singh

Salesforce Developer

15 min read - Jul 31, 2026

The short version

  • A prompt answers one question and stops. A loop is a goal the AI keeps working toward: it plans, does the work, checks its own result against the goal, and goes again until it clears the bar.
  • The gate is everything. If nothing can automatically fail the work - a test, a deploy, a validation rule - you do not have a loop, you have the AI grading its own homework.
  • Salesforce people are better positioned for loops than most developers: an org already ships the best gates in software (Apex tests, deploys that throw errors, validation rules) plus a built-in human approval layer.
  • Only build the heavy version when a task repeats at least weekly, can be auto-checked, runs end to end, and has an objective "done." Otherwise a normal prompt is faster.
  • The number that matters is cost per accepted change, not tokens spent. Below roughly half of results accepted, the loop costs more than it gives back.
  • Build order: prove one manual run, save it as a skill, add the gate and stop condition, and only then put it on a schedule. Scheduling an unproven loop is how it breaks while you sleep.

The One-Request Habit Is the Ceiling

You have probably felt it already. You open a chat, ask for a validation rule, read it, tweak it, paste it into Setup, then go back and ask for the next one. It helps, but you are still doing every step by hand. The AI only moves when you push it, and it stops the second you look away.

Watch that habit for a second, because the habit is the whole problem. You decide what to ask. You judge the answer. You decide what comes next. You are the engine, and the AI is the tool in your hand - and a tool does nothing on its own.

The other way is easy to describe. You give the AI the goal once and let it run the steps itself. It works out what needs doing, does the work, checks its own result against the goal, fixes what is weak, and goes again until the job is finished. You step out and the work keeps going. That pattern has a name: a loop. This guide covers how it works inside a Salesforce org, when it is worth building, and how to run one today.

What a Loop Actually Is

A prompt is a single instruction. It hands you one answer and waits for you to decide what happens next. A loop is a goal the AI keeps working toward until it gets there. You set the goal, you define what done looks like, and it runs the whole cycle on its own.

The cycle has four stages, and the last one carries all the weight: if the work clears the gate it ships, and if it does not, the result feeds back into the next pass and the loop tries again.

Discoverwhat needs doingPlandecide howExecutedo the work in the orgVerifycheck against the goalclears the gateDonechanges ready to shipnot there yet, feed the result back in
Discover, plan, execute, verify. If the work clears the gate, it ships. If not, the loop feeds the result back and tries again.

The Three Parts Everyone Gets Wrong

Verify is the heart of it. If nothing checks the result, you do not have a loop - you have the AI nodding along with itself. The check is what turns going in circles into real progress. Wire in something that can fail the work and the loop has a spine; skip it and the AI grades its own homework, which it is far too kind to do honestly.

The most useful trick in the whole discipline is splitting the agent that does the work from the one that checks it. The model that wrote the code is too easy on itself. A second agent with different instructions - and sometimes a stronger model - catches what the first one talked itself into. A person can play the checker too. That split is where most of the quality comes from.

State is what lets it learn. Each pass, the AI needs to remember what it already tried, or it makes the same mistake forever. A real loop keeps a short record on the side: what is done, what failed, what is next. Ground that in your real records and it resumes with context instead of starting cold. This is also where the bill starts to grow, which we will come back to.

And a stop condition keeps it sane. A loop with no way out runs until it works, breaks, or empties your budget. Give every loop two exits: success, and a hard cap - after five tries, stop and report what is left. In Salesforce there is a third exit, and it is the important one: a person. Anything risky pauses for human approval.

The Four-Box Test: Do You Even Need One?

Most guides sell you the loop before they admit when it is a bad idea. Here is the honest test - build a loop only when all four of these are true:

  • It repeats, at least weekly. A one-off validation rule is faster to just ask for once. If the setup cost never pays itself back, skip it.
  • Something can automatically reject a bad result. A test, a deploy, a validation rule, a hard check. If nothing can fail the work, the loop just spins.
  • The agent can do the whole thing itself, start to finish, without handing half of it back to you.
  • Done is objective, not a matter of taste. If quality comes down to judgment, a person still wins.

Miss one box and keep it as a normal prompt. Loop engineering is real, but most work does not need the heavy version yet - and the light version further down costs nothing to try. Just know where the line sits.

Why Salesforce People Are Better Positioned Than They Think

Loops caught on in software first because code is the easiest thing to check: a test passes or it fails and there is nothing to argue about, so the AI always knows whether it is finished. Here is the insight most loop guides miss - a Salesforce org is one of the most gate-rich environments in all of software. A deploy is clean or it throws a metadata error. An Apex test suite passes or fails with a coverage number attached. A validation rule fires on a bad record or it does not. Flows have error paths, approval processes are a native human-in-the-loop, and every change is tracked in setup audit history.

In other words: the hardest part of loop engineering - building a gate that can honestly fail the work - is the part your platform already ships. Most developers have to construct their verification layer from scratch. You inherit yours. Here is what a loop spec looks like when the target is a Salesforce change:

A loop spec, in Salesforce terms

GOAL
deploy the Require_Amount_for_Negotiation validation rule to the
sandbox with a clean deploy and both test records behaving correctly.

EACH PASS
  1. deploy to the sandbox and read every error
  2. pick the single biggest failure
  3. make the smallest change that fixes it
  4. redeploy and run the two test opportunities

VERIFY   clean deploy + fires below $1,000 + does not fire on a valid record
STOP     when verify passes, or 5 attempts
ON STOP  summarize what changed and what still fails

That shape - goal, then pass, then verify, then stop - is the whole game. The next section is the machinery that runs it without you sitting there.

A Worked Example: Watching the Loop Earn Its Keep

Specs are abstract, so here is what actually happens when that loop runs. Nobody touched it after setting the goal - this is the transcript shape you see in the loop's own log:

Three passes, no babysitting

PASS 1  deploy -> ERROR: no field Amount__c on Opportunity (line 3)
        smallest fix: correct the API name to Amount

PASS 2  deploy clean -> TEST FAILS: rule fires on the $5,000 record
        smallest fix: operator was <=, should be <

PASS 3  deploy clean -> fires below $1,000, silent on the valid record
        VERIFY PASSES -> loop stops, changes staged for review

RESULT  shipped in 3 passes and a few minutes of compute

Three things in that trace are worth noticing, because they are the whole discipline in miniature. First, errors are fuel, not failure: the deploy error in pass 1 is exactly the information the next pass needed, and the loop consumed it automatically instead of waiting for you to read it. Second, the smallest-change rule kept each pass diagnosable - when the loop changes ten things at once and the test flips, nobody knows which change did it, including the loop. Third, the run ended because the gate said so, not because the model felt finished. That last distinction is the entire difference between automation you can trust and automation you have to check.

Now scale the same trace in your head: ten validation rules in a backlog, a loop per rule, running overnight. The ones that clear the gate are staged for your morning review; the ones that hit the attempt cap arrive as a summary of what was tried and what still fails. You review outcomes instead of performing steps. That is the shift.

The Five Building Blocks

A production loop is built from five parts, and tools like Claude Code, Codex, and Agentforce give you all five. Knowing which part does what means you know which one to fix when something breaks.

  • The trigger, the heartbeat. What turns a one-off into something that runs on its own: a schedule, a record change, a scheduled Flow, a CI pipeline. The findings come to you instead of you going to check.
  • The skill, saved instructions. Instead of pasting the same wall of rules into every run, save them once as a file the loop reads each time - the rules, the patterns, and a hard list of what it must never touch (managed packages, mass Contact updates). This is exactly what the open SKILL.md format is for; we publish 141 free Salesforce skills built this way at cloudsheer.com/skills.
  • Two agents, not one. Split the builder from the reviewer. The builder can be fast and cheap; the reviewer slow, careful, and stricter. The split is where the quality comes from.
  • Connectors, so it acts. The difference between 'here is the fix' and a loop that deploys the metadata, updates the record, and posts to the channel once tests pass. Connectors let the loop work inside your real org instead of describing what it would do.
  • The gate, the verifier. The test, the deploy, the check that automatically rejects bad work. This one part decides whether the loop helps you or just spends money. Everything else is plumbing.

Stack those together and teams run whole fleets of them at once - one engineer used a loop like this to migrate an entire codebase between languages in about six days, work that would have taken close to a year by hand. It is a real change in how software gets built. It also comes with a catch the demos skip.

You Have Already Done This: The Agentforce Mapping

If you have configured Agentforce, here is the reveal: you have already done loop engineering, under different names. Every concept in this guide has a direct Agentforce counterpart, and seeing the mapping makes both sides easier to reason about.

  • Topics are the goal space. A Topic scopes what jobs the agent may work toward - the loop's goal, defined once, bounded deliberately.
  • Actions are the execute step. Flows, Apex, and API calls the agent can invoke - the connectors that let it act in the org instead of describing what it would do.
  • Instructions are the skill. The saved rules the agent reads on every run, including the hard list of what it must never touch.
  • Guardrails and escalation rules are the stop conditions. Attempt limits, forbidden territories, and the human exit for anything risky - the three exits from section three, productized.
  • The Atlas Reasoning Engine is the plan-and-verify cycle. Its reason-act-observe pattern is this article's loop diagram running inside the Salesforce trust boundary.

The mapping cuts both ways, and that is the practical payoff. If you understand loops, you configure better agents: your Topics get crisper goals, your instructions get real never-touch lists, and you stop shipping agents whose only gate is vibes. And if you have run Agentforce in production, you already have the instincts for everything else in this guide. Our own flagship deployment - the warranty agent resolving 92% of cases across 12,000+ a month - is exactly this architecture: tight goal space, hard gates, human escalation. Loop engineering is not a new discipline arriving in Salesforce; it is the discipline Salesforce AI was already quietly built on.

The Cost Nobody Mentions

Loops run on tokens, and tokens cost money. The trap is not that each step costs something - it is how the cost stacks. Every pass re-reads everything: the goal, the metadata, the last result, what failed. That pile goes through the model again on every iteration and grows each time. A loop that runs ten times does not cost ten prompts; it costs ten prompts that each keep getting bigger. Run a second agent as reviewer and the bill doubles, because two models now read the work.

Rough cost of one loop

single agent, one medium task   ~50,000 to 200,000 tokens
context re-sent every pass       grows each time
a fleet running in parallel      multiply all of the above

The number that actually matters - and almost nobody watches - is cost per accepted change. Not tokens spent, not loops run. If the loop hands you ten results and you throw six away, you are doing the review work it was supposed to save. Below about half accepted, it costs more than it gives back.

And loops fail quietly. A well-known failure mode is the agent that decides it is finished too early, stops on a half-done job, or keeps running and spending while producing nothing. Without a hard gate that can fail the work, a loop does not crash - it bills you in silence. That is why the heavy version belongs to teams with budget and guardrails: attempt caps, token budgets, cheap models on the boring steps, monitoring.

The Order That Works

If you do build one, the order matters more than the tools. Teams whose loops survive in production all do it the same way:

Build order

1. Get ONE manual run reliable first.
2. Turn that into a skill (save the instructions).
3. Wrap the skill in a loop (add the gate and the stop condition).
4. THEN put it on a schedule.

Scheduling something you have not made reliable by hand is exactly how a loop breaks while you sleep. In Salesforce terms: prove it in a sandbox, save the steps, add the tests and the approvals, then let it run. Prove it once, harden it, then automate it.

The Maturity Ladder: Where Your Team Actually Is

Teams adopt loops in recognizable stages, and knowing which rung you are on stops you from buying machinery you cannot feed yet. Each rung must pay for the one below it - you climb because the current rung is saturated, never for pride.

  • Level 0 - one-shot prompts. Ask, read, paste, repeat. Where nearly everyone starts and where the ceiling in section one lives.
  • Level 1 - self-checking prompts. The paste-anywhere structure below: criteria, self-scoring, iterate until FINAL. Costs nothing, works today, and most teams should live here for months. The quality jump over Level 0 is bigger than any jump above it.
  • Level 2 - saved skills. Your reliable prompts become files with rules and never-touch lists, shared across the team. Consistency arrives; tribal prompting dies.
  • Level 3 - gated loops. A real verifier that can fail the work, attempt caps, and cost tracking. This is where the four-box test becomes mandatory rather than advisory.
  • Level 4 - scheduled fleets. Loops on triggers with monitoring and human approval gates - the nightly data check, the Friday digest. Powerful, and only sane with Level 3 discipline underneath.

The honest diagnostic: if your team has no saved skills, the next step is not a scheduled fleet - it is one self-checking prompt used consistently for a week. And if you are already at Level 3 wondering why the bill grows faster than the value, the answer is almost always a weak gate at Level 3, not more automation at Level 4.

A Loop You Can Paste Into Any Model Right Now

You do not need an agent framework to feel how this works. The trick is handing the model all three parts at once - a goal, strict success criteria, and a rule that forces it to check itself before it can stop. Paste this into any capable model right now:

A self-checking loop you can paste anywhere

You will work in a loop until the task meets the bar.

TASK
[describe exactly what you want produced]

SUCCESS CRITERIA (be strict, no soft passes)
- [criterion 1]
- [criterion 2]
- [criterion 3]

LOOP (repeat every turn)
  1. PLAN   state the single next step.
  2. DO     produce or improve the work.
  3. VERIFY score the result 1 to 10 on each criterion.
            be honest, and list what is still weak.
  4. DECIDE if every criterion is 8 or higher, print "FINAL" and stop.
            otherwise print "ITERATING" and fix the weakest point first.

RULES
- Never call it done until every criterion is 8 or higher.
- Each pass must fix the weakest score from the last VERIFY.
- Do not ask me questions. Make a sensible assumption, note it, keep going.

Begin. Run the loop until FINAL.

Watch what happens. It drafts, scores its own work against your criteria, finds the weak spot, and rewrites - again and again - until it clears the bar instead of handing you the first thing that looked close. That is a loop, built with a paragraph.

Now notice what is still missing. You are the trigger. You opened the chat and you are sitting there watching it go; close the tab and it is gone. For a loop that runs on a schedule or fires the moment a record changes, the AI needs a safe, governed way to reach into your org through approved tools and proper access controls - Named Credentials, scoped integration users, MCP. We wrote a full technical guide to exactly that: how to connect Claude to Salesforce, from the API pattern to MCP. That governed-access side is where the follow-up guide picks up.

Five Loops Worth Running in a Real Org

The four-box test points at the same handful of jobs again and again. Here are five that earn their keep, each written the same way: a goal, a gate that can fail it, and a stop. If you cannot fill in the gate line, it is not ready to be a loop yet.

  • Keep the test suite green. After a change, fix failing Apex tests before the work goes further. Gate: every test passes and coverage stays above your bar. Stop: green, or 8 attempts, then report what still fails.
  • Turn a sentence into a validation rule. Take a plain-language rule from a stakeholder and deploy it as real metadata. Gate: clean sandbox deploy, fires on a bad record, leaves a good one alone. Stop: pass, or 5 attempts, then hand back a summary.
  • Run a nightly data check. Find Accounts missing required fields or likely duplicates, and open a task for the owner. Gate: only flags records matching the rule, and writes nothing but tasks. Stop: one run a night, capped at a set number of records.
  • Keep documentation current. Document every Flow that changed this week - purpose, trigger, key steps. Gate: every changed Flow has its Description filled in. Stop: when all changed Flows are covered.
  • Post a Friday release digest. Summarize the week's deploys from change history into your channel. Gate: the summary matches the deploy log, with nothing invented. Stop: once a week, on schedule.

Notice the shape never changes. Every one is a goal, a check that can say no, and a limit. Get that skeleton right and the topic of the loop barely matters - what decides success is not the task, it is whether the gate is real.

One closing thought on scale: this is not theoretical for us. Our flagship Agentforce deployment runs this exact shape in production - goals, gates, and human escalation - and autonomously resolves 92% of warranty cases across more than 12,000 a month. The pattern in this guide is the same one, just starting smaller. Which tasks are safe to hand an agent, and which need a person in the loop, is a governance question of its own - and that is where the next guide in this series picks up.

FAQ

Frequently Asked Questions

What is an AI loop in Salesforce?

An AI loop is a goal the AI works toward on its own instead of a single prompt you babysit: it plans a step, does the work in the org, verifies the result against explicit success criteria (a passing Apex test, a clean sandbox deploy, a validation rule behaving correctly), and repeats until the work clears the gate or hits a stop condition. The verification step is what separates a real loop from the AI going in circles.

Do AI loops work with Agentforce?

Yes - Agentforce is effectively loop machinery inside the Salesforce trust boundary: Topics define the goal space, Actions do the work, guardrails and escalation rules are the stop conditions. Our flagship Agentforce deployment autonomously resolves 92% of warranty cases across 12,000+ a month, and it follows exactly the shape in this guide: a goal, a gate that can fail the work, and a human exit for anything risky.

How much does running an AI loop cost?

A single-agent loop on one medium task typically burns 50,000 to 200,000 tokens, and the context re-sent on every pass grows each time - so ten passes cost more than ten prompts. The metric worth watching is cost per accepted change: if you throw away more than half of what the loop produces, it is costing more than it saves. Caps on attempts, budgets on tokens, and cheaper models on routine steps keep it honest.

What Salesforce tasks are safe to automate with a loop?

Tasks that repeat, can be automatically verified, and have an objective definition of done: keeping the Apex test suite green, turning plain-language rules into deployed validation rules, nightly data-quality checks that only create tasks, documentation upkeep on changed Flows, and scheduled release digests. Anything touching mass updates, managed packages, or customer-facing records should keep a human approval in the loop.

Want to see how this applies to your business?

Book a free 30-minute call. We will walk through your specific use case and show you what's possible.

Book Free Discovery Call
Ask me anything