# Loop
<!--
ref: @protocol/loop
tags: [loop, improvement, audit, strategy, autonomous, meta, iteration]
aliases: [@protocol/looping]
triggers: [loop, looping, ri, recursive improvement, smart loop, focused loop, ratchet, recursively improve that protocol, this is my strategy]
trigger_prompt: When the user seeks to enhance a project or feature through systematic iteration, whether broadly or with a specific focus.
category: orchestrate
last_reviewed: 2026-05-14
complements: [@protocol/chunk, @protocol/orchestrate, @protocol/spec]
audience: [agent-author]
version: 12
updated_at: 2026-11-03T18:03:07.440Z
-->

Iterative improvement with modes — broad recursive improvement or focused single-goal loops.

Iterative improvement protocol. Audits state, selects work, executes via `@protocol/chunk`, and repeats until done.

Three modes: **recursive improvement** (broad, strategic), **focused** (narrow, persistent), and **ratchet** (improve a strategy against a real-world number).

---

## Modes

### Recursive Improvement Mode

The broadest looping mode. Deep audit of the full project (or scoped area), strategic task selection, health checks between iterations.

```
AUDIT → SELECT → chunk(task) → AUDIT → SELECT → chunk(task) → ...
```

Use when:
- "Get to work on project X"
- "Recursive improvement on the backend"
- Multi-task improvement sessions where you need to decide what matters most

Features:
- Full confidence map across project areas
- Priority waterfall for task selection
- Rut, thrash, and diminishing returns detection
- Can launch spec sessions for features needing discussion
- Can do architecture sessions to update the spec tree itself

### Focused Mode

Narrow, persistent looping on a single goal or feature. Ralph Wiggum style — keep going until done.

```
chunk(task) → verify → done? → chunk(task) → verify → done? → ...
```

Use when:
- "Loop on the search feature"
- "Focus on auth until it works"
- Single feature or goal with clear completion criteria

Features:
- One goal, one area — ignore everything else
- After each chunk, ask: am I done?
- Can audit and verify within the focused area
- Terminate when goal is met or diminishing returns hit
- Simpler than recursive improvement — no priority waterfall needed

### Ratchet Mode

Improve a *protocol* (a strategy whose results show up in the world: replies, signups, AI answer share) rather than a codebase. Measure (one real-world score, with underlying signals beside it), make one change, act, measure again; keep the change only if the score improved. Invoked as "Ratchet <protocol>", "recursively improve that protocol", or "this is my strategy for <goal>". Full protocol: **`@protocol/ratchet`**.

### Choosing a Mode

| Signal | Mode |
|--------|------|
| Broad scope, many areas | Recursive improvement |
| Single feature or goal | Focused |
| "Get to work on X" | Recursive improvement |
| "Loop on X until done" | Focused |
| Unclear what to do next | Recursive improvement (audit first) |
| Clear goal, just need to grind | Focused |
| A strategy judged by a real-world number | Ratchet (`@protocol/ratchet`) |

---

## Scoped Mode

Either mode can be scoped to a specific area:

```
"Loop on the UI" → focused on UI
"Recursive improvement on the API" → broad audit but only API-related work
```

When scoped, the audit focuses on that area — reading only relevant spec sections, git history for those files, and tests for that domain. Unrelated issues are ignored even if globally higher priority.

---

## The Spec Tree

Both modes operate on a **spec tree** — a hierarchical definition of the why and the what (never the how).

- Completed work marked done
- Roadmap of what's planned
- Breakable into pieces when parts aren't related (saves context)
- Read-only objective kernel at the root

The Loop reads the spec tree to audit. Chunk writes to it to record completion or partial progress. The spec tree is the canonical project surface — it stays where the project keeps it (`SPEC.md`, `docs/spec/`, etc.).

---

## AUDIT (recursive improvement mode)

Every entry into recursive improvement starts here. Read state fresh — progress lives in git and files, not context.

### 1. What's been done?

- `git log` since last session / last N commits
- Read spec tree — what's marked complete, in progress, planned
- Identify project areas and what's changed

### 2. Confidence per area

| Area | Last Verified | Changed Since? | Confidence | Gap Type |
|------|--------------|----------------|------------|----------|
| Auth | 2h ago | no | HIGH | — |
| UI vs spec | never | — | LOW | verification |
| Search | 3 days | yes | MEDIUM | staleness |

**Rules:**
- Never verified → **LOW**
- Verified + unchanged since → **HIGH**
- Verified + changed since → **MEDIUM**
- Was passing, now failing → **CRITICAL**

**Gap types:** `verification` · `staleness` · `regression` · `roadmap` · `tech-debt` · `polish`

### 3. Is the loop healthy?

- **Rut** — Same area/category 3+ consecutive times? Force a different area or out-of-box audit.
- **Thrash** — Same files modified with reversals? Stop. Root-cause analysis first.
- **Diminishing returns** — No meaningful confidence improvement in last few rounds? Switch areas or stop.
- **Overbaking** — Unbidden complexity appearing? Reset scope to objective kernel.
- **Cost** — Been at this too long? Summarize state and stop.
- **Quiet stop** — When you do stop because nothing is actionable (3+ consecutive no-op ticks, PLATEAU, or DONE in a long-running loop), emit a single short line and exit. Don't restate "nothing to do" on every tick — the transcript is what the user reads later, and repeated no-op messages are noise that wastes their attention when they come back to review.

### 4. Half-finished work

Check the spec tree for items marked in-progress but not complete. A prior chunk run may have broken or been interrupted. Prioritize completing or reverting these.

---

## SELECT (recursive improvement mode)

Pick the highest applicable from the priority waterfall:

1. **Regressions** — was working, broke
2. **Half-finished** — started but incomplete
3. **Verification gaps** — never tested against spec
4. **Stale verifications** — tested but code changed since
5. **Roadmap** — planned, not started
6. **Tech debt** — known shortcuts
7. **Polish** — cosmetic, DX

**Sanity check** before committing:
- Can I verify the result?
- Will I know if I break something adjacent?
- Can I revert if it goes wrong?
- **Reversibility under uncertainty** — if a prior iteration raised a question the user hasn't answered, gate on the action's reversibility. Reversible (local edits, running tests, scratch files) → make your best call and proceed. Irreversible (push, force-push, delete, send, post, publish, schedule-to-external-system) → wait another cycle. The cost of acting wrongly on something irreversible is much higher than the cost of waiting one more iteration.

**Anti-repetition:** If same category 3+ times consecutively, force a switch.

### Non-chunk actions

SELECT can also choose:
- **Spec session** — a feature needs interactive discussion.
- **Architecture session** — the spec tree itself needs updating.
- **Out-of-box audit** — forced when rut detected. Step back, find what's been ignored.
- **Escalate** — requires human judgment.

---

## VERIFY (focused mode)

After each chunk in focused mode, ask:

- Did it work? Run tests, check the output.
- Am I done? Is the goal met?
- Am I stuck? Same thing failing repeatedly?

If done → terminate. If stuck → escalate or try a different approach. Otherwise → next chunk.

---

## Objective Kernel

The root of the spec tree contains a **read-only** objective kernel:

```markdown
## Objective Kernel (READ-ONLY)
- Primary goal: [user's stated goal]
- Success criteria: [measurable exit conditions]
- Out of scope: [explicitly excluded]
- Cost ceiling: [max iterations / max time]
```

If goals need changing, **escalate to the user** — don't self-modify.

---

## Exit Conditions

- **DONE** — Goal met (focused) or all areas HIGH confidence (recursive improvement)
- **CEILING** — Max iterations reached. Summarize what's done and what remains.
- **ESCALATE** — Thrash, blocked, or judgment needed. Hand to human with diagnosis.
- **PLATEAU** — Diminishing returns. Honest assessment of what more iteration would achieve.

---

## Invocation

```
"Loop on [goal]"                    → focused mode
"Recursive improvement on [area]"   → recursive improvement mode
"ri"                                → recursive improvement mode
"Get to work on [project]"          → recursive improvement mode
```

First action is always the audit (recursive improvement) or context loading (focused).

---

## Environment adapters

The protocol describes *what to do* each iteration; the harness supplies *when*. Cadence is intentionally not specified here — that's an environment concern.

- **Claude Code (mature).** `/loop` is the built-in cadence primitive. `/loop 5m <prompt>` for fixed interval (cron). `/loop <prompt>` for self-paced — the runtime uses `ScheduleWakeup` and the model picks each next interval. `/loop` alone for autonomous mode. The connection to **this** protocol is a single `UserPromptSubmit` hook that detects the `/loop` prefix and injects a pointer to `@protocol/loop` as `additionalContext`. No file syncing, no per-project setup, no per-tick cache cost — install the hook once globally and every project gets the protocol on every `/loop` invocation. See "Install the hook" below.
- **Generic shells / unmanaged harnesses.** Drive cadence with `while true` (Ralph-style — well-suited to focused mode), `cron` for fixed cadence, or rely on the agent to re-enter this protocol per turn. The spec tree on disk is the cross-tick memory; conversation context cannot be assumed to survive between iterations.

### Install the hook (Claude Code)

The integration is one shell script plus one entry in `~/.claude/settings.json`.

**1. Write the hook script.** Save as `~/.claude/hooks/loop-protocol-inject.sh` and `chmod +x`:

```bash
#!/bin/bash
# UserPromptSubmit: when prompt starts with /loop, inject pointer to @protocol/loop.

set -euo pipefail

input=$(cat)
prompt=$(printf '%s' "$input" | jq -r '.prompt // ""')

[[ "$prompt" =~ ^/loop([[:space:]]|$) ]] || { echo '{}'; exit 0; }

jq -n '{
  hookSpecificOutput: {
    hookEventName: "UserPromptSubmit",
    additionalContext: "Loop iterations use @protocol/loop. If not already loaded in this conversation, fetch it:\n\n    curly protocol @protocol/loop\n\nIt covers how to choose what to do each iteration and how to navigate the spec tree."
  }
}'
```

**2. Wire it into settings.** Add (or merge into) the `UserPromptSubmit` array in `~/.claude/settings.json`:

```json
{
  "hooks": {
    "UserPromptSubmit": [
      {
        "hooks": [
          { "type": "command", "command": "~/.claude/hooks/loop-protocol-inject.sh" }
        ]
      }
    ]
  }
}
```

That's the whole integration. The hook returns `{}` for every prompt that isn't `/loop`, so it's a no-op outside loops. When `/loop` fires, it injects a short pointer — the full protocol is fetched on demand via `curly protocol @protocol/loop` only when the iteration actually needs it. Nothing is inlined every tick.

Spec-tree pointing is project-local: the project's `CLAUDE.md` (or `SPEC.md` location) is where you tell the loop *which* tree to audit. The hook handles the protocol pointer; the project handles the tree pointer; the two are kept independent.

The harness handles cadence; this protocol handles decisions; the spec tree holds the truth.

---

## Composition

```
loop (modes: recursive-improvement, focused)
  └── chunk (execution: context, plan, implement, verify, record)
        └── orchestrate posture (delegate to sub-agents, keep context lean)
```

**Session = interactive.** When the loop encounters a feature that needs discussion, it pauses for a conversation with the user.

---

*Related: `@protocol/ratchet` · `@protocol/groom-protocols` · `@content/youtube/cole-medin/your-ai-second-brain-is-slowly-rotting-here-s-how-to-fix-it` · `@protocol/retro` · `@protocol/caper`*

---

*You're reading a protocol on [protocol.supply](https://protocol.supply) — hosted, searchable knowledge for AI agents. Think Agent Skills, as an API: bootstrap once (`curl -sL https://api.protocol.supply/bootstrap`), search (`/search?q=…`), fetch (`/@repo/slug`).*

*Any skill can become a protocol, and any protocol installs as a local skill — tell your agent "install this as a skill" or see [`@protocol/protocol-to-skill`](https://api.protocol.supply/@protocol/protocol-to-skill).*