---
name: ratchet-loop
description: >
  Designs and stands up an autonomous, single-agent improvement harness that treats a codebase, prompt, config, or parameter set as a programmable interface for iterative optimization. The agent proposes a motivated change, commits it, evaluates it against one hard metric, and keeps or reverts it via git — running as many cheap, reversible bets as a fixed time or iteration budget allows. Use this whenever the user wants to set up an autoresearch loop, build a self-improving harness, iterate on something automatically over a stretch of time, let an agent tune a metric unattended, or "ratchet" a number up over many small bets. Trigger on phrases like "set up an autoresearch loop," "build a self-improving harness," "iterate on this automatically," "let an agent tune this over N hours," "ratchet this metric up," or "run hundreds of small experiments against this." Project-agnostic — applies to ML training code, prompts, pricing/config parameters, SQL query plans, or any artifact with a measurable objective and a reversible history.
---

# Ratchet Loop Skill

## Overview
Most engineering iteration is bottlenecked by a human proposing, testing, and judging one change at a time. This skill designs a harness that removes the human from that inner loop entirely: an agent runs the propose → commit → evaluate → keep-or-revert cycle by itself, as many times as a fixed budget allows, against one hard metric it cannot argue with.

The payoff isn't steady, average improvement — it's rare, high-value outliers. A bounded, reversible environment lets the agent take hundreds of genuine bets instead of one carefully-reasoned guess. Most bets will fail cheaply and get reverted; the value comes from the ones that don't (see `power-law-engineering` for why concentrating on the tail beats optimizing the average).

This skill is **project-agnostic**: the artifact under iteration might be model training code, a prompt, a pricing config, a SQL query plan, an infra parameter set, or anything else with (a) a measurable objective and (b) a version-controllable state. Nothing in the harness design should assume a specific language, stack, or domain.

## When to Use
- The user wants an agent to improve something unattended over a stretch of time (a few minutes to overnight) rather than reviewing every change themselves
- There's a single number that already defines success (validation loss, latency, cost per unit, conversion rate, query runtime) or one can be constructed
- The artifact lives in git (or can be put there) so every state is reversible
- The user is comfortable with "many small reverted experiments" as the normal, expected shape of the run — not a sign something's broken

## When Not to Use
- No metric exists and one can't be constructed cheaply — don't force a fake number just to run the loop; go define the metric first, separately
- The change surface isn't reversible (e.g., destructive external side effects, real money moved, irreversible API calls with no dry-run mode) — reversibility is the whole safety model here, and without it the loop is not safe to leave unattended
- A single well-reasoned change is clearly enough (small, well-understood fix) — the overhead of a harness isn't worth it for a one-shot edit

## Core Operating Rules

### 1. Lock the Hard Metric First
Before any harness code is written, force this to a single scalar:
- Must be deterministic (or averaged over enough trials to be stable) and cheap enough to compute hundreds of times within the budget
- Must be computable automatically, with no human judgment call in the loop
- State it explicitly as "higher is better" or "lower is better" before starting
- If the user's stated goal doesn't reduce to one number, that is the actual first task — don't start iterating on a fuzzy proxy and call it done

### 2. Reversible Environment via Git
Git is the ratchet mechanism, not just version history:
- One commit per iteration, no exceptions
- Before proposing a change, the agent must be on a known-good, previously-evaluated commit
- After a change: evaluate → if it passes the keep criteria, leave it committed and move forward; if not, `git reset --hard` to the prior good commit before proposing the next change
- Never let an unevaluated change sit underneath the next proposed change — one bet in flight at a time

### 3. Guardrail Gate, Not Metric-Only (default ON)
A metric-only loop will cheerfully wreck anything the metric doesn't measure. By default, require a **non-regression guardrail** alongside the hard metric — whatever "still works" means for this artifact (existing tests pass, output still validates against a schema, latency doesn't blow through a ceiling, security checks still pass). A change is kept only if the guardrail holds AND the metric improved.
- State the guardrail explicitly before starting, in project-agnostic terms: "the existing verification step for this artifact must still pass"
- The user can explicitly opt out of the guardrail for a given run, but the default is on — silence should never mean "no guardrail"
- If no guardrail can be defined for a given artifact, say so out loud before proceeding rather than silently running metric-only

### 4. Budget: Time-Boxed, Project-Agnostic
The stop condition is a **fixed wall-clock time budget**, stated up front (e.g., "30 minutes," "overnight," "2 hours") — not a fixed iteration count, since iteration cost varies wildly by artifact (a prompt eval takes seconds, a training run takes minutes). Time budget is the one unit that means the same thing regardless of what's being iterated on.
- Budget is a hard ceiling: when time runs out, stop after the current iteration finishes evaluating — never mid-evaluation, never "just one more"
- In addition to the time ceiling, set a **consecutive-revert kill switch** (e.g., N consecutive reverted iterations with no accepted change) as an early-exit signal — this catches a stalled or misconfigured loop long before the time budget would, and is itself project-agnostic since it only counts kept vs. reverted, not domain-specific signals
- Report both numbers at the end: time used vs. budget, and iterations run vs. the revert-streak threshold that was in effect

### 5. Motivated-Change Discipline
Every proposed change carries a one-line hypothesis before it's made: what is expected to move the metric, and why. This is not optional narration — it's what makes the log legible afterward. A change with no stated hypothesis is not ready to commit.

### 6. Logging Is a Deliverable, Not a Side Effect
Every iteration is logged with: hypothesis, diff (or summary of it), metric before/after, guardrail pass/fail, kept or reverted, and running best-so-far. At the end, the log — not just the final state of the artifact — is handed back, because:
- It's what lets a human find and understand the outlier iteration that actually mattered
- It's what makes the run auditable later (why was this kept? what got tried and abandoned?)
- It turns "the agent ran for 2 hours" into a reviewable trail rather than a black box

### 7. Output Requirements
Always deliver, in this order:
1. The locked metric (direction stated: higher/lower is better) and the guardrail definition (or explicit "none" with reasoning)
2. The time budget and revert-streak kill switch that were set
3. The full iteration log (hypothesis / result / kept-or-reverted per iteration)
4. Final state: best metric achieved, which commit it lives on, and how it got there in 2-3 sentences
5. One explicit call-out of anything the guardrail didn't cover, if relevant — so the human knows what wasn't checked

## Worked Example

**Input**: "Take this recommendation model's feature pipeline and try to improve validation AUC over the next hour. Don't break the existing test suite."

**Setup**:
- Metric: validation AUC, higher is better, computed on a fixed held-out split (cheap enough to run every iteration)
- Guardrail: existing test suite must pass (default ON, and the user named it explicitly here)
- Budget: 60 minutes wall-clock, kill switch at 15 consecutive reverts
- Environment: one commit per iteration on a scratch branch, `git reset --hard` on any reverted attempt

**Loop behavior**: propose a feature transform → commit → run tests (guardrail) → run AUC eval (metric) → keep if tests pass and AUC improved, else reset. Repeat until 60 minutes elapse or 15 reverts happen in a row.

**Output at the end**: iteration log showing (say) 40 attempts, 6 kept, best AUC improvement of +2.3 points from a single feature-interaction term found around iteration 24 — flagged as the outlier worth understanding, per power-law thinking, rather than treated as one point among forty equally-weighted attempts.

## Advanced Techniques
- **Pairing with power-law-engineering**: after the run, apply that skill's "measure the tail" rule directly — the log's best-and-worst iterations matter more than the average iteration's metric delta.
- **Multi-armed variants**: instead of one hypothesis per iteration, propose 2-3 divergent changes per round and keep the best that clears the guardrail — trades iteration count for higher signal per round, still fits the same time budget.
- **Escalating guardrails**: start a long run with a cheap guardrail (fast smoke test) and tighten it (full test suite) only for changes that clear an initial metric bar — keeps early iterations fast without weakening the final bar.
- **Cold-start metric construction**: if the user has a fuzzy goal but no metric yet, treat metric construction as its own short prior step, not as part of the loop's budget.

## Quality Checklist (run before starting the loop)
- [ ] Metric is a single scalar, direction stated, cheap enough to run hundreds of times in budget
- [ ] Guardrail defined (or explicitly, out loud, declared absent) — never silently metric-only
- [ ] Time budget stated in wall-clock terms, not iteration count
- [ ] Consecutive-revert kill switch set
- [ ] One commit per iteration, reset-to-last-good enforced before each new proposal
- [ ] Every iteration will be logged with hypothesis, result, and keep/revert decision
- [ ] Nothing in the setup assumes a specific language, stack, or domain
