Claude Codeのループ:反復を止めるloop-guardスキル
Dmitriy Solodukha、Caprock開発者 · 公開日
にClaude CodeとCodexでテスト済み
Claude Codeのループは、失敗する同じ手順を繰り返す状態です。無料のloop-guardスキルが停止させ、誤った前提を特定して方法を変えます。
Claude Codeがループしたとき(同じコマンドの失敗、修正しても同じエラー、同じファイルの編集と差し戻し)、loop-guardスキルは停止させ、試行を列挙し、すべてに共通する前提を特定します。そのうえで別の前提を検証する方法を試すか、ユーザーに尋ねます。Claude Code、Codex、OpenCode、Cursor向けのSKILL.md 1ファイルで、Apache-2.0のもと無料です。
loop-guardスキルをインストールする
エージェントごとに1コマンド。スキルはSKILL.md 1ファイルで、インストール時に何も実行しません。
9スキルをプラグインとして導入します。Claude Code内で次を入力してください:
このスキルだけを導入する場合は、プロジェクトのフォルダーで次を実行します:
全プロジェクトに導入するには -g を追加します。
プロジェクトのフォルダーでターミナルから実行:
全プロジェクトに導入するには -g を追加します。
プロジェクトのフォルダーでターミナルから実行:
全プロジェクトに導入するには -g を追加します。 OpenCodeでは未検証です。オープンな形式の通常の指示ですが、OpenCodeでの実行確認はしていません。
プロジェクトのフォルダーでターミナルから実行:
全プロジェクトに導入するには -g を追加します。 Cursorでは未検証です。オープンな形式の通常の指示ですが、Cursorでの実行確認はしていません。
loop-guardスキルを使うプロンプト
依頼の内容が説明と合うと、エージェントがスキルを選びます。名前を指定すると確実です。プロンプトをクリックしてコピーできます。
loop-guardがClaude Codeのループを抜ける方法
スキルはループの判定方法と抜け方を定めます:
- テスト。同じ入力の同じコマンドが2回失敗した、2回目の修正でも同じエラーが出た、同じハンクを変更して戻している、2つの修正を交互に繰り返す、ポーリングで変化がない場合です。途中で何か変わったなら、同じ操作を2回行っても構いません。
- 止めて、確認する。 「もう一度だけ」は行いません。直近のエラーを全文読み、各試行とその正確な結果を列挙します。
- ループ報告。繰り返していること、試行、誤った前提、次の手順を記します。特に重要なのは誤った前提です。ループ中の各試行は、同じ思い込みを共有しています。
- 前提から方法を変えるとして順番に試すのは、実行せずコードを読む、環境を確認する、失敗を最小化する、最後に動いていた状態へ戻す、テストやタスク自体を疑うことです。新しい方法で一度試し、結果を判断します。
- 試せる方法がなくなったときや、残る「修正」が問題を隠すだけになるときは尋ねる。
実行したテストとエージェントの動作
各スキルは2026年11月29日に、専用の使い捨てリポジトリへプロジェクトスキルとしてインストールして実行しました。小さなPythonリポジトリで、tests/test_slug.pyがsys.path上でtests/をsrc/より前に配置していたため、古いモジュールのコピー(tests/textkit/slug.py)が読み込まれ、src/textkit/slug.pyを何度編集しても変化がありませんでした。テスト用に手書きしたNOTES.mdには、「前のエージェント」による4回の試行が記され、いずれも同じ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.
2回実行しました。どちらもloop-guardを呼び、Caprockのloop_alertsを実行し、テストが実際に読み込んだファイルを表示して、テスト内のsys.pathの順序を修正しました。アサーションとsrc/textkit/slug.pyは変更せず、テストは成功しました。古いtests/textkit/フォルダーはgitが追跡しているため、両方とも削除前に確認しました。初回のプロンプトには末尾の「Answer in English.」がありませんでした。2回目のループ報告:
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、2026年11月30日に実施)
The slug test still fails and I've tried fixing src/textkit/slug.py three times. Fix it.
.agents/skills/loop-guard/SKILL.mdを見つけて読み、Caprockのloop_alertsを呼び出した後、src/を先に読み込むようにtests/test_slug.pyを修正しました。アサーションは変更せず、テストは成功し、git diff --checkも問題ありませんでした。報告はループの行で始まりましたが、スキルの書式にある試行一覧と誤った前提の行が抜けていました(リンクは通常のテキストで表示):
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.
検証したエージェント
- Claude Code:2026年11月29日に、
.claude/skills/にプロジェクトスキルとしてインストールし、claude -p --model sonnetで検証しました。 - Codex:2026年11月30日にCodex 0.163.0(
codex exec)、.agents/skills/内のスキルで検証しました。同日の以前のCodex実行にはスキルが入っていなかったので、数に含めていません。 - OpenCodeとCursor:未検証です。オープンなAgent Skills形式の通常の指示ですが、どちらでも実行して確認していません。
制限
- スキルはエージェントが見える範囲で動作します。セッションをまたぐループや、エージェントが気づかないループでは「you're in a loop」と伝えてください。
- Caprockがなければ、会話自体から試行を復元します。圧縮済みの会話では初期の試行が失われていることがあります。
- 再試行回数の制限やプロセスの強制終了は行いません。指示を無視するエージェントをスキルで止めることはできません。
- Codexの1回の実行では、完全な形式ではなく1行のループ報告になりました。
Caprockがある場合とない場合
Caprock MCPサーバーに接続している場合、スキルはloop_alertsを呼び、同じツール呼び出しを繰り返す稼働中セッションについて、ツール、回数、入力、そのコストを取得します。接続がなければ、会話から試行を列挙します。Caprockはコンピューター上の全コーディングエージェントのセッションを記録する無料のオープンソースアプリです。このスキルに必須ではありません。
SKILL.md全文
dspv/skillsのリビジョンdfce799にあるファイルそのものです。手動で導入する場合、プロジェクト内の、Claude Codeは.claude/skills/loop-guard/SKILL.md、Codexは.agents/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.
loop-guardスキルについての質問
- Claude Codeのループとは?
- 結果が変わる変更を加えず、失敗済みの手順を繰り返す状態です。同じコマンド、修正後も同じエラー、編集と差し戻しの反復などです。時間とトークンを費やし、修正の代わりにエラーを隠して終わることもあります。
- loop-guardスキルでClaude Codeのループを止めるには?
- インストール後に「you're in a loop, use loop-guard」と伝えます。エージェントが停止し、誤った前提を含むループ報告を書き、別の方法を1つ試すか質問します。
- loop-guardは失敗するテストをスキップして成功扱いにしますか?
- 行いません。テストのスキップ・弱体化、例外の無視、`|| true`、`--no-verify`、出力のハードコードは問題を隠す方法とし、その操作を明示的に依頼されない限り禁止します。
- loop-guardスキルはCodexでも使えますか?
- 使えます。Codex 0.163.0が2026年11月30日のテストでループと原因を説明し、アサーションを変更せずimportパスを修正しました。