Guide

Agent Loops 2026: Ralph Loop, /loop, /goal and Headless Loops for AI Coding Agents

How do I run an AI coding agent in a loop (the Ralph loop, /loop, /goal, or a headless loop) and keep it safe?

The Ralph loop is Geoffrey Huntley's technique of feeding the same prompt file to a coding agent over and over in a Bash loop. Claude Code now ships /loop for interval runs and /goal for running until a condition holds, and Anthropic's Ralph Wiggum plugin runs the loop inside a session with a Stop hook. Codex has /goal and codex exec, and Gemini CLI, Amp and Factory Droid all have headless modes you can script. Always set a stop condition, a turn or budget cap, and a sandbox before you leave a loop unattended.

Coding agent settings change often

Get one email a week when a setting, flag or permission rule changes, checked against the vendor docs.

What the Ralph loop is

Geoffrey Huntley describes Ralph as a technique, and says that in its purest form Ralph is a Bash loop. The loop pipes the same PROMPT.md into the agent on every pass. Work persists in files and git, so each pass sees what the last one did.

The original loop from ghuntley.com/ralph

while :; do cat PROMPT.md | claude-code ; done
  • Ask for one thing per loop. Huntley repeats this rule on purpose.
  • His example prompts keep a fix_plan.md as a prioritised to-do list and an AGENT.md with build and run notes.
  • He says Ralph can be done with any tool that does not cap tool calls and usage.
  • He also describes Ralph as one process working in one repository, doing one task per loop.

Claude Code: /loop, /goal and Stop hooks

Claude Code documents three ways to keep a session running. /loop re-runs a prompt on a time interval. /goal keeps starting new turns until a separate model judges your condition met. A Stop hook in settings decides after every turn whether Claude should continue.

Interval loop and goal loop

/loop 5m check if the deployment finished and tell me what happened
/loop check whether CI passed and address any review comments
/goal all tests in test/auth pass and the lint step is clean
/goal clear
  • /loop is session-scoped. With no interval, Claude picks a delay between one minute and one hour after each iteration.
  • A bare /loop runs a built-in maintenance prompt, or your .claude/loop.md or ~/.claude/loop.md if one exists.
  • Recurring /loop tasks expire 7 days after creation, and a session can hold up to 50 scheduled tasks.
  • Press Esc to stop a self-paced /loop. Set CLAUDE_CODE_DISABLE_CRON=1 to disable the scheduler entirely.
  • /goal is a wrapper around a session-scoped prompt-based Stop hook. It does not change your permission mode, so run it in auto mode for unattended turns.
  • To bound a goal, add a clause such as "or stop after 20 turns" to the condition.
  • A Stop hook that exits with code 2 prevents Claude from stopping and continues the conversation.

Claude Code: the Ralph Wiggum plugin

The anthropics/claude-code repository includes a ralph-wiggum plugin. It runs the loop inside your current session, so you do not need an external Bash loop. A Stop hook blocks Claude's exit and feeds the same prompt back.

Start and cancel a Ralph loop

/ralph-loop "Build a REST API for todos. Requirements: CRUD operations, input validation, tests. Output <promise>COMPLETE</promise> when done." --completion-promise "COMPLETE" --max-iterations 50

/cancel-ralph
  • --max-iterations stops after N iterations. The default is unlimited.
  • --completion-promise is a phrase that signals completion. It uses exact string matching.
  • The README says to always use --max-iterations as your primary safety mechanism.
  • It lists tasks that need human judgment, one-shot operations, unclear success criteria and production debugging as poor fits.

Headless loops with claude -p

To script your own loop, run Claude Code non-interactively with -p. It exits with code 0 on success and non-zero on failure, so a shell script can branch on the result. Print mode adds two caps that suit loops: --max-turns and --max-budget-usd.

A capped headless Ralph-style loop built from documented flags

while :; do
  claude -p "$(cat PROMPT.md)" \
    --max-turns 30 \
    --max-budget-usd 5.00 \
    --permission-mode acceptEdits || break
done
  • --max-turns limits agentic turns in print mode and exits with an error when the limit is reached. There is no limit by default.
  • --max-budget-usd stops the run once estimated spend reaches the amount. Spend can pass the cap, so leave headroom.
  • --output-format json includes total_cost_usd, which a script can add up across passes.
  • --continue or --resume carries one conversation across runs. A fresh call per pass gives each pass a clean context.
  • Setting a goal with -p runs the /goal loop to completion in one invocation.

Codex: /goal, codex exec and resume

Codex has a /goal command for one durable objective. OpenAI says Codex can then work independently for multiple hours and stops when it is confident it has reached the stopping condition. For scripts, codex exec runs Codex non-interactively.

Codex goal and exec

/goal <objective>
/goal pause
/goal resume
/goal clear

codex features enable goals

codex exec --sandbox workspace-write "<task>"
codex exec resume --last "fix the race conditions you found"
  • If /goal is missing from the slash command list, enable features.goals in config.toml or run codex features enable goals.
  • By default, codex exec runs in a read-only sandbox. Pass --sandbox workspace-write to allow edits.
  • --full-auto is no longer supported. Use --sandbox workspace-write instead.
  • Use danger-full-access only in a controlled environment such as an isolated CI runner or container.
  • codex exec requires a Git repository unless you pass --skip-git-repo-check.

Gemini CLI, Amp and Factory Droid

These agents have no documented built-in loop command, but each has a headless mode you can call from a shell loop.

  • Gemini CLI: headless mode starts with -p or --prompt, or in a non-TTY environment. Exit code 53 means the turn limit was exceeded.
  • Gemini CLI: model.maxSessionTurns caps turns in a session, and -1 means unlimited. model.disableLoopDetection turns off automatic infinite-loop detection, so leave it off.
  • Gemini CLI: YOLO mode, which auto-approves all actions, can only be enabled on the command line with --yolo or --approval-mode=yolo.
  • Gemini CLI: for unpaid tier and Google One users, Gemini CLI was replaced by Antigravity CLI on June 18th, 2026.
  • Amp: amp -x (--execute) sends a prompt, waits until the agent is done and prints its last message. Execute mode still exists in the rebuilt Amp CLI.
  • Amp: after the rebuild, Amp no longer asks for permission before running tools. The old --dangerously-allow-all behavior is the default for users who have not configured permissions.
  • Factory: droid exec runs a task without interactive mode. The default autonomy is read-only, --auto low, medium or high raises it, and -s continues a session.
  • Factory: --skip-permissions-unsafe skips all permission prompts, though command blocks still apply.

Headless one-shots you can wrap in a loop

gemini -p "<task>"
amp --execute "<task>"
droid exec --auto medium "run tests"

Cursor: cloud agents and long-running agents

Cursor runs long jobs in the cloud instead of in a local loop. Its help docs describe background agents, also called Cloud Agents, as coding agents that typically run for a very long time.

  • Each Cloud Agent runs on its own dedicated virtual machine, sandboxed and isolated from your local machine.
  • You control which repositories, secrets and network access an environment gets.
  • In February 2026 Cursor opened its long-running agents research preview at cursor.com/agents for Ultra, Teams and Enterprise users.
  • Long-running agents propose a plan and wait for approval before they start executing.

Safety checklist for unattended loops

  • Give every loop a hard stop: --max-iterations for the Ralph plugin, --max-turns for claude -p, or a turn clause in a /goal condition.
  • Cap spend with --max-budget-usd on claude -p, and track total_cost_usd from JSON output.
  • Run in a sandbox. codex exec defaults to read-only, and Cursor Cloud Agents run in isolated VMs.
  • Keep broad flags such as --dangerously-skip-permissions, danger-full-access, --yolo and --skip-permissions-unsafe for isolated runners or containers.
  • Write a completion condition the agent can prove in its own output, such as a test command exiting 0.
  • Remember that /goal can stop on its own: it clears on an exhausted credit balance or an authentication failure.

Get coding agent settings changes by email

When a setting, flag or permission rule in this guide changes, it goes in the weekly AgentAtlas update, checked against the vendor docs. One email a week.

Sources

Other guides

How to allow Cursor to run all commands: Run Everything, allowlist and sandboxHow to allow Claude Code to run all commands: permission modes, allow rules and skip permissionsClaude Code permissions: allow, ask and deny rules, rule syntax and allowed toolsCodex CLI: approval and sandbox modesGemini CLI: YOLO mode, auto_edit and allowing specific shell commandsCursor Privacy Mode: telemetry, training and data retentionClaude Code telemetry and data retention: what is sent and how to turn it offGemini CLI: turn off usage statistics and telemetryCLAUDE.md: where it goes, how it loads, and how it works with AGENTS.mdClaude Code hooks: format on save, block risky edits, get notifiedClaude Code subagents: create one, limit its tools, and call itAdd MCP servers to Cursor with mcp.json: Keep files out of Cursor with .cursorignore: Configure Codex with config.toml: Configure Gemini CLI with settings.json: Add MCP servers to Claude Code (claude mcp add, .mcp.json, scopes): Claude Code custom slash commands and skills (SKILL.md): GitHub Copilot custom instructions: Adding MCP servers to GitHub Copilot: Claude Code settings.json: file locations, precedence, and key settingsClaude Code plugins and marketplaces: install, create, and shareGemini CLI extensions and custom commands: Configuring OpenCode with opencode.json: Cline Rules: workspace, global, and conditional rulesKiro steering files: .kiro/steering, inclusion modes, and AGENTS.mdZed agent: instruction files, MCP servers, tool permissions, and ACP agentsCursor CLI: install, headless mode, permissions and CIAider: CONVENTIONS.md, .aider.conf.yml and API keysJunie guidelines, MCP and the Action Allowlist: Amp AGENTS.md, settings.json and MCP: Configure Goose extensions, hints, recipes and permissions: Customize OpenHands with skills, AGENTS.md, setup.sh and MCP: Configure Factory Droid CLI: AGENTS.md, settings.json, autonomy, custom droids and MCPConfigure Qwen Code: settings.json, providers, QWEN.md, MCP and approval modesCursor hooks: hooks.json, beforeShellExecution, afterFileEdit and exit codesCursor sandbox: sandbox.json, network allowlist and run modesCursor settings: settings.json, Cursor Settings and the ~/.cursor config filesCursor browser agent: @browser, browser automation and approval modesCursor subagents: .cursor/agents, frontmatter, built-in Explore and BrowserCursor telemetry and OpenTelemetry export (Privacy Mode, OTLP, Analytics API): Cursor rules setup: project, user and Team Rules, .mdc frontmatter, globs and AGENTS.mdClaude Code headless mode: claude -p, --output-format json, --bare and CI flagsClaude Code statusline: custom status bar in settings.json with context %, cost and git branchClaude Code /model: switch models, aliasesClaude Code /cost and /usage: check token spend, usage limits and reduce costsClaude Code VS Code extension: install, shortcuts, settings and /ideCodex AGENTS.md: global, project and override instruction files explainedCodex MCP servers: codex mcp add and [mcp_servers] in config.tomlCodex sandbox modes: read-only, workspace-write, danger-full-access and network accesscodex exec: run Codex non-interactively in scripts and CI with JSON outputCodex skills: create SKILL.md, skill folder locations and $skill invocationGEMINI.md in Gemini CLI: context file locations, imports and /memoryGemini CLI MCP servers: gemini mcp add and mcpServers in settings.jsonGemini CLI custom slash commands: TOML files, {{args}}, !{shell} and @{file}Gemini CLI headless mode: gemini -p, JSON output and exit codes for scripts and CIGemini CLI sandbox: enable Docker, Podman, macOS Seatbelt or gVisorcopilot-setup-steps.yml: set up the GitHub Copilot cloudGitHub Copilot CLI permissions: --allow-tool, --deny-tool, --allow-all-tools and trusted directoriesGitHub Copilot custom agents: .github/agents/*.agent.md profiles, tools and frontmatterGitHub Copilot code review settings: automatic PR reviews, rulesets, effort level and approvalsOpenCode MCP Server Setup: Local and Remote Servers in opencode.jsonOpenCode Permissions: Allow, Ask or Deny Bash, Edit and WebfetchOpenCode Custom Agents and Subagents: Markdown Files, Modes and @ MentionsCline MCP Setup: cline_mcp_settings.json for Local and Remote ServersCline Auto Approve and YOLO Mode: Run Commands and Edits Without PromptsCline Skills: SKILL.md Location, Format and Slash Command UseAmp MCP Setup: amp mcp add, amp.mcpServers and Workspace ApprovalAmp AGENTS.md: File Locations, @ Mentions and Glob-Scoped GuidanceAmp Skills: SKILL.md Folders, amp skill add and Search OrderKiro MCP Setup: .kiro/settings/mcp.json, autoApprove and OAuthKiro Hooks: .kiro/hooks JSON, PreToolUse, PostFileSave and StopKiro Permissions: permissions.yaml Allow, Ask and Deny RulesFactory Droid MCP Setup: droid mcp add, mcp.json Locations and /mcpFactory Droid Hooks: hooks.json, PreToolUse Matchers and Exit CodesFactory Droid Custom Droids (Subagents): .factory/droids Markdown FilesJunie MCP Setup: .junie/mcp/mcp.json for CLI and /mcp CommandJunie Brave Mode and Action Allowlist: Auto-Approve Commands in Junie CLIJunie Custom Slash Commands: .junie/commands Markdown Files and Argumentsgoose .goosehints and AGENTS.md: Global and Project Instructionsgoose Permission Modes: GOOSE_MODE auto, approve, smart_approve and chatgoose Recipes: recipe.yaml Format, Parameters and goose run --recipeZed Agent Tool Permissions: Auto-Approve Terminal Commands with tool_permissionsUse Claude, Codex and Gemini CLI in Zed: External Agents and agent_serversZed with Ollama, LM Studio and llama.cpp: Local Model Setup and Context LengthMCP 2026-07-28 Migration Guide: Stateless Protocol, No Sessions, server/discover, MRTR, and SDK v2 UpgradeSubagents and Custom Agents Compared: Claude Code vs Codex vs Cursor vs Gemini CLI vs GitHub CopilotAllow all commands in any AI coding agent: Cursor, Claude Code, Codex, Gemini CLI, Copilot CLI and 7 moreAdd an MCP server to any AI coding agent: Claude Code, Cursor, Codex, Gemini CLI, VS Code and 8 moreSettings file locations for every AI coding agent: Claude Code, Cursor, Codex, Gemini CLI, OpenCode, Qwen Code, Amp and Factory DroidRules and instruction files in every AI coding agent: .cursor/rules, CLAUDE.md, AGENTS.md, GEMINI.md, Copilot instructions and moreGemini CLI hooks: settings.json, BeforeTool, AfterTool, exit codes and /hooksGitHub Copilot hooks: .github/hooks/*.json for Copilot CLI and the cloud agentHooks in every AI coding agent: Claude Code, Cursor, Gemini CLI, GitHub Copilot, Kiro and Factory DroidAgent Skills (SKILL.md) in every AI coding agent: Claude Code, Codex, Cline, Amp and OpenHandsHow to deploy a remote MCP server (Streamable HTTP): Cloudflare Workers, Vercel, Railway and moreHeadless mode in every AI coding agent: claude -p, codex exec, gemini -p, Cursor agent -p and copilot -p for scripts and CIClaude Code sandbox: /sandbox, sandbox.enabled, allowedDomains, excludedCommands and strict modeSandbox modes in every AI coding agent: Claude Code, Cursor, Codex and Gemini CLI comparedCustom slash commands in every AI coding agent: file locations, arguments and examplesMigrate from Gemini CLI to Antigravity CLI (2026): Config, MCP, Skills, FlagsRun GitHub Copilot CLI with copilot -p in scripts and CI (2026):

Reviewed Oct 19, 2026. Settings change often; the linked vendor docs are the source of truth.