- Home
- Skills
- Agents & Orchestration
- Agent Loops — Safe Multi-Step and Unattended Runs
Works with the AI Agents you already use
Agent Loops — Safe Multi-Step and Unattended Runs
Sets up multi-step or unattended agent loops with fresh context per step, separate review, stop conditions and rollback.
Free
Agent Loops — Safe Multi-Step and Unattended Runs
Example session with this skill installed
I want Claude to run unattended overnight and migrate our Express route handlers from callbacks to async/await. There are about 40 files in src/routes/; each still has handlers like this:
router.get("/orders/:id", function (req, res, next) {
Order.findById(req.params.id, function (err, order) {
if (err) return next(err);
if (!order) return res.status(404).json({ error: "not found" });
res.json(order);
});
});
Tests run with npm test and currently pass. Set up the loop so I can start it tonight and review in the morning.
- Read your context and instructions
- Compiled the agent loops
Summary
This is many small, independent changes to one codebase, all with the same objective, so the simplest pattern that fits is a
sequential pipeline per file: implement → de-sloppify → independent review → npm test → commit. Each step runs as a separate claude -p call with a fresh context, so a mistake in file 12 doesn't follow the run into file 13. SHARED_TASK_NOTES.md carries decisions forward. I didn't pick parallel fan-out: overnight, the time saved isn't worth the risk of merge conflicts in shared middleware. Nothing below has been executed yet; this is the setup for you to start.
Before you launch (checklist)
- A clean working tree and a dedicated branch:
git switch -c chore/async-routes. Or use an isolated worktree:git worktree add ../api-async-routes -b chore/async-routes. -
npm testpasses on that branch. The script checks this again and refuses to start if it fails. - A stop condition and a budget: 50 attempts maximum, 6 hours of wall-clock time, and a stop after 2 consecutive failed files or the same test failure twice.
- Rollback: one commit per green file, so any file can be reverted on its own in the morning.
- Check the
claudeflags againstclaude --helpon your installed version.
The context bridge: SHARED_TASK_NOTES.md
# Shared task notes: callbacks → async/await in src/routes/
## Objective
Convert callback-style route handlers to async/await with identical behavior:
same status codes, same response bodies, errors still reach next(err).
## Rules
- Touch only the file you were given (plus this notes file).
- Mongoose model calls return promises: use `await Model.findById(...)`, no callbacks.
- Wrap handler bodies in try/catch and call next(err), or use the project's existing async wrapper if one exists.
## Done
<!-- one line per file, appended by the loop -->
## Decisions
<!-- conventions chosen, so later files stay consistent -->
## Gotchas
<!-- anything surprising: shared helpers, streams, res.download, etc. -->
The driver script: loop.sh
#!/usr/bin/env bash
# Sequential pipeline: implement -> de-sloppify -> review -> test -> commit, one fresh context per step.
set -uo pipefail
MAX_RUNS=50
MAX_SECONDS=$((6 * 3600))
MAX_FAILS_IN_A_ROW=2
START=$(date +%s); RUNS=0; FAILS_IN_A_ROW=0; LAST_ERR=""
mkdir -p logs
stop() { echo "STOP: $1" | tee -a logs/loop.log; exit 1; }
git diff --quiet || stop "working tree not clean"
npm test > logs/baseline.log 2>&1 || stop "baseline tests fail; not starting"
# Completion signal: no file still has a callback-style handler.
mapfile -t FILES < <(grep -lE 'function *\(req, *res' src/routes/*.js)
[ ${#FILES[@]} -eq 0 ] && { echo "Nothing left to convert."; exit 0; }
for f in "${FILES[@]}"; do
RUNS=$((RUNS + 1))
[ "$RUNS" -gt "$MAX_RUNS" ] && stop "max runs reached"
[ $(( $(date +%s) - START )) -gt "$MAX_SECONDS" ] && stop "time budget exceeded"
name=$(basename "$f")
# 1. Implement: fresh context, edit tools only (no shell, so it can't touch git).
claude -p "Read SHARED_TASK_NOTES.md first. Convert the callback-style route handlers in $f to async/await, following the notes. Behavior must not change. Edit only $f. When done, append one line under 'Done' in SHARED_TASK_NOTES.md, plus any decision or gotcha later files need." \
--allowedTools "Read,Edit" > "logs/$name.implement.log" 2>&1
# Drift guard: only the target file and the notes may change.
CHANGED=$(git diff --name-only | grep -vxE "$f|SHARED_TASK_NOTES.md" || true)
[ -n "$CHANGED" ] && { git restore .; stop "off-objective edits in: $CHANGED"; }
# 2. De-sloppify: separate context whose only job is cleanup.
claude -p "Cleanup pass only, on the lines added in the uncommitted changes to $f. Remove dead code, leftover callback comments, debug prints, unused imports and inconsistent naming. Do not change behavior, do not touch lines that were not added, and do not redesign or rename anything." \
--allowedTools "Read,Edit" > "logs/$name.cleanup.log" 2>&1
# 3. Review: a context that did not write the change.
git diff -- "$f" | claude -p "You did not write this change. Read the Objective in SHARED_TASK_NOTES.md and judge the diff against it, not against earlier steps. Review this diff of a callbacks-to-async/await conversion for behavior changes: missing await, errors no longer reaching next(err), changed status codes or bodies, unhandled rejections. First line must be exactly PASS or FAIL, then the reasons." \
--allowedTools "Read" > "logs/$name.review.log" 2>&1
VERDICT=$(head -n 1 "logs/$name.review.log")
# 4. Verify and checkpoint.
if [ "$VERDICT" = "PASS" ] && npm test > "logs/$name.test.log" 2>&1; then
git add "$f" SHARED_TASK_NOTES.md
git commit -q -m "refactor(routes): async/await in $name"
FAILS_IN_A_ROW=0
else
git restore -- "$f"
echo "- FAILED: $name (review: $VERDICT), see logs/$name.*" >> SHARED_TASK_NOTES.md
FAILS_IN_A_ROW=$((FAILS_IN_A_ROW + 1))
ERR=$(tail -n 20 "logs/$name.test.log" 2>/dev/null | md5sum | cut -d' ' -f1)
[ -n "$LAST_ERR" ] && [ "$ERR" = "$LAST_ERR" ] && stop "same test failure repeated"
LAST_ERR=$ERR
[ "$FAILS_IN_A_ROW" -ge "$MAX_FAILS_IN_A_ROW" ] && stop "$MAX_FAILS_IN_A_ROW files failed in a row; needs a human"
fi
done
echo "Loop finished: $RUNS files attempted." | tee -a logs/loop.log
Start it (not run here): chmod +x loop.sh && ./loop.sh, inside the branch or worktree.
How the stop conditions map to the skill
| Stop signal | How the script enforces it |
|---|---|
| Completion | grep finds no callback-style handlers left, so the next start exits immediately |
| Max runs / max time | MAX_RUNS=50, MAX_SECONDS=6h |
| No progress across two checkpoints | 2 consecutive failed files: stop and escalate |
| The same error repeating | A hash of the last 20 test-log lines matches the previous failure |
| Drift off the objective | Any changed file other than the target and the notes |
Pick a cost ceiling that fits your plan. The script bounds runs and time; it does not track spend.
In the morning
- Read
logs/loop.logfor the stop reason andSHARED_TASK_NOTES.mdfor the Done, Decisions, Gotchas and FAILED lines. - Run
git log --oneline main..chore/async-routes: one commit per converted file, each revertible on its own. - Convert the FAILED files by hand or in an attended session; they are the ones the loop couldn't defend.
- Before opening the PR, run one full review of the branch in a fresh context (the
reviewing-codeskill or/dual-review). Push and open the PR yourself.
If the loop wedges instead of stopping cleanly (repeating the same action, or burning budget without commits), switch to the debugging-agent-runs skill.
Connects securely to your tools. The creator never sees your data.
About this skill
Running Agent Loops is a playbook for driving work across many steps or iterations, including unattended runs, without the run drifting, looping, or shipping sloppy code. The trade-off it is built around is isolation versus continuity. A fresh context for each step prevents drift, but then whatever needs to carry over has to be carried deliberately.
Principles applied to every loop:
- Each step (
claude -por a subagent) starts with a fresh context. - The reviewer is never the author.
- Two focused passes beat one heavily constrained pass.
- Every loop has an explicit stop condition: maximum runs, cost, time, or a completion signal.
Four patterns, from simplest to most involved:
- Sequential pipeline: implement → de-sloppify → verify → commit.
- PR loop: implement → review → fix → checks, repeated until green or out of budget.
- Parallel fan-out: an orchestrator assigns each agent a distinct direction, run in waves of 3–5.
- RFC → DAG: work units with dependencies, isolated worktrees, a merge queue.
Also covered:
- The cross-iteration bridge: a
SHARED_TASK_NOTES.mdfile each step reads at the start and updates at the end. - The de-sloppify pass: a separate cleanup step that removes dead code, debug prints, and over-engineering. The pass is bounded: it cleans only the lines the step added and never redesigns, renames or widens the step's scope. Every step is checked against the original contract, not the previous step's output, so drift can't build up across iterations.
- A pre-launch safety checklist: green baseline tests, budget, a branch or worktree for rollback, checkpoints, and clear rules for when to escalate to a human (no progress across two checkpoints, a repeated error, off-objective drift, budget exceeded).
Triggers on: "loop", "run autonomously", "iterate until it's done", chaining claude -p calls, fanning out parallel agents, or setting up an implement → verify → commit cycle. It does not trigger for one-shot tasks.
The skill is a focused SKILL.md plus the slop catalog it cites for the cleanup pass (bundled under shared/). Free and MIT-licensed, part of claude-skills-czl.
Source on GitHub: this skill · full repository
Loops assume a shell, git and a headless agent CLI (examples use claude -p), and each iteration costs model usage. Every loop needs explicit stop conditions; the cleanup pass touches only lines the step added. Pushing and opening PRs are left to you and the related skills.
How to use
- 1
Connect your agent to the Agensi MCP
Copy the prompt and paste it into Claude, ChatGPT, Cursor or any agent that supports MCP. It sets up the connection for you. Manual setup
- 2
Sign in to Agensi
Your agent shows a sign-in link. Sign in and click Allow.
- 3
Ask for what you need
Your agent loads this skill and uses it on your task. It always asks before buying a skill.
Reviews
No reviews yet
Be one of the first to try it. Every listed skill goes through the trust checks below.
Security scanned
Checked by our 8-point scan before listing
Fresh listing
Recently published to Agensi
Free to use
No account required to browse
Trust & safety
Security scan
Security scan passed 9 days ago
- Free with an Agensi account
- Software
Git
Permissions
File Scopes
- Reads files: yes. It reads the code, its `learnings/` folder, and the shared notes file between iterations. - Edits files: yes. The loops it sets up edit code through each step's agent, and maintain `SHARED_TASK_NOTES.md` (or the project's plan file). - Shell commands: yes, in the loops it sets up: the headless agent CLI (`claude -p`), the project's test and check commands, and git for branches, worktrees, and per-step commits. - Network access: only what the agent CLI itself uses to reach its model API. The skill adds no other network calls. - Git/GitHub: it creates local commits on a branch or worktree as rollback checkpoints. The skill doesn't push or post to GitHub; the review and PR steps are handed to the `reviewing-code` and `writing-pull-requests` skills.
What's inside
Frequently Asked Questions
New in Agents & Orchestration
Find more skills like this on the Claude Skills Marketplace, the Codex Skills Marketplace and the Gemini Skills Marketplace, or browse Claude Skills for Agents & Orchestration.