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.
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 ↗graded C · 65/100 — how grades work →
More automation loops
Ship PRD stories via dual-agent loop
Ralph runs a generator and evaluator in tandem until all user stories pass acceptance criteria and browser tests.
Ship production-grade apps autonomously
Hand an idea to Claude Code; it authors specs, designs, builds, tests, secures, and ships until enterprise done or budget exhausted.
Set and ship autonomous goals
Run a persistent goal autonomously until completion, routing each task to the optimal model for cost and capability.