Mastering Loop Engineering: 6 Practical Scenarios to Supercharge Your AI Workflows

For the past two years, the vast majority of people have been using AI the exact same way: write a prompt, wait for a response, read it, add another line, and wait again. You hold the reins, pushing the conversation forward one round at a time.

By mid-2026, the conversation shifted drastically. Peter Steinberger, the author of OpenClaw, posted a tweet (with over two million views) stating: “You shouldn’t be prompting your coding agent anymore; you should be designing the loops that prompt the agent for you.” Boris Cherny, who leads Claude Code at Anthropic, shared a similar experience: “I don’t prompt Claude anymore. I have a bunch of loops running that prompt Claude and decide the next steps. My job is to write the loops.” Soon after, Addy Osmani labeled this paradigm 「Loop Engineering」.

To put it simply:

「Loop Engineering is the shift from prompting an AI yourself to designing a system that continuously prompts the AI on your behalf.」

Your value as a human hasn’t disappeared; it has simply relocated. On one side, you provide 「intent」—defining what you want so clearly that the outcome is verifiable. On the other side, you bear 「accountability」—the results, for better or worse, are ultimately your responsibility. The repetitive back-and-forth of asking, checking, and rewriting can now be handed over to loops.


1. What Exactly Is a Loop?

To understand Loop Engineering, we need to see where it fits in the broader technological landscape. Over the years, the leverage point has consistently moved further away from “bare model calls.”

The position of Loop Engineering in the tech spectrum

The difference between a loop and a cron job is that 「a loop contains an agent that decides what to do next」. A cron job executes a static script; a loop observes the current state, chooses an action, executes it, checks the result, and then decides whether to continue, retry, roll back, or stop. This “observe-decide-act-verify” cycle is the engine driving it. Most major AI vendors have gravitated toward this structure, which ultimately traces back to the 「ReAct (Reasoning + Acting) framework」 proposed by Princeton and Google in 2022.

The Anatomy of a Loop: Five Core Components and a State Layer

The six-piece structure of Loop Engineering

The sixth component—the 「state file」—is the one most beginners overlook. Since models forget everything after each run, the state file allows today’s execution to remember what yesterday’s execution accomplished. Without it, many systems aren’t really looping; they are simply repeating the same first step over and over.

If you remember this 「shape」—this six-piece skeleton—while forgetting every specific command, you have mastered Loop Engineering. If you memorize the commands while missing the shape, you have merely learned this month’s command-line interface.


2. How Do You Know If a Task Should Be a Loop?

Don’t try to turn everything into a loop. Run it through three filters first:

Filter Description
「Frequency」 You do it often enough that the cost of designing the system is worth it.
「Verifiability」 “Done” can be expressed as a check that an agent can actually validate. If you can’t define what “success” looks like, the loop won’t know when to stop.
「Value」 The output justifies the token burn. Loops have a baseline cost in time and money; trivial tasks aren’t worth it.

If all three conditions are met, it wants to be a loop. If not, stick to manual prompting or a simple script.

Another Way to Look at It: The Nature of the Work

「Process-Oriented」: The steps are known, the order is fixed, and the outcome is predictable (e.g., invoice received → matched → paid). This is a flowchart with no decision branches; use traditional automation (scripts, RPA). No loop is needed.

「Tool-Assisted」: The goal is clear, but the path is variable. You ask, the AI answers, and you decide. You’re still in the driver’s seat. This is where most AI copilots sit today.

「Goal-Driven」: You set a goal and the boundaries, and let the system figure out the steps: assess, decide, act, check, and repeat until completion—or escalate high-risk decisions to you. 「This is the sweet spot for loops.」

The real question isn’t “Can I automate this?” but rather: 「”Where do I install a loop that can judge the next step?”」


3. Building Your First Loop: A Step-by-Step Guide

Now that we’ve covered the theory, let’s build a common “Morning Maintenance Loop.” Try this in a throwaway test repository first; don’t point it at your critical production code just yet, as it will modify files.

The finished product looks roughly like this:

Every weekday at 9 AM:               # ① Heartbeat
  Read progress.md                  # ⑥ State file (memory)
  Find last night's CI failures + new issues  # The work
  For each item:
    Draft a fix in an isolated checkout  # ② Worktree
    Use the project's triage skill       # ③ Skill
    Have a separate reviewer score it    # ⑤ Sub-agent (Doer/Checker split)
    PASS: Open a PR                     # ④ Connector
    Risk: Log it in progress.md for human review
  Update progress.md                   # ⑥ State file

Now, let’s assemble it piece by piece.

Step 0: Select a Task and Define “Done” as a Verifiable Condition

This is the hardest part. “Improve the code” is too vague. “All tests in test/auth pass and npm run lint is clean” is concrete. Write the stopping condition as an acceptance criteria, filling in all four fields as best you can:

Defining verifiable acceptance criteria

The agent remains the executor; this is the checklist it must pass.

Step 1: Install the Heartbeat (So It Starts Itself)

Heartbeats come in four flavors, ranging from “stops when I close this session” to “runs without you completely.”

「① In-Session Loops (Watch it run; stops when you close the session)」
Good for keeping an eye on a long task until it finishes.

# Claude Code: Runs every 5 minutes while the session is open
/loop 5m Check if the deployment has finished and tell me the result

# OpenCode: Using shell as the heartbeat
while true; do
  opencode run "Check if the deployment is complete. If done, reply DONE."
  sleep 300
done

「② Run Until Goal (Let the loop judge when to stop)」

# Claude Code: Provide a condition it can verify through its own output
/goal All tests under test/auth pass and npm run lint is clean.

# OpenCode: Using shell + exit codes to stop
for i in $(seq 1 8); do          # Always cap it—don't run infinitely
  opencode run "Make the test/auth tests pass and fix lint errors."
  if npm test -- test/auth && npm run lint; then
    echo "Goal achieved on attempt $i"; break
  fi
done

The beauty of /goal is that after each turn, a separate small model reads the log and judges whether the goal has been met. The agent writing the code does not grade itself. It doesn’t have a built-in “stop after N tries,” so you must write that into the condition (e.g., “stop after 20 turns”).

「③ Unattended Scheduled Loops (Runs while you sleep)」

# Using cron on your own machine: every weekday at 9 AM
0 9 * * 1-5 cd /path/to/repo && claude -p "Check the CI board and summarize failures" >> ~/cron.log 2>&1

# OpenCode version
0 9 * * 1-5 cd /path/to/repo && opencode run "Check the CI board and summarize failures" >> ~/cron.log 2>&1

If you want it to run even when your laptop is off, use a cloud routine (e.g., on runroutine.io) or trigger it via GitHub Actions’ schedule.

「④ Event-Driven (Triggered by PR openings, CI failures, or messages)」
For example, a GitHub Action for PR review:

on:
  pull_request:
    types: [opened, synchronize, reopened]
# After trigger, let the agent review the PR diff

「Give your loop two brakes: a success condition and a cap.」 The success condition defines completion. The cap defines the maximum number of iterations, minutes, or dollars. Without a cap, your budget will slowly burn on an unreachable goal.

Step 2: Put the Steps into a Skill (Keep the Loop Prompt to One Line)

Anything you find yourself explaining repeatedly belongs in a skill file. This allows your scheduled task’s prompt to shrink to a single line like “Run the daily-triage skill,” while the details remain in version control where anyone can modify them.

Here’s a realistic SKILL.md:

---
name: daily-triage
description: Morning maintenance: read progress, collect last night's CI failures,
  new issues, and audit alerts; draft fixes (each checked by a separate reviewer);
  open PRs for those passing, write risky ones to progress.md for human review.
---
# Daily Triage (Follow the order. Do not skip the progress file—it's your only memory.)

## 1. Read Memory
- Open progress.md and read the "In Progress" and "Needs Human" sections.
- If something is in "Completed," do not redo it.

## 2. Find Work (In order, max 5 items)
1. CI failures since the last run.
2. Open issues tagged `bug` or `maintenance`.
3. New alerts from `npm audit` (or your project's audit tool).

## 3. Process Each Item
- Create an isolated checkout (git worktree, or a new branch `claude/<short-slug>`).
- Draft the minimal change to solve *that one* problem. Do not bundle multiple fixes.
- Hand the diff to the reviewer agent and wait for a verdict.

## 4. Decide Based on the Verdict
- PASS & Low Risk (no public API changes, no data migrations, no file deletions): Open a PR. Title: `fix: <one line>`, link the issue.
- FAIL or touches anything risky: Do NOT open a PR. Append to "Needs Human" in progress.md. Explain what you tried and why you stopped.

## 5. Update Memory
- Move completed items to "Completed" with today's date. Save progress.md.

## Golden Rules
- Open at most 5 PRs per run. Never push directly to main. Use only `claude/*` branches. When in doubt, escalate.

Step 3: Split “Doer” and “Checker”—Add a Reviewer Sub-Agent

A critical rule in loops: 「The agent that writes the code must not grade its own work.」 Models are notoriously generous when scoring themselves. You need a separate, read-only reviewer (often using a cheaper model) to run the tests, check the specs, and only reply with PASS or FAIL.

---
name: reviewer
description: Check a diff against specs and test results. Reply with PASS or FAIL. Make no changes.
tools: Read, Bash(npm test*), Bash(npm run lint*), Bash(git diff*)
model: claude-haiku-4-5
---
You are a strict, read-only reviewer. You never modify files.
1. Run the tests and linter yourself. Read the output. Do not trust "it says it passed."
2. Check the changes against the project conventions in CLAUDE.md and relevant specs.
3. Look for bugs, missed edge cases, security risks, and changes to public behavior.
Then, reply ONLY with one of these:
- PASS: Followed by one line on what you verified.
- FAIL: Followed by specific reasons, one per line.
"Looks fine to me" is NOT a valid PASS. The tests must actually pass, and the change must do only what was asked.

「Note」: Sub-agents consume more tokens. Use them where a second opinion matters—like any loop that commits changes without your direct oversight. Skip them for trivial, read-only tasks.

Step 4: Install the State File

The model forgets everything after each run. 「Memory must live outside the model—on disk.」 Use two layers:

  • 「Rule files」 (CLAUDE.md, AGENTS.md): Store stable habits. Keep them short to avoid burning tokens on every read.
  • 「Progress files」: Log “what was tried, what passed, and what’s still open.”
<!-- progress.md: The loop's cross-run memory -->
## Completed
- 2026-06-22: Fixed flaky test in test/auth (added retry for token refresh)
## In Progress
- Dependency audit: 7 alerts, fixed 3; lodash upgrade hit an API change.
## Needs Human
- Image library CVE-2026-xxxx: The fix changes output format. Escalating to maintainer.

The golden rule: 「At the start of each run, read it. At the end, update it.」 If your loop keeps making the same mistake, don’t write a more convoluted prompt; write the lesson into the rule file so every future run can read it.

Step 5: Connect Tools (So It Can Act)

A loop that can only read files is limited to “talking.” 「Connectors」 (often based on MCP) let it open PRs, update tickets, send Slack messages, query databases, and call staging APIs. The difference between a system that says “here is the fix” and one that opens a PR, links a ticket, and posts to the channel after tests pass is huge. Plug your manual connectors into your scheduled or cloud routine.


Putting It All Together: A Real Morning

You’ve done the design once. One morning, you wake up, and the record might look like this:

[09:00] daily-triage triggered
  → Read progress.md: 1 item in progress (lodash), no new flags.
  → Found: 2 CI failures last night, 1 new npm-audit alert.
  → CI failure #1 (flaky auth test):
        Drafted fix in claude/fix-auth-retry
        Reviewer → PASS (tests green; retry logic for token refresh; no API change) → Opened PR #142
  → CI failure #2 (type error in report.ts):
        Drafted fix → Reviewer → PASS → Opened PR #143
  → Alert (image library): Fix changes output format.
        Reviewer → FAIL (public behavior change) → Appended to "Needs Human" in progress.md. No PR.
  → Updated progress.md. Exited.
[You, 09:30] Two PRs to review, one decision to make. You haven't typed a single line of code.

「This is Loop Engineering in practice」: finding work, drafting fixes, checking them, shipping the safe ones, and only bringing the truly ambiguous decisions to your attention. Whether you use Claude Code or OpenCode primarily affects the heartbeat and execution environment; the underlying design—skills, state files, worktrees, doer/checker separation, connectors—remains remarkably similar.


4. What Repetitive Work Can These Loops Save?

Once you have the skeleton down, you can transplant this “morning maintenance” pattern to other areas. Before you scale, ask one question: 「Can the output be verified by a command, a checklist, or another agent?」

Code & Engineering

Tasks you can hand off:

  • Daily CI failure triage
  • Issue triage
  • Fixing a recurring class of bugs
  • Running dependency upgrades
  • Framework migrations
  • Reviewing PRs one by one

「Common variations:」

  • 「”Run until tests pass”」: /goal All tests in test/auth pass and lint is clean (let the small model judge).
  • 「Framework/API migration (Queue-clear mode)」: Find the next file using the old API, migrate it, run tests. Stop when “no files match the old pattern.” Cap at 200 iterations.
  • 「Security vulnerability fixing at scale」: Use a simple LLM judge to score files (probability of memory safety issues × ease of exploitation from the web). The agent tries multiple approaches to trigger a bug. Verification is split: trigger a crash first, then have a verifier confirm the report is valid. This structure also works for performance optimization and technical debt.

Content Pipelines

Tasks you can hand off:

  • Batch copy-editing
  • Turning rough ideas into hooks
  • Splitting long content into multi-platform versions
  • Generating articles to fill gaps

Here, “completion” must be countable. For example:

/goal Rewrite each line in captions.txt to under 150 characters without hashtags,
      until all are done. Don't touch other files. Max 30 turns.
      # Verifiable: 0 lines over 150 chars or containing #

/goal Turn each of the 20 rough ideas in ideas.txt into a 10-word hook.
      Until all 20 are rewritten.
      # Verifiable: 20 entries rewritten

A larger variation is a multi-agent pipeline: Agent A generates illustrated articles based on content gaps, Agent B pushes them for publishing. But be clear-eyed here: 「The stronger the model, the more the bottleneck becomes your taste as the director.」 Loops amplify the judgment embedded in your rubrics, skills, and verification steps. If that judgment is sloppy, the loop will simply produce stuff you shouldn’t publish, at higher speed.

Information Monitoring & Research

Tasks you can hand off:

  • Monitoring logs and service health
  • Tracking competitor pricing pages
  • Watching API changelogs
  • Monitoring a specific news domain
  • Conducting competitive research

Four trigger patterns:

Trigger Description Example
Heartbeat Runs continuously at short intervals Check staging error logs every 5 minutes; open an issue if error rate exceeds 1%.
Scheduled Runs a batch at a fixed time Review all PRs older than 3 days every weekday at 10 AM.
Hook Runs once on an event Trigger when a PR is pushed, CI fails, or a message arrives.
Goal Iterates until a condition is met Identify all public competitors in our category, score them on five dimensions, and draft a positioning brief.

You can also treat a live webpage as a heartbeat: monitor a set of URLs and trigger when content changes. Pricing page changed? Start the competitive response. Changelog updated? Trigger a documentation rewrite. Status page incident? Wake the on-call engineer.

Document Generation

Tasks you can hand off:

  • Writing 5-line summaries for a stack of PDFs
  • Structuring raw data into reports
  • Drafting proposals/solutions from templates
  • Maintaining documentation that goes stale

The core pattern is “「Queue clearing + Reflection + Multi-agent checking」“:

/goal Write a 5-line plain-language summary for each PDF in the reports folder,
      into summaries.md, until each has one. Don't modify the PDFs. Max 40 turns.
      # Verifiable: each PDF has a corresponding summary entry.

Select the loop pattern based on risk:

  • 「Reflection + Schema validation」: Draft structured reports, validate against a schema to fill missing fields, and have a human review. Good for field reports and forms.
  • 「Multi-agent review + Human gate」: Agent A drafts, Agent B checks for compliance and flags sensitive identifiers, human signs off. Good for clinical plans and compliance docs.
  • 「Reflection + Checklist」: Draft, check against a methodological framework, word count, format, and data consistency. Flag unsupported assertions. Good for proposals.
  • 「Autonomous with guardrails」: Validate item by item; escalate only what fails automated checks (typically <5%). Good for data batch processing.

Personal Tasks & Office Work

Tasks you can hand off:

  • Cleaning an overflowing inbox
  • That monthly report you dread
  • Customer service ticket clearance

You don’t need complexity. Build your first autonomous agent with “Goal + Timer.” Create a routine: “Every morning, read unread emails, summarize the top 3 in one line each, send them to me on Slack. Don’t reply to anything.” Connect Gmail/Slack, set for 9 AM daily. To level up, add a skill with your handling rules, and an independent checker that re-opens tickets if it decides they need a human.

「Safety advice」: Start read-only. Let it “summarize and report” for a few days. Set hard limits in plain language (“Don’t reply,” “Don’t delete”). Watch the first few runs before letting it take action.

Business & Operations

Handle decisions that are made periodically but should be continuous. Pricing reviews every quarter, HR surveys done annually but actioned six months later, product priorities set per sprint based on last month’s data—all of these can be revisited.

The shift is from a “Capability Map” to a “Loop Map.” For each capability, ask: Is it process-oriented (traditional automation)? Tool-assisted (better tools for humans)? Or goal-driven (deploy a bounded, escalating, human-supervised loop)? Identify positions like “continuously evaluate pricing signals and suggest real-time adjustments” or “continuously track early attrition and flag intervention points before the resignation letter hits.”

Also consider industry reality: Gartner predicts that by the end of 2027, over 「40% of agentic AI projects」 will be scrapped due to cost overruns, unclear value, and poor risk control. Many of these failures share a root cause: shoving agents into fragmented processes without clearly defining where the loop should sit and what it needs to run.


5. Risks and Boundaries

Loops change how you work, but they don’t delete you from the process. The more powerful the loop, the more pressing these three issues become.

1. Stopping a Loop Is Hard

Every loop must have 「hard brakes」. Install all three if possible:

  • 「Hard iteration cap」: A loop that can’t finish shouldn’t spin forever.
  • 「No-progress detection」: If nothing changed in the last few turns, stop.
  • 「Token and budget cap」: Stop before the bill becomes unmanageable.

Without these, cost overruns are inevitable. A rough cost sense: One “beat” (maker + checker) reads about 40k tokens and writes 6k tokens. At Sonnet 4.6 pricing, that’s roughly **20/month—reasonable. But if you run the same loop every 5 minutes all day, the number of beats multiplies a hundredfold, easily exceeding $1,000/month—often without producing proportional value.

「What really drives costs is frequency.」 Three ways to save:

  • 「Model tiering」: Use strong models for planning and checking, cheap models for the grunt work. This saves the most.
  • 「Keep prompts and rule files short」.
  • 「Lower frequency」: Running once an hour is about 12x cheaper than every 5 minutes.

2. Verification Is Still Your Responsibility

If it runs unattended, it will also make mistakes unattended. Splitting the doer and checker gives “done” more weight, but 「”done” is just a statement—you need the evidence.」 Read the diffs the loop opens. Take responsibility for the code it produces. The most honest checkers are the test runner and linter. No command can convince itself “the work is good.”

3. Understanding Will Thin Out

Loops ship code you didn’t write into your repository faster. The gap between “what’s in the repo” and “what you actually understand” widens. This is 「comprehension debt」. Once a loop runs, you are also more prone to accept its output without question—「cognitive surrender」.

Designed with intent, loops accelerate work you already understand. Designed to escape thinking, they move you into increasingly unfamiliar territory. The loop can’t distinguish between these two scenarios; you have to.


6. Getting Started: The Maturity Ladder

Don’t aim for “auto-merge” on day one. Climb the ladder one rung at a time.

The Loop Engineering maturity ladder

At each level, ensure the output is something you would already accept manually before moving up.

The Pre-Launch Safety Checklist

# Safety Measure
1 A clear success condition
2 Caps (iterations, minutes, spend)
3 Isolated branches or worktrees
4 A read-only checker
5 A state file
6 A human gate (risky/failing items go to a human; never push directly to main)
7 Logs or notifications (so you know if something breaks at night)

Missing any of these, and your loop becomes insecure, forgetful, or invisible in failure.

A Handy Formula

「AI Leverage = Your Skill × Your Clarity」

  • 「Clarity」: Your ability to define what “done” looks like in verifiable terms.
  • 「Skill」: Your ability to review the output and refine the loop.

Every year, tools will absorb more of the mechanical parts—orchestration, checking, scheduling. Last year, you needed shell scripts; this year, they are built into /goal, routines, and dynamic workflows. But tools cannot absorb the two edges: 「Intent」 (stating requirements until the outcome is verifiable) and 「Accountability」 (taking responsibility for what you ship). That’s why it’s called engineering.


Go build your loops. Hand off the repetitive, verifiable work. But build them the way an engineer would. Read the diffs they produce. Take responsibility for the quality. Write good skills. Define solid stopping conditions.

Loops can make you faster on work you already understand. They can also help you escape understanding things you really should. The tools won’t decide which path you take—you will.