How to Use the /goal and /loop Commands in Claude Code for Autonomous Long-Running Tasks
Combine /goal and /loop in Claude Code to create tasks that run on a schedule and won't stop until your end condition is met. Here's how to set it up.
Why Long-Running Tasks in Claude Code Often Stall
Anyone who’s tried to use an AI coding agent for something that takes more than a few minutes has hit the same wall. You set up a task, Claude Code starts working, and then — it finishes one piece, asks if it should continue, waits for your input, and the whole autonomous promise falls apart.
That’s where the /goal and /loop commands in Claude Code come in. Together, they let you define a persistent objective and keep Claude running until it’s met — without you sitting there approving each step. This guide covers exactly how to use them, how to combine them effectively, and where things go wrong.
What the /goal Command Actually Does
The /goal command tells Claude Code what you’re ultimately trying to achieve — not just what to do next, but what “done” looks like.
When you issue a /goal, you’re setting a persistent target that Claude keeps in mind across every step of its work. Without a goal, Claude operates instruction by instruction. With one, it evaluates each action against whether it’s moving toward the end state you defined.
How to Issue a /goal
The syntax is straightforward:
/goal <your end condition>
For example:
/goal All TypeScript files in /src pass lint with zero errors and all unit tests return green
Or something more open-ended:
/goal The README accurately documents every public function in the codebase
Other agents start typing. Remy starts asking.
Scoping, trade-offs, edge cases — the real work. Before a line of code.
The goal should describe a verifiable end state, not a process. “Refactor the code” is a process. “Every function has a JSDoc comment and no function exceeds 40 lines” is a verifiable end state. The more concrete the condition, the better Claude can evaluate whether it’s been met.
What Claude Does With a Goal
Once a goal is set, Claude uses it as a reference point when deciding what to do next. It checks whether the current state satisfies the goal condition after each significant action. If it doesn’t, it figures out what’s still missing and continues working toward it.
This is meaningfully different from just writing a long prompt. A goal persists across the session and shapes Claude’s reasoning at every step, rather than just priming its first response.
What the /loop Command Does
The /loop command tells Claude Code to keep executing in a cycle rather than stopping after completing a single pass.
By default, Claude Code finishes a task and waits. The /loop command changes that behavior — Claude will complete a cycle, assess the state of things, and then start again unless a stop condition is met.
Basic /loop Syntax
/loop [interval] [until: <condition>]
You can run a loop on a fixed schedule:
/loop every 10m
Or tie it to a condition:
/loop until: all tests pass
Or combine both:
/loop every 5m until: deployment succeeds
The interval controls how often Claude checks in and acts. The until condition tells it when to stop. If you don’t specify an until condition, the loop runs indefinitely until you manually stop it or exit the session.
Loop vs. Just Running Claude Multiple Times
The difference isn’t just convenience. When Claude operates in a loop, it has continuity — it remembers what it tried, what failed, and why. Each iteration builds on the last. Re-running Claude from scratch each time loses that context and often results in Claude repeating the same failed approaches.
A loop with a goal is particularly powerful because Claude isn’t just repeating the same steps. It’s evaluating what still needs to happen to satisfy the goal and taking targeted action on that delta.
Combining /goal and /loop for Autonomous Tasks
This is where things get useful. Used together, /goal and /loop create a self-directing, self-terminating agent loop.
The basic pattern:
- You define what “done” looks like (
/goal) - You tell Claude to keep working until it gets there (
/loop until:) - Claude runs, checks, runs again, until the goal condition is satisfied
- It stops on its own
Here’s a practical example for a CI failure scenario:
/goal All GitHub Actions workflows pass on the main branch
/loop every 3m until: CI passes
Claude will check the current CI status, identify what’s failing, make a fix, push the change, wait for CI to run, and then check again. It does this on a 3-minute cycle until all checks are green — then it stops.
A Step-by-Step Setup
Step 1: Open Claude Code in your project directory
claude
Step 2: Set your goal
Be specific. Vague goals produce vague work.
/goal Every endpoint in the API returns a response matching its OpenAPI spec
Step 3: Give Claude the context it needs
Other agents ship a demo. Remy ships an app.
Real backend. Real database. Real auth. Real plumbing. Remy has it all.
Before starting the loop, point Claude at relevant files, docs, or previous error outputs. The more context you front-load, the less likely it is to spin in circles.
Step 4: Start the loop
/loop every 5m until: all endpoints validated
Step 5: Let it run
Claude will work through the task, report status after each cycle, and stop when the goal is met. You can check in any time, but you don’t have to hover.
Practical Use Cases
Automated Test Fixing
Set a goal to get all tests passing, loop until they do. Claude will read failing test output, trace the cause, make changes, re-run tests, and repeat.
/goal All tests in the test suite pass without skips or warnings
/loop every 2m until: tests pass
This works especially well when failures have clear error messages Claude can act on. Flaky tests or environment-specific failures are harder — Claude may correctly identify the issue but not be able to fix it (a flaky network dependency, for instance). In those cases, it will tell you.
Documentation Generation
/goal Every exported function and class has accurate JSDoc comments reflecting its current implementation
/loop until: documentation coverage is complete
Claude will go file by file, check for missing or outdated docs, write them, and move on. When all files are covered, it stops.
Dependency and Security Audit
/goal No known high or critical severity vulnerabilities in package.json dependencies
/loop every 30m
Without an until condition, this runs indefinitely on a schedule — useful for ongoing monitoring during a development sprint where you’re regularly adding packages.
Migration Tasks
If you’re migrating from one pattern to another across a large codebase:
/goal All components use the new design system tokens and no legacy style imports remain
/loop until: migration complete
Claude will find remaining legacy usage, migrate it, verify, and continue until none is left.
Setting Up Scheduled Loops
For tasks that should run on a recurring schedule — not just until a one-time goal is reached — the interval-based loop is the right tool.
/loop every 1h
Combined with a goal, this creates a periodic health-check agent:
/goal The staging environment is running the latest build from main with all health checks passing
/loop every 30m
Every 30 minutes, Claude checks whether staging is up to date and healthy. If it’s not, it takes action. If it is, it waits for the next cycle.
Keeping Loops Bounded
Unbounded loops can run up API costs quickly. A few ways to keep them in check:
- Always use an
untilcondition when possible - Set a maximum number of iterations with
/loop max: 20 - Use longer intervals for tasks that don’t need frequent attention
- Review the cost display with
/costbefore starting a long-running loop
Common Mistakes and How to Avoid Them
Vague Goal Conditions
The most common failure mode. If Claude can’t objectively evaluate whether the goal is met, it may declare success early or keep running indefinitely.
Too vague:
/goal The code is clean and well-organized
Better:
/goal ESLint reports zero errors, no function exceeds 50 lines, and all files have consistent import ordering
Missing Context Before the Loop
- ✕a coding agent
- ✕no-code
- ✕vibe coding
- ✕a faster Cursor
The one that tells the coding agents what to build.
If Claude doesn’t know your project structure, conventions, or constraints before the loop starts, it’ll make assumptions. Some of those will be wrong, and correcting them mid-loop is disruptive.
Spend a few turns before starting a loop to orient Claude: show it relevant files, explain naming conventions, describe the architecture. Then start the loop.
Setting Intervals Too Short
A 30-second loop that involves running a full test suite will overlap with itself or exhaust API rate limits. Match your interval to how long each cycle actually takes to complete.
If you’re not sure, start with a longer interval and shorten it if needed.
Not Reviewing the First Cycle
Watch the first iteration of any new loop. Claude’s initial interpretation of the goal and context will shape everything that follows. If it starts down the wrong path, stop it, correct course, and restart.
Forgetting to Stop
If you walk away from a session with an indefinite loop running, it will keep running. Check /status before leaving a session. Use /cost to see cumulative spend.
How MindStudio Fits Into Autonomous Agent Workflows
Claude Code’s /goal and /loop commands are powerful inside a coding environment, but they operate within the bounds of a terminal session. When you need autonomous agents that run on a persistent schedule, trigger from external events, or coordinate across multiple tools — a different layer is useful.
MindStudio lets you build background agents that run on a defined schedule or trigger, connect to 1,000+ business tools, and execute multi-step workflows without you being present at all. It’s a no-code environment, so you’re configuring logic rather than writing infrastructure.
One specific connection to what you’re doing in Claude Code: if you’re using Claude Code for local development tasks and want to extend that pattern into production systems — think automated content pipelines, data sync agents, or CI notification workflows — MindStudio’s autonomous background agents are built exactly for that. You define the schedule, the goal condition, and what to do at each step, and the platform handles execution, retries, and error handling.
For developers who want even tighter integration, MindStudio’s Agent Skills Plugin is an npm SDK that lets your Claude Code agent call MindStudio capabilities directly — things like sending emails, searching the web, or triggering a full workflow — as simple method calls from within an agentic loop.
You can try MindStudio free at mindstudio.ai.
Troubleshooting Stuck or Misbehaving Loops
The Loop Keeps Running Past the Goal
Claude’s evaluation of the goal condition may be too conservative. Either the goal description is ambiguous, or Claude is checking a proxy for the condition rather than the condition itself.
Fix: Restate the goal with a more specific, directly checkable condition. If the goal involves running a command (like a test suite), tell Claude explicitly which command to run to verify.
Claude Is Making Changes That Break Other Things
This usually means the goal is too narrow. If you say “make the linter happy” without specifying “without breaking tests,” Claude may satisfy the linter by removing code.
Build guardrails into the goal:
/goal ESLint passes with zero errors AND all existing tests continue to pass
The Loop Exits Before the Goal Is Met
Claude may have concluded it can’t make progress — it hit a dead end, a permission issue, or a dependency it can’t resolve. Check the session output for the last few cycles to see what stopped it.
High Unexpected Costs
Check /cost to see token usage per cycle. If costs are high, the context window may be growing too large. Use /compact to compress conversation history before starting a loop, and consider breaking a large goal into smaller, sequential goals.
FAQ
What is the /goal command in Claude Code?
The /goal command sets a persistent objective that Claude Code works toward across an entire session. Instead of Claude completing a single instruction and stopping, a goal gives it a verifiable end state to reach. Claude evaluates each action against the goal and keeps working until the condition is met or it determines it can’t proceed further.
What does /loop do in Claude Code?
The /loop command tells Claude Code to operate in repeating cycles rather than completing a single pass and waiting. You can run loops on a schedule (/loop every 10m), tied to a completion condition (/loop until: tests pass), or both. Combined with /goal, loops allow Claude to autonomously pursue an objective over time.
Can I use /goal and /loop together?
Yes — combining them is the intended pattern for autonomous long-running tasks. /goal defines what “done” means; /loop keeps Claude working toward it until that condition is satisfied. When Claude determines the goal has been met, the loop exits automatically.
How do I stop a running loop?
You can interrupt a running loop at any time by pressing Ctrl+C in the terminal or typing a message into the session. Claude Code will pause and await your input. You can then modify the goal, adjust the loop parameters, or end the session.
Are there costs associated with long-running loops?
Yes. Each loop cycle uses tokens, and long or frequent loops can accumulate significant API costs. Use /cost to monitor spend during a session. Bounded loops with clear until conditions are more economical than indefinite loops. The /compact command can reduce token usage by compressing conversation history.
What kinds of tasks work best with /goal and /loop?
Tasks that are well-suited tend to be: iterative (requiring multiple passes), verifiable (you can check whether they’re done), and bounded (there’s a realistic end state). Test fixing, documentation generation, dependency audits, code migration, and CI maintenance are all strong fits. Tasks that rely on ambiguous human judgment or require external approvals are harder to automate this way.
Key Takeaways
/goaldefines a persistent, verifiable end state for Claude Code to work toward — not just a task to complete, but a condition to satisfy./loopkeeps Claude running in cycles until a stop condition is met, either time-based, event-based, or both.- Combined, they create a self-directing agent loop that exits when the goal is achieved.
- Specific, checkable goal conditions outperform vague ones every time.
- Monitor the first cycle of any new loop and set cost controls before walking away from long-running tasks.
- For production-grade autonomous agents that run on a persistent schedule and connect to external tools, MindStudio extends this pattern beyond a local terminal session.
