Loop cost guardrails pattern

The four-part cost guardrail every agent loop should ship with: a hard iteration cap, a stop-after-N-turns clause in the goal text, a budget limit on SDK loops, and a /cost check inside the loop body.

prompt
→ Claude
Every loop gets: `MAX_ITER=20` hard cap, "or stop after N turns" in the /goal text, `max_budget_usd` on SDK loops, and a /cost check in the loop body.
claude-code

Implementation note

When to use: before running any loop unattended — this is the checklist pattern for the most common loop disaster, discovering the overnight run cost fifty times your estimate. How it works: four guardrails, applied together rather than as alternatives. A hard MAX_ITER=20 cap in the loop wrapper bounds iterations mechanically. An or-stop-after-N-turns clause written into the /goal text bounds the in-session layer. max_budget_usd on SDK-driven loops bounds dollar spend directly. And a /cost check inside the loop body gives running visibility, so drift is observable mid-run instead of at invoice time. Safety: the redundancy is the design — each rail catches what another misses: the iteration cap stops infinite loops, the budget cap stops expensive-per-iteration loops, and the in-prompt clause survives contexts where the wrapper does not apply. Adopt all four as the default template for every loop you ship, not just the risky ones.

Source: Developers Digest

More automation loops

Run workflows with dynamic sub-agents

/goalnew

Split a task into packets, run sub-agents in parallel, synthesize results, and verify completion.

prompt
→ Claude
/goal loop and verify until complete
automationlow risk

Run agent turns until goal met

/goalnew

Agent executes repeated turns toward a condition, with a lightweight evaluator checking progress after each turn until the goal is reached.

prompt
→ Claude
/goal <condition turns a prompt into a durable objective. Thanos immediately starts a turn toward the condition, and after each turn a fresh, tool-less side-channel evaluator (a one-shot completeSimple call, not a subagent — so no extra agent turn and no re-entrancy) reads the last turn's evidence and returns MET / NOT MET . NOT MET auto-continues another turn with the reason as guidance; MET clears the goal and records the achievement. Unparseable evaluator output is treated as NOT MET (fail-safe: it never declares a false "done
automationmedium risk

Run agent until goal met

/goalnew

Queue agent turns with goal context until your objective is achieved, treating the goal as untrusted data.

prompt
→ Claude
/goal <objective , after /goal resume , and after every agent turn that leaves the goal active , the extension queues Codex's goal continuation prompt as hidden model-visible context. The objective is XML-escaped and wrapped as untrusted user data so it does not become higher-priority instructions
automationlow risk