﻿# Deterministic Loop Detection & Loop Engineering

## The Problem: The Loop Your AI Agent Can't See Itself In

Every modern autonomous coding agent runs inside an execution loop:

$$\text{Reason} \longrightarrow \text{Act (Tool Call)} \longrightarrow \text{Observe (Output)} \longrightarrow \text{Repeat}$$

While powerful, this loop introduces a critical architectural vulnerability: **The Observability Gap**.

Because a Large Language Model generates tokens step-by-step based on prior context, the agent's attention is consumed by the immediate error message or tool output. It cannot step outside its own generation trajectory to ask: _"Have I been repeating minor variations of this same failing command for the last 6 turns?"_

### Common Failure Modes

1. **Exact Repetition:** Repeatedly running `npm test` or `curl localhost:3000` without changing configuration or code.
2. **Fuzzy Repetition:** Changing tiny irrelevant flags (`grep -r` vs `grep -rn` vs `grep -rnI`) trying to find something that doesn't exist.
3. **Exploration Cycles:** Falling into closed alternating loops:
   $$\text{grep} \longrightarrow \text{find} \longrightarrow \text{npm test} \longrightarrow \text{grep} \longrightarrow \text{find} \longrightarrow \text{npm test}$$
4. **Output Stagnation:** Getting the exact same 500-line stack trace 5 times in a row while burning thousands of context tokens.

---

## The Burr Solution: Deterministic Runtime Guard

Instead of relying on a slow, expensive, and hallucination-prone secondary LLM to judge the agent, Burr implements a **deterministic mathematical runtime watcher**.

Before every proposed tool call, Burr computes a composite **Loop Risk Score ($0 - 100$)**:

```text
┌──────────────────────────────────────────────────────────────┐
│                   BURR LOOP RISK DETECTOR                    │
├────────────────────────────────┬─────────────────────────────┤
│ Detector                       │ Risk Weight                 │
├────────────────────────────────┼─────────────────────────────┤
│ 1. Exact Argument Repetition   │ +40 points                  │
│ 2. Fuzzy Jaccard Repetition    │ +25 points (Jaccard >= 0.85)│
│ 3. Subsequence Cycle Detection │ +30 points (Window k: 2..6) │
│ 4. Output Stagnation Hash      │ +20 points                  │
│ 5. Recent Failed Verification │ +10 points (caller reported)│
└────────────────────────────────┴─────────────────────────────┘
```

---

## How Each Detector Works

### 1. Canonical Argument Hashing

Tool arguments are recursively canonicalized (sorting object keys, trimming strings, normalizing types) and hashed with SHA-256:

```ts
fingerprintInput(tool, args) -> sha256(tool + ":" + sortedJson(args))
```

If the fingerprint matches an action already in the recent window, risk increases by $+40$.

### 2. Tokenized Jaccard Similarity (Fuzzy Guard)

To catch subtle variations (e.g. `npm test -- test/foo.ts` vs `npm test -- test/foo.test.ts`), Burr extracts argument tokens and computes the Jaccard similarity coefficient:
$$J(A, B) = \frac{|A \cap B|}{|A \cup B|}$$
If $J(A, B) \ge 0.85$, fuzzy repetition is detected ($+25$ risk).

### 3. Subsequence Cycle Detection ($k \in [2, 6]$)

Burr inspects the history of executed tools for periodic cycles. For any cycle length $k$ between 2 and 6:
If $T[n-k \dots n] == T[n-2k \dots n-k]$, a cyclic trap is flagged ($+30$ risk).

### 4. Output Stagnation Fingerprinting

Post-execution outputs are normalized and hashed. If consecutive failing actions produce identical output fingerprints, output stagnation is flagged ($+20$ risk).

---

## Action Thresholds

- **Score $< 50$ (Safe):** Normal execution. Action recorded in the local session ledger.
- **Score $50 - 69$ (Warn):** Burr injects actionable warning advice into the agent prompt, suggesting alternative diagnostic tools or inspecting configuration files.
- **Score $\ge 70$:** Repeated failed executions can produce a **blocking decision**. Productive repeats remain warnings. The host must honor the decision before executing the tool.

These APIs require a host integration to record results and enforce the returned blocking decision. Skill installation alone does not intercept tools. The score is a heuristic, not a guarantee that repeating an action is incorrect.
