Installs just this skill. Get the whole plugin for auto-invocation.
⚡ How it fires
How this skill gets triggered: by you, by Claude, or both.
Fires itselfClaude auto-loads it when your prompt matches the work.
You can call itInvoke it directly when you want it.
Slash command/skill-iterative-loop
👁️ Context preview
The summary Claude sees to decide when to auto-load this skill.
Run tasks in a loop until goals are met — use for iterative refinement, polling, or convergence
📊 Stats
Stars3,869
Forks362
LanguageShell
LicenseMIT
📦 Ships with octo
</> SKILL.md
skill-iterative-loop.SKILL.md
---name: skill-iterative-loop
aliases:
- iterative-loop
- loop-execution
- repeat-until
description: "Run tasks in a loop until goals are met — use for iterative refinement, polling, or convergence"
trigger: |
AUTOMATICALLY ACTIVATE when user requests iterative execution:
- "loop X times" or "loop around N times"
- "loop around 5 times auditing, enhancing, testing"
- "keep trying until" or "iterate until"
- "run until X passes" or "loop until Y works"
- "repeat N times" or "try N times"
DO NOT activate for:
- Single execution requests
- Manual retry requests
- Infinite loops (require max iterations)
---# Iterative Loop Execution
## Overview
Systematic iterative execution with clear goals, exit conditions, and progress tracking.
**Core principle:** Define goal → Set max iterations → Execute → Evaluate → Loop or complete.
---## When to Use
**Use this skill when user wants to:**
- Execute a task multiple times with refinements
User: "Iterate 4 times improving the error messages based on user feedback"
Implementation:
**Loop Goal:** Error messages meet clarity standard
**Max Iterations:** 4
**Per-iteration:**
1. Review current error messages
2. Identify confusing ones
3. Rewrite for clarity
4. Evaluate against criteria
**Success:** All messages rated 8+/10 for clarity
Execute each iteration with progressive improvement
```
---
## Integration with Other Skills
### With skill-debug
```
Loop for debugging:
"Keep debugging until all tests pass, max 5 tries"
Each iteration:
- Use skill-debug to investigate failure
- Apply fix
- Re-run tests
- Evaluate
```
### With skill-audit
```
Loop for comprehensive checking:
"Loop 3 times auditing different aspects"
Iteration 1: Audit security
Iteration 2: Audit performance
Iteration 3: Audit accessibility
```
### With skill-tdd
```
Loop for TDD cycles:
"Do 5 red-green-refactor cycles"
Each iteration:
- Write failing test (red)
- Make it pass (green)
- Refactor (refactor)
- Evaluate and continue
```
---
## Best Practices
### 1. Always Define Max Iterations
**Good:**
```
Loop max 5 times trying to fix the issue
```
**Dangerous:**
```
Keep trying until it works
(What if it never works? Infinite loop!)
```
### 2. Measurable Success Criteria
**Good:**
```
Success: All 15 tests pass AND code coverage > 80%
```
**Poor:**
```
Success: Code looks better
(Too subjective)
```
### 3. Make Progress Visible
```
**Progress Tracking:**
Iteration 1: 5/15 tests passing
Iteration 2: 10/15 tests passing
Iteration 3: 13/15 tests passing
Iteration 4: 15/15 tests passing ✓
```
### 4. Early Exit on Success
Don't continue looping if goal is achieved:
```
**Iteration 2/5:** All tests pass!
Stopping early - goal achieved.
No need to continue to iteration 3.
```
### 5. Detect Stalls
```
Iteration 4: 10/15 tests passing
Iteration 5: 10/15 tests passing
Iteration 6: 10/15 tests passing
⚠️ No progress in 3 iterations - stopping to reassess approach
```
---
## Red Flags - Don't Do This
| Action | Why It's Dangerous |
|--------|-------------------|
| No max iterations | Could loop forever |
| Vague success criteria | Don't know when to stop |
| No progress tracking | Can't tell if making progress |
| Ignoring stalls | Waste time on ineffective approach |
| Same action each loop | If not working, need different approach |
---
## Strategy Rotation
If the strategy-rotation hook fires, immediately change approach. Do not retry the same approach. Explain what you'll do differently before the next attempt. The hook fires after consecutive failures of the same tool — this is a strong signal that the current approach is fundamentally wrong, not just slightly off.
---
## Self-Regulation (MANDATORY)
Every iterative loop MUST track a **Self-Regulation Score** that accumulates danger signals. This prevents runaway loops where the agent keeps "fixing" things without real progress.
### Sliding-Window Stuck Detection
Maintain a mental window of the **last 10 iterations** (or fewer if less than 10 have run). After each iteration, check for repeated patterns:
**Single-state repetition:** Did the same outcome/error occur 3+ times consecutively?
- Same test failure, same error message, same files modified → **STUCK**
**Multi-step cycle detection:** Is there an A→B→A→B oscillation?
- Iteration N touches file X, N+1 touches file Y, N+2 touches file X again, N+3 touches Y again → **CYCLE DETECTED**
- Compare the *files modified* and *error messages* across iterations, not just success/failure
**On first detection:** Announce the pattern to the user. Attempt ONE diagnostic retry with explicit acknowledgment: "This pattern has repeated — here's what I'll do differently: [specific change]."
**On second detection:** **HALT immediately.** Display the detected cycle and ask the user whether to continue with a completely different approach or stop.
### WTF-Likelihood Score
Track a cumulative score starting at 0%. Each event adds to the score.
**Default weights** (override via `~/.claude-octopus/loop-config.conf`):
| Event | Score Impact |
|-------|-------------|
| Revert (git revert, undo, roll back) | **+15%** |
| Touching files unrelated to the stated goal | **+20%** |
| A fix that requires changing >3 files | **+5%** |
| After the 15th fix attempt | **+1% per additional fix** |
| All remaining issues are Low severity | **+10%** |
| Comprehensive audit | 3-5 | All areas covered | No |
---
## Metric Verification Mode
When the user specifies a **Metric** command, switch to mechanical metric verification mode. This replaces subjective evaluation with automated measurement, git-backed experiments, and automatic rollback on regression.
**Falls back to standard loop behavior (above) when no metric is specified.**
### Key Principles
- **One change per iteration (atomic)** — never combine multiple unrelated changes
- **Mechanical verification only** — no subjective "looks good"; the metric command decides
- **Automatic rollback on regression** — `git revert HEAD --no-edit` if metric worsens
- **Simplicity wins** — equal metric results + less code = KEEP the simpler version
- **Git is memory** — every experiment is committed with `experiment:` prefix before verification
- **Guard commands must also pass** — even if metric improves, a failing guard reverts the change
### Parameters
| Parameter | Format | Required | Description |
|-----------|--------|----------|-------------|
| Metric | `Metric: <shell command>` | Yes (for this mode) | Command whose stdout is a number (the metric value) |
| Direction | `Direction: higher\|lower` | Yes | Whether higher or lower metric values are better |
| Guard | `Guard: <shell command>` | No | Must exit 0 for a change to be kept; run after metric |
| Iterations | `Iterations: N` | No | Max iterations (default: unbounded, runs until interrupted) |
### Experiment Log
All results are logged as JSONL to `.claude-octopus/experiments/<YYYY-MM-DD>.jsonl`.
Each line is a JSON object:
```json
{"iteration": 1, "timestamp": "2026-03-21T14:30:00Z", "metric": 72.5, "best": 72.5, "status": "kept", "description": "Add index to users table", "commit": "abc1234"}
```
Fields:
- `iteration` — iteration number (starting from 1; iteration 0 is baseline)
- `timestamp` — ISO 8601 timestamp
- `metric` — measured value from the metric command
- `description` — one-line summary of what was changed
- `commit` — short git SHA of the experiment commit (before potential revert)
### Execution Contract
You MUST follow this exact sequence for each iteration. No steps may be skipped or reordered.
#### Iteration 0: Establish Baseline
1. Create the experiment log directory if it does not exist:
```bash
mkdir -p .claude-octopus/experiments
```
2. **Check for existing experiment log** — if `.claude-octopus/experiments/<today>.jsonl` exists, read it to determine the current best metric value and iteration count. Resume from the next iteration number.
3. Run the metric command and capture the output number. This is the **baseline**.
4. Log the baseline:
```json
{"iteration": 0, "timestamp": "...", "metric": <baseline>, "best": <baseline>, "status": "baseline", "description": "Baseline measurement", "commit": "<current HEAD short SHA>"}
```
5. Report the baseline value to the user.
#### Each Subsequent Iteration (1..N)
**Step 1: Review state.** Read the experiment log (`.claude-octopus/experiments/<today>.jsonl`), review git history (`git log --oneline -10`), and identify what has been tried, what worked, and what failed.
**Step 2: Pick the next change.** Based on what worked/failed/is untried, decide on ONE focused change. Do NOT combine multiple unrelated changes.
**Step 3: Make the change.** Implement exactly one atomic change.
**Step 4: Git commit BEFORE verification.** Commit with the `experiment:` prefix:
```bash
git add -A && git commit -m "experiment: <one-line description of the change>"
```
This ensures every experiment is recorded in git history regardless of outcome.
**Step 5: Run mechanical verification.** Execute the metric command and capture the numeric result.
**Step 6: Evaluate and act.**
- **If metric improved** (higher when Direction=higher, lower when Direction=lower):
- If a Guard command is specified, run it now.
- If guard passes (exit 0) → **KEEP** the commit. Update best metric.
- If guard fails (exit non-zero) → **REVERT**: `git revert HEAD --no-edit`. Log status as `"reverted"`.
- If no guard → **KEEP** the commit. Update best metric.
- **If metric stayed the same:**
- Check if the change reduces code complexity or size. If simpler → **KEEP** (simplicity wins).
- Otherwise → **REVERT**: `git revert HEAD --no-edit`. Log status as `"reverted"`.
- **If metric worsened:**
- **REVERT**: `git revert HEAD --no-edit`. Log status as `"reverted"`.
- **If metric command crashed (non-zero exit, no numeric output):**
- Attempt a quick fix (one try only). If fix works, re-measure.
- If still broken → **REVERT**: `git revert HEAD --no-edit`. Log status as `"error"`.
**Step 7: Log the result.** Append a JSONL entry to `.claude-octopus/experiments/<today>.jsonl`.