Boucle Claude Code : la skill loop-guard qui empêche un agent de se répéter

Dmitriy Solodukha, développeur de Caprock · Publié le

Testé le sur Claude Code et Codex

Claude Code répète une étape en échec ? La skill gratuite loop-guard l'arrête, nomme l'hypothèse erronée et change d'approche.

Lorsque Claude Code est bloqué dans une boucle (la même commande échoue, la même erreur revient après chaque « correction », un fichier est modifié puis rétabli), la skill loop-guard fait arrêter l'agent, lui fait énumérer ses tentatives, identifier l'hypothèse commune à chacune et essayer une approche qui teste une autre hypothèse, ou vous demander. Il s'agit d'un seul fichier SKILL.md pour Claude Code, Codex, OpenCode et Cursor, gratuit sous Apache-2.0.

Installer la skill loop-guard

Une commande par agent. La skill se résume à un seul SKILL.md ; rien ne s'exécute à l'installation.

Les neuf skills dans un plugin. Saisissez ces commandes dans Claude Code :

Ou cette skill seule, depuis le dossier de votre projet dans un terminal :

Ajoutez -g pour l'installer pour tous les projets.

Prompts utilisant la skill loop-guard

L'agent choisit la skill lorsque vos mots correspondent à sa description ; la nommer permet de s'en assurer. Cliquez sur un prompt pour le copier.

Comment la skill loop-guard interrompt une boucle Claude Code

La skill donne à l'agent un moyen de détecter une boucle et une procédure pour en sortir :

  • Le test. La même commande avec la même entrée a échoué deux fois ; la même erreur est revenue après une deuxième correction ; un bloc de modifications est modifié puis rétabli ; deux corrections alternent ; une interrogation ne montre aucun changement. Exécuter quelque chose deux fois est normal si quelque chose a changé entre-temps.
  • S'arrêter, puis examiner. Pas de « encore un essai ». L'agent lit la dernière erreur en entier et liste chaque tentative avec son résultat exact.
  • Le rapport de boucle. Ce qui se répète, les tentatives, l'hypothèse erronée et l'étape suivante. L'hypothèse erronée est la ligne qui compte : toutes les tentatives d'une boucle reposent sur une même conviction.
  • Un véritable changement d'approche, dans l'ordre : lire le code au lieu de l'exécuter, vérifier l'environnement, réduire le cas d'échec, revenir au dernier état fonctionnel, remettre en question le test ou la tâche. Une tentative avec la nouvelle approche, puis une évaluation.
  • Demander lorsqu'il ne reste aucune approche, ou lorsque les seules « corrections » restantes masqueraient le problème.

Ce que nous avons exécuté et ce que les agents ont fait

Chaque skill a été exécutée le 29 novembre 2026 dans un dépôt jetable créé pour elle, où elle était installée en tant que skill de projet. Un petit dépôt Python dans lequel tests/test_slug.py plaçait tests/ avant src/ dans sys.path, ce qui importait une copie obsolète du module (tests/textkit/slug.py) et rendait toute modification de src/textkit/slug.py sans effet. Un NOTES.md, rédigé à la main pour le test, recensait quatre tentatives d'un « agent précédent », chacune se terminant par le même AssertionError.

Claude Code (claude -p --model sonnet)

My agent is stuck in a loop: it keeps editing src/textkit/slug.py and rerunning python3 tests/test_slug.py, same error every time (see NOTES.md). Break the loop and fix it. Say which skill you used, if any. Answer in English.

Deux exécutions. Toutes deux ont invoqué loop-guard, appelé loop_alerts de Caprock, affiché le fichier réellement importé par le test et corrigé l'ordre de sys.path dans le test, sans modifier l'assertion ni src/textkit/slug.py. Le test a réussi. Toutes deux ont demandé avant de supprimer l'ancien dossier tests/textkit/, car git le suit. Le prompt de la première exécution ne se terminait pas par « Answer in English. » Le rapport de boucle de la seconde exécution :

Loop detected: editing src/textkit/slug.py and rerunning python3 tests/test_slug.py, same AssertionError
Attempts (1-4 are from NOTES.md):
  1. Ran the test -> 'hello_world' != 'hello-world'
  2. Edited the regex in src/textkit/slug.py -> same error
  3. Rewrote slugify with str.replace -> same error
  4. Reverted step 3 -> same error
Assumption that was wrong: the test imports src/textkit/slug.py
Next (done): fixed the import path in the test

Codex (0.163.0, codex exec -s workspace-write, le 30 novembre 2026)

The slug test still fails and I've tried fixing src/textkit/slug.py three times. Fix it.

A trouvé et lu .agents/skills/loop-guard/SKILL.md, appelé loop_alerts de Caprock, puis corrigé tests/test_slug.py pour charger src/ en premier, sans modifier l'assertion ; le test a réussi et git diff --check était propre. Son rapport commençait par la ligne de boucle, mais omettait les tentatives et la ligne sur l'hypothèse erronée du format de la skill (lien affiché en texte brut) :

Loop detected: three source edits failed because the test imported the old `tests/textkit/slug.py` copy.
Fixed tests/test_slug.py to load `src` first. The assertion is unchanged.
`python3 tests/test_slug.py` passes, and `git diff --check` is clean.

Agents sur lesquels elle a été testée

  • Claude Code : testé le 29 novembre 2026 avec claude -p --model sonnet, la skill étant installée comme skill de projet dans .claude/skills/.
  • Codex : testé le 30 novembre 2026 avec Codex 0.163.0 (codex exec), la skill étant dans .agents/skills/. Une exécution antérieure de Codex le même jour n'avait aucune skill installée et n'est pas comptabilisée.
  • OpenCode et Cursor : non testés. La skill est constituée de simples instructions au format ouvert Agent Skills, mais aucune exécution sur l'un ou l'autre ne l'a vérifiée.

Limites

  • La skill s'appuie sur ce que l'agent peut voir. Si une boucle s'étend sur plusieurs sessions ou si l'agent ne la remarque pas, vous devez lui dire « you're in a loop ».
  • Sans Caprock, elle reconstitue les tentatives à partir de la session elle-même ; une conversation compactée peut avoir perdu les premières.
  • Elle ne limite pas le nombre de tentatives et ne tue aucun processus. Une skill n'arrête pas un agent qui ignore ses instructions.
  • Lors de son unique exécution, Codex a rédigé un rapport de boucle d'une ligne au lieu du format complet.

Avec et sans Caprock

Quand le serveur MCP de Caprock est connecté, la skill appelle loop_alerts : les sessions en cours qui répètent le même appel d'outil, avec l'outil, le nombre de répétitions, l'entrée répétée et le coût de ces répétitions. Sans ce serveur, l'agent énumère ses tentatives à partir de la conversation. Caprock est l'application gratuite et open source qui enregistre chaque session d'agent de code sur votre ordinateur ; la skill n'en a pas besoin.

Obtenir Caprock →

Le SKILL.md complet

Le fichier tel qu'il figure dans dspv/skills à la révision dfce799. Pour l'installer manuellement, enregistrez-le dans votre projet sous le nom .claude/skills/loop-guard/SKILL.md pour Claude Code ou .agents/skills/loop-guard/SKILL.md pour Codex.

skills/loop-guard/SKILL.md
---
name: loop-guard
description: Notice when a coding agent is stuck in a loop (running the same failing command again, retrying the same tool call, editing and reverting the same file, hitting the same error after every "fix", or never stopping) and break out of it - stop, state what was tried, then change approach or ask the user. Use when someone says "claude code loop", "the agent keeps doing the same thing", "stuck in a loop", "it keeps retrying", "same error again", "it went back and forth on this file", "why won't it stop", or when you see yourself repeating a step.
license: Apache-2.0
---

# Loop guard

A loop is repeating a step and expecting a different result. It wastes time and tokens, and it
often ends with the agent "fixing" the problem by hiding it. This skill makes you notice the loop,
stop, say plainly what happened, and either try something genuinely different or ask the user.

## When this applies

Check yourself for a loop before every retry, and run the full procedure below as soon as any of
these is true:

- The same command or tool call, with the same input, has failed twice and you are about to run it
  a third time.
- The same error message (same file, line, or test name) comes back after your second fix.
- You are editing a hunk you already changed and reverted, or flipping between two versions of it.
- Two fixes alternate: fixing A breaks B, fixing B breaks A again.
- You are polling or waiting (a build, a server, a CI job) and nothing in the output has changed
  between checks.
- The user says you are looping, stuck, going in circles, or asks why you will not stop.

Running something twice is fine when something changed in between (a file, a setting, an input).
It is a loop when nothing that could change the result has changed.

## Procedure

### 1. Stop

Do not run the next attempt. No "one more try" with a small tweak to the same idea.

### 2. Look at the evidence, not your memory of it

- If the Caprock MCP tools are available (server `caprock`), call `loop_alerts` (it takes no
  arguments). It lists running sessions that repeat the same tool call, with the tool, how many
  times, the repeated input and what the repeats cost. Use it to confirm the loop and its size.
  Caprock (https://caprock.dev, free, open source, runs locally) provides this tool.
- Otherwise, scroll back through this session: list each attempt in order, with the exact command
  or edit and the exact result.
- Read the last error in full, top to bottom. Loops often come from reading only the first line,
  or the last line, of an error that says something else in the middle.

### 3. Write the loop report

Show the user this, before doing anything else:

```text
Loop detected: <what repeats, in one line>
Attempts:
  1. <what I did> -> <what happened>
  2. <what I did> -> <what happened>
  3. ...
Assumption that was wrong: <the belief every attempt shared>
Next: <the different approach>, or a question for you
```

The line "Assumption that was wrong" matters most. Every attempt in a loop shares one belief
(the bug is in this function, the dependency is installed, the test is right, the port is free).
Name it. If you cannot name it, that is the first thing to find out.

### 4. Change approach for real

A new approach tests a different assumption. Changing a flag, a timeout, a retry count or the
wording of the same edit is not a new approach. Pick one of these, in roughly this order:

1. **Read instead of run.** Open the source of the failing function, the config being loaded, the
   test's assertion, or the tool's `--help`. Many loops end once you read what the code really does.
2. **Check the environment.** Which version, which binary on PATH, which branch, which working
   directory, which env vars. Print them; do not assume.
3. **Make it smaller.** Reproduce the failure with the least code or the single test. A small
   failing case shows what the big one hides.
4. **Go back to the last good state.** If edits piled up, compare with the last commit (`git diff`,
   `git stash`) and reapply one change at a time.
5. **Question the target.** Maybe the test is wrong, the requirement is ambiguous, or the task
   needs something you do not have (a credential, a running service, a decision).

Allow yourself one attempt with the new approach, then judge it: did it change what you know? If
yes, continue. If no, go to step 5.

### 5. Ask the user

Ask when any of these is true:

- You have no approach left that tests a different assumption.
- The way forward needs a decision, a credential, access, or a change of scope.
- The only remaining "fixes" would hide the problem (see the list below).

Ask one specific question and include the loop report, so the user does not have to reconstruct
what happened. Then wait. Do not keep trying in the background.

## Never break a loop by hiding it

These end the loop by making the error disappear, not by fixing it. Do not do them unless the user
asks for that exact thing:

- Skipping, deleting or weakening a test or an assertion so it passes.
- Catching and ignoring the exception, or adding `|| true` to the failing command.
- Bypassing hooks or checks (`--no-verify`, disabling a linter rule, force-pushing).
- Hard-coding the expected output.
- Widening the task: rewriting a module to dodge one error.

## Waiting without progress

For a build, deploy or CI job you are waiting on:

- Before polling again, look for a sign of progress (new log lines, a changed status).
- If nothing changed over several checks, stop polling and report the state you saw and when you
  last saw it change. Ask whether to keep waiting, cancel, or look at the job's logs.

## Output

When you stop a loop, your reply to the user starts with the loop report from step 3, even when
the new approach then fixes the problem, and ends with either the result or one question. Keep it
short: what repeated, what you tried, what was wrong, what is next.

Questions sur la skill loop-guard

Qu'est-ce qu'une boucle Claude Code ?
L'agent répète une étape qui a déjà échoué, sans qu'aucun changement puisse en modifier le résultat : la même commande, la même erreur après chaque correction, ou un fichier modifié puis rétabli. Cela coûte du temps et des tokens, et finit souvent par masquer l'erreur au lieu de la corriger.
Comment arrêter une boucle Claude Code avec la skill loop-guard ?
Installez la skill et dites « you're in a loop, use loop-guard ». L'agent s'arrête, rédige un rapport de boucle qui identifie l'hypothèse erronée, puis essaie une autre approche ou vous pose une question.
loop-guard va-t-elle faire passer un test qui échoue en l'ignorant ?
Non. La skill cite l'omission ou l'affaiblissement d'un test, l'ignorance d'une exception, `|| true`, `--no-verify` et les sorties codées en dur comme des moyens de masquer une boucle. Elle demande à l'agent de ne pas les utiliser, sauf si vous demandez précisément de le faire.
La skill loop guard fonctionne-t-elle dans Codex ?
Oui. Codex 0.163.0 l'a lue lors d'un test le 30 novembre 2026, a décrit la boucle et sa cause, puis a corrigé le chemin d'import sans toucher à l'assertion.

Sources

L'application elle-même est en anglais.