# Anti-Looping Guardrail

## Rule
Prevent infinite retry loops and circular subagent handoffs.

## Detection Patterns
- **Same tool call repeated 3+ times in 5 turns**: Regex match on tool name + arguments hash
- **Circular subagent handoffs**: Agent A delegates to B, B delegates back to A
- **Identical error message appearing twice consecutively**: Match on `stderr` output

### Regex Patterns
```regex
tool_call_count\(name="(\w+)", args_hash="([^"]+)"\) > 3
subagent_depth > 2
error_msg == last_error_msg
```

## Mechanics
- Max-turn budget per task: 15 turns. Warning at 12, hard stop at 15.
- Command retry limit: 3 attempts. If command fails 3 times, stop and escalate.
- Loop detection: If identical tool call or file edit is made twice with same error, abort.
- Escape condition: When trapped, output current state, exact error, and request human intervention.

## Tool-Call Examples
**Correct**: 
- Turn 1: `grep -r "deprecated_api" src/` -> Not found
- Turn 2: `find . -name "*.py" | xargs grep -l "deprecated_api"` -> Not found
- Turn 3: Stop. Report: "Function not found in codebase. Verify function name."

**Incorrect**:
- Turn 1: `grep -r "deprecated_api" src/` -> Not found
- Turn 2: `grep -r "deprecated_api" src/` -> Not found (identical call)
- Turn 3: `grep -r "deprecated_api" src/` -> Not found (infinite loop)

## When This Fires
1. Agent retries `npm install` 4 times because of network timeout.
2. Subagent Architect delegates to Debug Detective, which delegates back to Architect.
3. Agent edits a file, sees same syntax error, edits same line again without changing logic.

## Integration: Subagent `disallowedTools` YAML
```yaml
disallowedTools:
  - terminal: ["rm -rf", "git push --force"]
  - write_file: ["*.env", "*.key"]
```
Anti-looping integrates by counting tool invocations per task session. Once limit hit, agent stops dispatching and reports state.

## Verification
- Log each tool call with arguments hash.
- Check cumulative turn count before each tool dispatch.
- Output loop-break status in final response.
