# Self-Supervision Mechanism in Reverse-Skill: How It Prevents Infinite Loops

> Discover how Reverse-Skill's self-supervision mechanism prevents infinite loops with progress checks, blocks identical tool calls, and enforces execution budgets. Learn more.

- Repository: [ZhaoXu/reverse-skill](https://github.com/zhaoxuya520/reverse-skill)
- Tags: internals
- Published: 2026-08-14

---

**Reverse-Skill prevents infinite loops through a policy-level self-supervision layer that forces periodic progress checks, blocks repeated identical tool calls, and enforces hard budgets on tool execution.**

The `zhaoxuya520/reverse-skill` framework embeds guardrails directly into its routing rules rather than relying on external monitoring. This design ensures that AI agents remain deterministic and resource-efficient even when tackling complex, multi-step tasks with unpredictable external tools.

## Where the Self-Supervision Policy Lives

The authoritative rules for self-supervision are defined in **[`RULES.md`](https://github.com/zhaoxuya520/reverse-skill/blob/main/RULES.md)** at lines 19-27. These rules function as a contract that the AI must follow during task execution. Rather than implementing loops solely in code, Reverse-Skill makes self-monitoring a first-class citizen of its execution policy.

The policy is triggered through **[`skills/MASTER-ROUTING.md`](https://github.com/zhaoxuya520/reverse-skill/blob/main/skills/MASTER-ROUTING.md)**, which defines when and how supervision checks are invoked. For architectural context, **[`docs/ARCHITECTURE.md`](https://github.com/zhaoxuya520/reverse-skill/blob/main/docs/ARCHITECTURE.md)** shows how this layer integrates into the broader execution pipeline.

## The Five Core Self-Supervision Conditions

Reverse-Skill's self-supervision mechanism enforces specific thresholds designed to catch different failure modes:

### Periodic Progress Review Every 5 Tool Calls

After every fifth tool invocation—or whenever the AI detects being "stuck"—execution pauses for a `<self_review>` step. The AI must answer: *"Am I actually making progress toward the goal?"* and cite concrete evidence. This prevents the agent from continuing blindly down an ineffective path.

### Block Repeated Identical Tool Calls (≥2 Times)

The same tool with identical parameters cannot be called consecutively more than twice. This rule directly targets retry loops where an agent repeatedly attempts the same failed operation without adaptation.

### Mandate Error Comprehension

When the AI cannot explain an error message, it must stop and understand the failure before proceeding. This prevents cascading errors from misunderstood feedback.

### Switch Methods After 2-3 Failures

If the same method fails repeatedly, the agent must pivot to an alternative approach—for example, switching between static and dynamic analysis or using different tooling. This encourages strategic flexibility over stubborn persistence.

### Hard Budget Limit at 30 Calls Per Sub-Task

When approaching the tool-call budget, the agent reports status to the user and requests permission to continue. This cap prevents runaway resource consumption on intractable problems.

## Implementation: The SelfSupervisor Class

A reference implementation in `skills/` demonstrates how agents can operationalize these rules:

```python
class SelfSupervisor:
    def __init__(self, budget=30):
        self.call_count = 0
        self.repeated_calls = {}
        self.budget = budget

    def record_call(self, tool_name, params):
        self.call_count += 1
        key = (tool_name, tuple(params.items()))
        self.repeated_calls[key] = self.repeated_calls.get(key, 0) + 1

        # 1️⃣ Every 5 calls → self-review

        if self.call_count % 5 == 0:
            self.self_review()

        # 2️⃣ Same tool+params ≥ 2 times → change approach

        if self.repeated_calls[key] >= 2:
            raise RuntimeError(
                f"Repeated call to {tool_name} with identical params; switch strategy."
            )

        # 3️⃣ Budget limit → ask user

        if self.call_count > self.budget:
            raise RuntimeError(
                f"Tool-call budget of {self.budget} exceeded; need user approval."
            )

    def self_review(self):
        # In practice this emits structured log the AI can read

        print("[SELF_REVIEW] Checking progress, confirming no drift...")

```

## Practical Usage in Skill Scripts

The `SelfSupervisor` integrates into agent workflows as a call interceptor:

```python
supervisor = SelfSupervisor()

for item in work_items:
    supervisor.record_call("run_static_analyzer", {"file": item})
    result = run_static_analyzer(item)
    if not result.success:
        # Switch to dynamic analysis after repeated failures

        supervisor.record_call("run_dynamic_analyzer", {"file": item})
        result = run_dynamic_analyzer(item)

```

This pattern ensures that all tool invocations pass through policy checks without cluttering business logic with guardrail code.

## Why Policy-Level Supervision Outperforms Code-Only Approaches

Embedding self-supervision in **[`RULES.md`](https://github.com/zhaoxuya520/reverse-skill/blob/main/RULES.md)** rather than scattering checks throughout implementation code provides three advantages:

- **Auditability** – The complete policy exists in one human-readable document
- **Consistency** – All skills inherit the same protection automatically
- **Adaptability** – Thresholds can be tuned without modifying execution logic

The framework treats self-supervision as a cross-cutting concern, similar to how mature systems handle logging or authentication.

## Summary

- **Self-supervision in Reverse-Skill** is implemented through explicit routing rules in [`RULES.md`](https://github.com/zhaoxuya520/reverse-skill/blob/main/RULES.md), not implicit code behavior
- **Five trigger conditions** enforce progress verification, block repeated calls, mandate error understanding, require method switching, and cap resource usage
- **`SelfSupervisor` class** provides a reference implementation that tracks call patterns and raises exceptions when policy thresholds are breached
- **30-call budget** per sub-task serves as a hard ceiling requiring human intervention
- **Master routing** in [`skills/MASTER-ROUTING.md`](https://github.com/zhaoxuya520/reverse-skill/blob/main/skills/MASTER-ROUTING.md) orchestrates when supervision checks execute

## Frequently Asked Questions

### How does Reverse-Skill detect when an AI is stuck in a loop?

Reverse-Skill detects stuck states through multiple signals: repeated identical tool calls (≥2 times), the same method failing 2-3 times in succession, or explicit recognition by the AI itself during mandatory self-reviews every 5 calls. These conditions trigger exceptions that force strategy changes or user consultation.

### Can the tool-call budget be customized per skill?

Yes. The `SelfSupervisor` class accepts a configurable `budget` parameter in its constructor. While the default policy specifies 30 calls per sub-task, individual skills can instantiate `SelfSupervisor(budget=N)` with different thresholds appropriate to their complexity.

### What happens when the tool-call budget is exceeded?

When `self.call_count > self.budget`, the supervisor raises a `RuntimeError` with the message that user approval is required. Execution halts rather than continuing uncontrolled, preserving resources and preventing infinite consumption loops.

### Is the self-supervision mechanism mandatory for all Reverse-Skill agents?

According to [`RULES.md`](https://github.com/zhaoxuya520/reverse-skill/blob/main/RULES.md), the self-supervision checks are binding policy. The routing infrastructure in [`skills/MASTER-ROUTING.md`](https://github.com/zhaoxuya520/reverse-skill/blob/main/skills/MASTER-ROUTING.md) ensures these checks execute regardless of which specific skill implementation runs, making protection universal across the framework.