Stop Policies for AI Agents: How to Break Out of Repetitive Task Loops

    AI agents and coding tools often keep calling tools without making progress. They may retry a failed search or repeat a check after the target is already found. This article explains why these loops happen and how to stop them. For end users, it covers how to define completion, retry, and stop conditions in a task. For developers, it covers how to enforce these rules in the execution control layer, using progress tracking, action deduplication, bounded retries, and multi-dimensional budgets.

    1. Running Is Not the Same as Making Progress

    When you use an AI coding tool or an automated agent, you may see a confusing pattern. You ask it to find a file, and it runs the same search several times without success, yet it keeps searching. Or it finds the file, then repeats the lookup several times without returning the result.

    These two behaviors correspond to two problems: ineffective retries after failure, and repeated confirmation after success. On the surface, the agent keeps calling tools and analyzing results. In practice, it gains no new information that moves the task forward.

    The core issue is not the loop itself. The issue is that the loop has no clear exit condition.

    The most effective fix is to write stop conditions as executable task rules, rather than relying on the model to decide on its own when to finish.

    For individual users, add retry limits and completion criteria to the task description. For developers, enforce these rules in the execution control layer, and check them before and after each tool call.

    2. Why Agents Need Loops

    A plain question-and-answer exchange usually requires only one generated response. An agent, however, must take a sequence of actions. A typical task loop looks like this:

    Understand the goal → choose an action → call a tool → read the result → update the state → decide the next step.

    For example, locating a configuration file may require checking the working directory, searching for the target file, and then verifying that its contents meet the requirements. Each step depends on the result of the previous one, so the loop must run in sequence.

    However, completing a tool call does not mean the task has advanced. The following actions may look different but add nothing new:

    • Searching the same directory again for the same file name;
    • Rewording the same query and running it again;
    • Retrying after the same error without changing parameters, permissions, or the environment;
    • Adding the same verification after the required result has already been obtained.

    For this reason, the number of loop iterations is not a measure of how much work was done. A more useful question is whether the current iteration added new evidence, resolved an uncertainty, or completed a clear sub-goal.

    3. Two Kinds of Repetition Need Different Handling

    1. Repeated Failures: The Conditions Did Not Change, but the Agent Expects a Different Result

    Suppose a task asks the agent to find a file in a specified directory. The first search returns “not found.” A reasonable next step would be to check whether the path is correct, whether a subdirectory was missed, or whether the current identity has access permission.

    If none of these conditions have changed, running the same query again is unlikely to succeed.

    However, “not found” does not automatically mean “the file does not exist.” It may also indicate:

    • The search scope does not include the target location;
    • The file name differs in case, extension, or encoding;
    • Insufficient permissions hide some directories;
    • The query is too strict;
    • A remote index or data sync has not finished.

    The right approach is to identify the type of error first, then decide whether to retry. What should be stopped is the repeated action that lacks a new basis, not every follow-up action after a failure.

    2. Repeated Success: Missing Completion Criteria Cause Endless Self-Confirmation

    A second type of waste is less obvious. The tool has already returned the target file, but the agent still runs the same query again.

    This usually happens because the task has an action request but no acceptance criteria. A request like “Help me find the file” does not specify whether it is enough to find the path, or whether the agent must also confirm that the file is readable, has valid content, and is the correct version.

    If the completion criterion is “find a file that is located in the specified directory, has an exact name match, and can be read,” then the search should end once all three conditions are met.

    Note that necessary verification is not the same as a repeated query. For example, reading the top of a file to confirm that it is the target configuration adds new evidence. Returning the same path again usually adds no value.

    4. Will the Execution Framework Stop the Loop Automatically?

    The orchestration and execution control layer around an agent usually manages model calls, tool execution, state logging, and loop scheduling. It can set turn limits, timeouts, error handling, and resource budgets. Which of these features exist depends on the implementation.

    Therefore, it is wrong to assume that an execution framework will retry endlessly, and it is equally wrong to assume it will detect every useless action.

    “Maximum number of execution turns” and “detecting that a task is stuck in a loop” are two different things.

    The first answers: “How long can the whole task run at most?”

    The second answers: “Is the current action still worth executing?”

    A task may stay in a repetitive loop well before it reaches the total turn limit. Conversely, a task with many steps that keeps making progress should not be treated as abnormal just because it makes many calls.

    In addition, reaching the context limit, running out of account quota, or failing a tool execution are not ideal stopping mechanisms. They are resource boundaries or abnormal exits, and they cannot replace active task control. Different systems may handle these cases by truncating, compressing, or raising errors. Do not assume that any one of these behaviors is shared by all agents.

    5. The Most Practical Stop Rule: Define Completion, Retry, and Stop

    A clear set of task constraints should answer at least four questions:

    1. What counts as completion?
    2. When is a retry allowed?
    3. When must the agent stop?
    4. What should the agent deliver to the user after stopping?

    Take file search as an example. The task description could read:

    Search for the target file within the directory scope specified by the user. Once a file with a matching name that can be read is found, return its path and any necessary verification results, then end the search. If the first search finds nothing, check the path and search conditions. Continue querying only if there is a clear new hypothesis. Do not run queries that add no new information for the same scope and conditions. If progress stays stalled for the preset number of attempts, stop and report the areas checked, the current conclusion, and the information needed from the user. Do not expand the search into other sensitive directories without authorization.

    Instructions like this work better than “Don’t waste tokens” or “Finish as quickly as possible,” because they turn abstract requirements into observable behavior constraints.

    However, prompt instructions are still soft constraints. A model may miss a requirement or misjudge whether progress was made. Systems that must run reliably also need hard limits in the control layer.

    6. Implementing Stop Policies as Execution Logic

    1. Create Comparable Identifiers for Actions

    To detect repeated calls, do not compare only natural-language descriptions. Compare the actual execution semantics.

    An action identifier can be built from the following elements:

    action type + target resource + normalized parameters + relevant environment version.

    For example, the same search scope, the same target file name, and the same filter conditions can be grouped as the same query. A change in spacing, parameter order, or wording should not automatically count as a new action.

    However, environmental changes must be taken into account. If a file was just generated, permissions were just updated, or external data was just refreshed, querying again with the same parameters may be reasonable.

    Repetition checks should therefore consider two things: whether the action is the same, and whether the preconditions for executing it have changed.

    2. Sort Results Into Distinct States

    Tool outputs should not all be collapsed into a vague “failed” status. At a minimum, distinguish between:

    • Goal satisfied: End the current step and move on to delivery or the next sub-task;
    • Clear precondition error: Correct the path, permissions, or input before running again;
    • Possibly recoverable temporary error: Retry a limited number of times within the attempt and time budgets;
    • Insufficient evidence: Run a targeted additional check, or ask the user for clarification;
    • No new information: Count it as a step without progress, and stop once the threshold is reached.

    These states describe a general design approach. In a real implementation, they should be refined based on the structure of tool responses and the business logic.

    3. Use a Budget for Consecutive Steps Without Progress

    A total turn limit serves only as a final safety net. A more direct method is to add a budget for consecutive steps without progress. The pseudocode below is an illustration of the logic. The names are for explanation only and do not represent any specific API.

    1. Initialize task state
    2. Initialize total budget
    3. Initialize consecutive no-progress count = 0
    4. Loop:
    5. If the task completion condition is met:
    6. Output the result and end
    7. If the total budget is exhausted:
    8. Output partial results and the reason for stopping
    9. End
    10. Plan the next action
    11. If the action is a repeat and the relevant environment has not changed:
    12. Block the action
    13. Request new grounds for execution, or end the current branch
    14. Execute the action
    15. Classify the result
    16. If the result produces a meaningful change in task state:
    17. Consecutive no-progress count = 0
    18. Else:
    19. Consecutive no-progress count += 1
    20. If the consecutive no-progress count reaches the threshold:
    21. Output known facts, open issues, and recommendations
    22. End

    The key point is that “meaningful change” must be defined in terms of the task. Finding a new path, confirming that a directory is inaccessible, or completing a content check can all count as progress. Generating new analysis text does not necessarily count.

    The threshold should not be the same for every task. A simple local read-only query can use a strict threshold. A remote task with a clear asynchronous completion process may need a longer wait and a different retry strategy.

    7. Retries Can Help With Temporary Errors, but They Need Limits

    Network fluctuations, brief rate limiting, and resources that have not finished initializing can sometimes be resolved by retrying. In these cases, the system should not block an action just because it is the same as an earlier one.

    A sound retry strategy should include:

    • A clear classification of retryable errors;
    • A maximum number of attempts;
    • An upper limit on total wait time;
    • Increasing wait intervals, with random jitter if needed;
    • Immediate termination of retries after success.

    For actions with side effects, such as writing data, deleting records, or sending notifications, idempotency also matters. A request that times out has not necessarily failed. The operation may have succeeded. Running it again without checking can create duplicate data or duplicate notifications.

    For this reason, after a timeout on an action with side effects, the system should usually query the actual state first, or rely on deduplication at the business layer, before deciding whether to retry. Saving tokens matters, but avoiding duplicate changes to business state matters more.

    8. Budgets Should Not Only Count Tokens

    Repetitive loops consume more than model generation resources. They also use tool execution time, external API quotas, storage access, and the user’s waiting time.

    Consider setting the following limits at the same time:

    • Total execution time: Prevent a task from occupying resources for too long;
    • Model call budget: Control the cost of inference and generation;
    • Tool call count: Limit high-cost operations;
    • Repeat count per action: Stop local loops;
    • Consecutive steps without progress: Detect loops that make no real progress;
    • High-risk operation count: Limit actions that have side effects.

    When a budget runs out, do not return only “execution failed.” A more useful output reports what has been completed, which results are reliable, where the task is blocked, and what conditions are needed to continue.

    The relationship between token usage and actual cost or platform quota depends on each provider’s billing rules. Do not assume that every environment deducts usage at the same rate.

    9. How to Verify That a Stop Mechanism Works

    Before deployment, prepare test scenarios built for stopping behavior, not just for successful task paths.

    At a minimum, cover the following cases:

    1. The target file does not exist;
    2. The file exists, but the directory configuration is wrong;
    3. The file exists, but permissions are insufficient;
    4. The first call fails with a temporary error, then recovers;
    5. The first query already succeeds;
    6. The external environment changes, so the query must run again;
    7. An operation with side effects times out, but actually completed.

    Focus on three things: whether the system avoids unnecessary repetition, whether it stops tasks that could still make progress by mistake, and whether the explanation it gives after stopping is clear enough.

    Monitoring can track metrics such as the share of repeated calls, the length of consecutive no-progress runs, redundant calls after success, and the reason each budget was triggered. Logs should keep action summaries and the evidence for state changes, while avoiding unnecessary sensitive content.

    10. Summary: A Reliable Agent Must Know When to Stop, Not Just How to Run

    Agents can complete tasks across many steps because of loops. The same loops also waste resources when they have no clear boundaries.

    Effective optimization does not mean simply asking the model to “think less.” It means building a complete control loop:

    Use completion criteria to end successful tasks, use error classification to guide retries, use state changes to judge progress, use repetition detection to block idle loops, and use multi-dimensional budgets as the final safeguard.

    For users, write when a task counts as complete, how many attempts are allowed, and how failures should be reported. For developers, turn these constraints into execution rules that can be tested and observed.

    An agent should continue when there is evidence, pause when there is no basis for progress, and deliver results promptly once the task is done. That is how it reduces wasted effort and becomes more reliable.