Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

behavioral-loop-detection

БесплатноЗапускает вложенные скриптыНе проверен

Detect when agents are stuck in repetitive action loops using a rolling 20-action window with escalating nudges — replan after 3 similar actions, explore…

oimiragieoот oimiragieo★ 48 звёзд на GitHub

Об этом скилле

Behavioral Loop Detection

Overview

Detects when an agent is stuck in a repetitive action loop by maintaining a rolling 20-action history window. Compares recent actions using normalized similarity scoring and applies escalating interventions before the agent wastes tokens or blocks progress.

Designed for any agentic context — browser automation, file editing, API calls, or multi-step orchestration — not tied to any specific tool type.

When to Use

Invoke this skill when:

  • An agent task has been running for more than 10 steps without clear progress
  • The same tool is being called repeatedly with similar arguments
  • A task appears stalled with no TaskUpdate(completed) after a long sequence
  • You want proactive loop-prevention in a custom orchestrator
Skill({ skill: 'behavioral-loop-detection' });

The Iron Law

SAME ACTION × 3 = REPLAN
SAME ACTION × 5 = EXPLORE
SAME ACTION × 8 = FORCE-DONE

Never let an agent silently loop forever. Each repetition consumes tokens and produces no value.

Action History Window

Maintenance Rules

  • Keep a rolling buffer of the last 20 actions (FIFO — drop oldest when full)
  • Each entry in the buffer: { toolName, normalizedArgs, timestamp, stepIndex }
  • Reset the buffer only when a fundamentally different tool/action type appears
  • Never reset on argument variation alone (e.g., same tool, different file path = still similar)

Normalized Action Comparison

Two actions are similar when:

  1. The toolName is identical, AND
  2. The normalized argument string similarity score ≥ 0.75 (Jaccard over word tokens)

Normalization rules (apply in order):

  1. Convert all values to lowercase
  2. Strip file paths down to basename only (e.g., /a/b/file.ts → file.ts)
  3. Remove timestamps, UUIDs (8-4-4-4-12 hex pattern), and numeric IDs
  4. Sort object keys alphabetically before stringifying
  5. Truncate the result to 200 characters

Similarity scoring:

function jaccardSimilarity(a, b) {
  const setA = new Set(a.split(/\s+/));
  const setB = new Set(b.split(/\s+/));
  const intersection = new Set([...setA].filter(x => setB.has(x)));
  const union = new Set([...setA, ...setB]);
  return intersection.size / union.size;
}

Escalation Ladder

Threshold Trigger Condition Intervention Message to Agent
Level 1 3 similar actions in a row REPLAN nudge "You have repeated a similar action 3 times. Stop and produce a revised plan before continuing."
Level 2 5 similar actions in a row EXPLORE nudge "You have repeated a similar action 5 times. The current approach is failing. Try a completely different tool or method."
Level 3 8 similar actions in a row FORCE-DONE signal "Loop limit reached (8 repetitions). Mark this task complete with partial results and explain what was not accomplished."
  • Escalation levels are cumulative: Level 2 fires at step 5 regardless of whether Level 1 fired
  • After FORCE-DONE signal, call TaskUpdate({ status: 'completed', metadata: { partial: true, loopDetected: true } })

Workflow

Step 1: Initialize the Action Buffer

At the start of task execution or when this skill is loaded, create the buffer:

Command:

const actionBuffer = {
  window: [], // Array of last 20 action entries
  maxSize: 20,
  similarRunLength: 0, // Current streak of similar actions
  lastNormalized: null, // Normalized args of last action
};

Expected output: In-memory buffer ready; no file I/O required unless persisting across sessions.

Verify: actionBuffer.window.length === 0 on initialization.

Step 2: Record Each Action

Before executing any tool call, append to the buffer:

Command:

function recordAction(buffer, toolName, rawArgs) {
  const normalized = normalizeArgs(toolName, rawArgs);
  const entry = {
    toolName,
    normalizedArgs: normalized,
    timestamp: Date.now(),
    stepIndex: buffer.window.length,
  };
  if (buffer.window.length >= buffer.maxSize) {
    buffer.window.shift(); // drop oldest
  }
  buffer.window.push(entry);
  return entry;
}

Expected output: Buffer contains the new entry; length never exceeds 20.

Verify: buffer.window.length <= 20 after each call.

Step 3: Check Similarity Against Last Action

After recording, compute similarity and update the run-length counter:

Command:

function checkSimilarity(buffer, currentEntry) {
  if (!buffer.lastNormalized) {
    buffer.lastNormalized = currentEntry.normalizedArgs;
    buffer.similarRunLength = 1;
    return { similar: false, runLength: 1 };
  }
  con
Полный SKILL.md на GitHub

Установить behavioral-loop-detection в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Read
Write
Bash
TaskUpdate

Вложенные файлы

commands/behavioral-loop-detection.mdhooks/post-execute.cjshooks/pre-execute.cjsreferences/research-requirements.mdrules/behavioral-loop-detection.mdschemas/input.schema.jsonschemas/output.schema.jsonscripts/main.cjstemplates/implementation-template.md

FAQ

Что делает скилл behavioral-loop-detection?

Detect when agents are stuck in repetitive action loops using a rolling 20-action window with escalating nudges — replan after 3 similar actions, explore after 5, force-done after 8.

Как установить скилл behavioral-loop-detection?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл behavioral-loop-detection запускает скрипты?

Да, скилл несёт исполняемые скрипты. Проверь исходник перед установкой.

Похожие скиллы

Сравнить behavioral-loop-detection с