Skip to content
Giallo

Stop hook: loopless checks in Claude Code

Design a Stop hook with verifiable conditions, stop_hook_active and limits. Comparison between script, prompt and agent, with no invented results.

Reading time: 11 min

Claude Code Stop hook: event, control and result in development workflow

One Stop hook can check a condition when Claude Code finishes an answer and, if necessary, ask to continue. It is useful only if the condition has a proof and a term. "Form check has to be concluded" is verifiable; "it still improves the project" is not. Input includes stop_hook_active, which serves to recognize a continuation already provoked by the hook. Event Stop.

The end of an answer is not the same as delivering a project. The event does not itself certify testing, review or publication. The checker must know what to observe and how to handle missing errors or prerequisites. In the Guide to the Claude Code Hooks find the overview; this page focuses on the risk of repeated continuations.

Verified Sources on 9 October 2026. Examples are hypothetical and snippets have not been executed in this guide. No test results or automatic delivery coverage are declared.

In summary

  • Stop is an end-of-response moment, not an end-of-project test.
  • The condition must produce an observable outcome.
  • stop_hook_active should be handled before requesting more work.
  • Script, prompt, and agent check conditions in different ways.
  • An external block must be declared, avoiding endless requests.

What condition can a Stop hook control?

Choose a condition related to the current delivery. It may relate to a verification result, an out-of-scope change, or an out-of-date mandatory document. The criterion must identify the source of the evidence and the state to which it relates. A file with the word "success" is not enough if it can come from a previous edit.

Distinguishing evidence from the statement is essential. The text of the reply can say "tests pass", while the command has not been executed. A deterministic check must verify a real data; an evaluation of the text can at most judge what has been provided to it. They are different responsibilities, which should not be mixed in the same name as hook.

For feedback collected during edits consult PostToolUse for formatting and testing. The Stop hook can verify that a relevant result is available at the end, but does not retroactively transform an still-ongoing suite into a completed verification.

How does a continuation loop come about?

The problematic sequence is simple: Claude concludes, the hook asks to continue, Claude concludes again and the same hook repeats the request. If the condition does not change or cannot be met, the workflow consumes tasks without producing a new test. It can also happen with a seemingly reasonable request, such as running tests that depend on an unavailable service.

stop_hook_active indicates that the answer is already inside a continuation generated by the hook. The reference also documents a limit of eight consecutive continuations. This limit is a product protection; it should not be the normal output criterion of your automation. Stop decision control.

A check should decide first whether he is allowed to ask for more work, then assess the condition. If it waits to handle the guard after a new block request, it can repeat the error. The continuation message must also be precise: finished activity, proof to collect and way to report a real impediment.

A minimum guard for the second conclusion

The following Python script shows only the guard and a condition on a local signal. The file review.pending represents an educational convention of the project: is not a test test. The script has not been executed and should only be used to understand the contract. JSON of Stop.

import json
import os
import sys
from pathlib import Path

try:
    event = json.load(sys.stdin)
    if event.get("stop_hook_active"):
        sys.exit(0)
    root = Path(os.environ["CLAUDE_PROJECT_DIR"])
    pending = root / ".claude" / "review.pending"
    if pending.exists():
        print(json.dumps({
            "decision": "block",
            "reason": (
                "Leggi il criterio di review pendente e raccogli la prova. "
                "Se un prerequisito manca, dichiaralo nella risposta."
            )
        }))
except (ValueError, KeyError, OSError, AttributeError):
    print("Verifica finale non disponibile.", file=sys.stderr)
    sys.exit(1)

The first result can ask for an activity; the second lets it end. It is a conservative choice of example, not a comprehensive certification system. Do not suggest that you automatically delete the signal to "pass" the control: the meaning of the file and who can update it must be defined in the project.

A real system should use a structured verification status consistent with the current revision. The guard avoids a type of repetition, but does not prove that the task is correct. It is important to retain both statements when the check is handed over to the team.

Where to register control and how to prove it?

A minimal recording can call up the project script. The contract does not require a tool matcher because Stop is not about the name of an Edit or Bash call. Integrate this block into existing settings and verify the presence of the control in /hooks. Hooks Configuration.

{
  "hooks": {
    "Stop": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "python3 \"$CLAUDE_PROJECT_DIR/.claude/hooks/check_stop.py\""
          }
        ]
      }
    ]
  }
}

For a direct test, prepare two synthetic inputs: one with stop_hook_active fake and a real one. Add a case with pending signal and one without. The expected result must indicate decision, exit code and message. Then try the path in the session, without involving data or production services.

The presence of the recording is not enough. If the project requires a mandatory verification, also observe what happens when Python is not available or when the script receives malformed JSON. Debug of the Hooks helps to separate script errors and event behavior.

Script, prompt or agent: what's the difference?

A command hook can compare deterministic data and start a project program. A prompt hook uses a single model evaluation on the received context. An agent hook can collect information through additional tools and readings; the documentation indicates it as experimental. The choice depends on the necessary proof, not the prestige of the most complex form. Prompt and agent hook.

Shape Suitable Question Limit to be explained
Script Is there a valid result for this state? Must correctly interpret data
Prompt Does the received text meet a described criterion? No evidence of facts not present in context
Agent Should the proof be searched in files or tools? Requires work, latency and boundaries
Stop hook without loop
illustrative diagram: Stop hook without loop. Arrows represent links and process controls; not measured results.

A model may evaluate a motivation, but it does not automatically make the statement contained in the motivation true. If the requirement is "really performed test", the test result must be read. If the requirement is "understanding explanation", the evaluation of the text may be relevant.

For a wider review you can read Claude Opus for Code Revision. The revision remains a collection of evidence on the code, with clear limits, and not a promise of total absence of problems.

How to write a finite continuation request?

The request should identify the concrete action: reading a diff, collecting the outcome of a command or correcting a specific error. It must indicate what counts as proof and what to do if the condition is not satisfactory. "Run the module suite if prerequisites are available; otherwise report which ones are missing" produces a useful outcome in both cases.

Do not use absolute criteria such as "no bugs possible" or "best solution". They are impossible to verify with a finite check. Even "all tests" are ambiguous if the repository has local, integrated, and service-dependent suites. Identify which controls belong to the change and which are mandatory before delivery.

The request must also comply with the job authorization: do not transform a final verification into an automatic submission, publication or access to an external system. If the test requires an unavailable action, the final response can describe the limit exactly. The loop should not be used to circumvent a human decision.

How to manage background tests and has been passed?

A suite started in the background may still be in progress when Claude concludes. The Stop hook must distinguish a pending state from a failure and success. Do not use the absence of errors in the text as proof that the process is over. The control must know the result of the command, or ask to collect it through an explicit path.

If relevant files have been modified after the suite, its result may not validate the current version. A project may retain an identifier of the audit, diff or verified status, as long as the criterion is documented. An identifier alone is not enough: it must be connected to the command and its outcome.

PostToolUse in background describes the previous part of the flow. SessionStart and compaction helps to preserve the state when the session resumes. The two automations can collaborate, but must read the same meaning of "verification concluded".

When does the block depend on something outside the project?

Missing login, an unreachable database, a test environment that has not started or a missing business decision cannot be resolved by repeatedly asking “continue”. The hook must produce a readable category of blocker. The response can indicate which check was completed, which did not start and what makes it unavailable.

This allows you to finish independent activities. If an integrated test is not available, the project can still collect relevant unit tests and reviews, without declaring the integration complete. The final check should not reduce the broom silently, but preserve the exact distinction between verified result and missing part.

A condition that must not generate another iteration

The check requires an authenticated service, but the session does not have the necessary login. The answer must record the missing prerequisite and the unexecuted check. Repeating the request does not provide authentication and does not produce additional proof.

If you need a warning to call you back to a decision, use the Local Notifications with a neutral message. A banner helps to see the moment, without changing the meaning of the block.

Two final checks in Italian reality

Hypothetical, untested example: a software house in Bari modify a quotation calculator. Before the final answer he wants a result of the relevant tests and a reading of the diff. The Stop hook detects a missing piece of evidence and only asks for one continuation. If the suite fails, Claude can correct the problem and repeat the check; if the runtime is not available, the answer declares the impediment instead of endless iteration.

Hypothetical example, untested: a cooperative in Modena experiment with a report generator with dummy data. Delivery requires checking that the sample file is created and that the response bears the limits of the demo. A prompt hook can assess the presence of the warning in the text, while the existence of the file requires a separate proof. The team does not confuse the quality of the explanation with the successful execution of the generator.

The two cases clarify why a Stop hook must have a recognizable responsibility. The same automation cannot indistinctly certify correctness of calculation, availability of a service and clarity of a report without criteria and specific tests.

What errors turn verification into noise?

The most frequent are not reading stop_hook_active, ask for impossible tasks, trust text-only response, use results from a previous review and add verifiers that invoke other verifiers without a limit. A model cost or latency should not be presented as negligible without a workflow measure: prompts and agent hooks produce additional work.

In a delegated stream, Hooks for subagent and team distinguishes Stop, SubagentStop and TaskCompleted. The end of the coordinator's response should not be used as a synonym for the outcome of each task. If the control calls a service, HTTP Hooks adds the issue of errors and the JSON decision.

The Official Example Security guidance shows checks distributed at different times of the job. Read it with its prerequisites: an additional control does not replace a project pipeline and a change review ready for delivery.

Who can update the completion test?

If the control reads a status file, the project must define who updates it and based on what result. The agent should not be able to turn a pending verification into a positive just to end the response. An outcome must result from the relevant command or review.

Even a valid proof can be passed by a new edit. The criterion must know this possibility and state when it is necessary to repeat the check. The responsibility for the result remains in the project process, not in the name of the file that contains the status.

How to know if the Stop hook is maintainable?

Prepares a matrix with satisfied condition, missing proof, already active continuation and unavailable prerequisite. For each case describe what needs to happen and what result needs to be shown. A policy change requires updating this matrix, not just the hook prompt.

For a small control, a clear script may suffice. When you need tools or a new interface, compare Mods by Claude before adding complexity. The mechanism should be chosen because it collects the necessary evidence, not because it generically promises more autonomy.

The design of AI agents may include completion criteria, iteration limits, and block management. A good Stop hook makes the end of the job more readable: finished question, available proof and precise statement of what remains to be verified.

Giallo Studio guides: methodology and sources

How we apply it in the company

Related resources

AI consulting services and process automation

FAQ

What does a Stop event control?

It fires when Claude finishes a response. It can allow Claude to finish or ask it to continue, depending on the result and the event contract.

What is stop_hook_active for?

It indicates that the continuation already comes from a Stop hook. The script must handle this case to avoid repeatedly requesting the same work without a limit.

Is it enough to say that the tests pass?

No. The check must have an observable result relating to the current change. A statement in the text does not replace running the check or reading the evidence.

When to use a prompt hook?

When it is necessary to evaluate a condition by reading the received context. The evaluation has a model cost and does not amount to a deterministic test.

When to use an agent hook?

When the check requires further reading or tools. It is an experimental feature and should be designed with clear limits on work and latency.

Can Stop handle an external block?

It can report it, but must not turn it into an endless request to continue. Logins, unavailable services or missing decisions require an explicit outcome.

Put it into practice

Let's turn this guide into your first live workflow.

Tell us what process you want to lighten: we evaluate feasibility, return and first operational step.