Access Granted

    Loop Engineering
    Playbook

    The practical guide to designing AI loops that stop only when a real check passes.

    Start here

    Build one safe loop before reading everything.

    The guide is long because the edge cases matter. Your first pass only needs these five decisions.

    1. 01Pick one AI behavior you corrected three times
    2. 02Decide whether it runs once or from a trigger
    3. 03Write the goal, context, action, check, and retry limit
    4. 04Choose the lowest verifier rung that proves the task worked
    5. 05Add a hard stop, smallest-safe-fix rule, and human gate for anything risky
    How to Read This

    Treat this like a workshop

    Use it like a workshop. Pick one real workflow, choose the loop shape, fill the canvas, then run the smallest safe version.

    10 minutes

    Skim the use cases, choose a loop shape, and decide if your task qualifies.

    30 minutes

    Fill the loop canvas and pick the verifier rung. Stop before building tools.

    7 days

    Run the build track, record failures, add rules, then decide whether to schedule it.

    Start Here

    Where and when to use loop engineering

    Use loop engineering when AI is allowed to do work, but only trusted after an external check passes. The loop can run once for a single task, or it can run repeatedly from a trigger.

    Scenario 1

    Single task loop

    You trigger it once. The agent may still loop internally: act, check, fix, rerun. It stops when the check passes or the retry limit is hit.

    single-run example
    Fix this failing test.
    Loop until the test passes.
    Stop after 3 attempts or if the fix touches auth.
    Scenario 2

    Triggered loop

    A schedule, webhook, queue, inbox item, or new file starts the same task loop again. The trigger repeats. The proof gate stays the same.

    triggered example
    Every weekday at 8:00:
    Read new replies.
    Draft follow-ups.
    Send nothing until the voice gate passes and I approve.
    Code repair

    Run tests, patch one failure, rerun, stop at green or handoff.

    Research cleanup

    Collect sources, reject dead links, keep only items that match criteria.

    Content quality

    Draft, validate banned phrases, score, revise until the threshold passes.

    Data workflows

    Normalize rows, validate schema, quarantine records that fail checks.

    Ops monitoring

    Inspect logs, classify incidents, propose action, escalate on risky cases.

    Resource publishing

    Create page, wire registry, check routes, build, then stop.

    Use the playbook when
    The agent can take an action, an outside check can reject bad work, and you can name what happens after pass, fail, and timeout.
    Do not use it when
    The work is mostly taste, strategy, sensitive relationships, high-risk permissions, or open-ended exploration. Use a human-led workflow there.
    Shape Chooser

    Choose the simplest loop shape that fits

    The best agent systems start simple. A single prompt is enough until the work needs memory, tools, branching, evaluation, or a recurring trigger.

    Prompt chain
    Use when

    The work has fixed steps, like outline, draft, edit, publish.

    Routing loop
    Use when

    Inputs arrive in categories, like support, sales, finance, or urgent.

    Evaluator loop
    Use when

    Quality improves when a separate check gives feedback and asks for revision.

    Tool-use loop
    Use when

    The agent must search, read, write, calculate, update a CRM, or inspect a system.

    Human approval loop
    Use when

    The agent can prepare work, but a person must approve the final action.

    Scheduled monitor
    Use when

    The same loop should run from a calendar, inbox, webhook, queue, or file drop.

    plain-language loop recipe
    Trigger: What starts the loop?
    Goal: What should be true when it finishes?
    Context: What does it need to read first?
    Tools: What is it allowed to do?
    Check: What outside signal proves it worked?
    State: Where does it record what happened?
    Fail path: What changes before the next attempt?
    Stop: When does it stop or ask a human?
    Complexity rule
    If a prompt chain can solve it, do not build an agent. If a human approval loop can control the risk, do not pretend the system is fully autonomous.
    Loop Canvas

    Fill this before you automate

    This is the one-page version. If you cannot fill every box, the loop is not ready for tools, scheduling, or autonomy.

    01
    Trigger

    What starts it? Manual click, schedule, webhook, inbox, file, or queue.

    02
    Goal

    What should be true when the loop finishes?

    03
    Context

    What must the agent read before acting?

    04
    Action

    What is it allowed to change, draft, update, or send?

    05
    Check

    What external signal rejects bad work?

    06
    Retry

    What changes before the next attempt?

    07
    State

    Where does it record decisions, failures, and lessons?

    08
    Human Gate

    Which cases must pause for approval?

    09
    Stop

    When does it stop because it passed, failed, or timed out?

    copyable blank canvas
    Loop name:
    Owner:
    Trigger:
    Goal:
    Context:
    Allowed actions:
    Verifier:
    Retry rule:
    State file or log:
    Human gate:
    Stop condition:
    Rollback or recovery path:
    Starter Templates

    Copy these before building anything custom

    Replace the bracketed parts with your tools, data, and approval rules. These work in no-code automations, Claude projects, Zapier agents, custom scripts, or a human-run checklist.

    sales follow-up loop
    Trigger: New reply or manual review.
    Goal: Produce one accurate next message.
    Context: Thread history, CRM notes, offer, last promise made.
    Action: Draft the reply and identify the next step.
    Check: Facts match the thread, tone fits the relationship, no unsupported promise.
    Retry: Revise once using the failed check.
    Human gate: Always approve before sending.
    Stop: Approved draft queued or escalated to owner.
    research brief loop
    Trigger: New research question.
    Goal: Produce a short brief with evidence.
    Context: Question, date range, allowed sources, disallowed sources.
    Action: Search, collect sources, summarize claims.
    Check: Every important claim has a live source and source date.
    Retry: Replace weak links and remove unsupported claims.
    Human gate: Required before using the brief in public or paid work.
    Stop: Brief saved with source list and open questions.
    support triage loop
    Trigger: New support ticket.
    Goal: Classify the ticket and prepare the safest next action.
    Context: Customer record, product docs, refund policy, previous tickets.
    Action: Classify, draft reply, suggest account action.
    Check: Category is valid, policy is cited, risky actions are flagged.
    Retry: Reclassify if policy or customer status does not match.
    Human gate: Refunds, angry customers, legal language, or account changes.
    Stop: Reply queued, ticket routed, or human escalation created.
    content improvement loop
    Trigger: Draft ready for review.
    Goal: Produce a publish-ready draft.
    Context: Source notes, audience, voice rules, banned phrases, target format.
    Action: Edit the draft.
    Check: Validator passes and quality score clears the threshold.
    Retry: Fix only the failed criteria. Preserve sections that already pass.
    Human gate: Final taste, claims, and offer positioning.
    Stop: Draft queued with validation results.
    claim-check loop
    Trigger: Draft or research brief is ready.
    Goal: Make every factual claim defensible.
    Context: Draft, source list, date range, allowed sources.
    Action: Extract every factual or trend claim.
    Check: Each claim has evidence strength: strong / medium / weak / missing.
    Retry: Cite, narrow, qualify, or remove weak and missing claims.
    Human gate: Required before public or paid use.
    Stop: Every claim is sourced, personal, or narrowed enough to defend.
    personal admin loop
    Trigger: New email, receipt, document, or reminder.
    Goal: Decide archive, reply, task, calendar, or escalation.
    Context: Inbox item, calendar, existing task list, preferences.
    Action: Extract needed action and draft the next step.
    Check: Date, person, amount, and commitment are present when needed.
    Retry: Ask for missing information or mark as unclear.
    Human gate: Money movement, contracts, medical, travel purchase, or sensitive reply.
    Stop: Item archived, task created, event drafted, or human review requested.
    Practice

    Three checkpoints before you build

    Checkpoint 1
    Name the loop

    Write the loop in one sentence: When X happens, AI does Y, checks Z, and stops when Q is true.

    Checkpoint 2
    Find the weak box

    Look at the canvas and mark the weakest box. Most failed loops have weak context, weak verifier, or missing stop condition.

    Checkpoint 3
    Run it by hand once

    Before scheduling anything, run the loop manually with the agent and record every place you had to intervene.

    Transfer test
    If the same loop shape works for a different domain, you learned the pattern. If it only works for one tool, you learned a tool trick.
    Three-correction rule
    If you corrected the same AI behavior three times, stop improving the prompt and build the loop around it.
    Core Idea

    A loop is five plain steps

    A useful AI loop has a goal, the context it needs, an action it takes, a check on whether the action worked, and a retry rule if it failed.

    01
    Goal

    What result should exist?

    02
    Context

    What must the agent read first?

    03
    Action

    What does it do?

    04
    Check

    What proves it worked?

    05
    Retry

    What changes before the next attempt?

    If check passes, stop. If check fails, retry and rerun action.
    The whole job
    The loop is cheap to write. The valuable work is deciding what counts as done, then turning that decision into a check that runs outside the agent's own story.
    closed-loop skeleton
    Goal: [specific output]
    Context: [files, data, rules, examples]
    Action: [what the agent does]
    Verifier: [lowest check that proves the output is valid]
    Retry: [max attempts + what changes each retry]
    Stop: [time, spend, attempt, or human gate]
    Build Test

    Should this become a loop?

    Most tasks do not deserve automation. A loop earns its setup cost when the work needs iteration until proof passes, or when the same proven loop should rerun from a schedule, webhook, inbox, or new file.

    Single Run

    Task loop

    Runs once, but may cycle through action, check, and retry several times before it stops.

    Recurring Trigger

    Scheduled loop

    Runs the same task loop again when time, an event, or a queue item triggers it.

    Needs iteration

    The task can run once, but the agent may need several attempts before the verifier passes.

    Trigger is explicit

    Manual click, schedule, webhook, inbox item, or file drop. No hidden always-on behavior.

    Machine-checkable

    A test, build, linter, link check, schema check, or fixed rule can reject bad output.

    Real tool access

    The agent can read the system, run the code, inspect logs, or touch the workflow it should improve.

    Hard stop

    Attempts, time, spend, token budget, or human review stops the loop before it wanders.

    Skip the loop when
    The work has no tool action, no external check, no clear stop condition, or too much relationship, legal, payment, auth, or strategy risk. A good prompt plus a human in the chair still wins there.
    Verifier Design

    The verifier ladder

    Verifiers sit on a ladder from dumb and certain to smart and arguable. Your goal is to stay as low as the task allows.

    Use this when the loop's first promise is simple: create a report, export a CSV, write a summary file, produce an invoice, save a screenshot.

    example check
    test -s deliverables/report.html

    This does not prove quality. It proves existence. That is still better than accepting the agent's word.

    Loop Stack

    Four loops stack together

    The first loop automates work. The outer loops make it reliable, always-on, and able to improve from its own traces.

    01
    Agent loop

    Model calls tools until the task is complete.

    02
    Verification loop

    A grader or rule checks output and sends failures back for retry.

    03
    Event loop

    A manual click, schedule, webhook, Slack message, or new file triggers the task loop.

    04
    Hill-climbing loop

    Traces from production runs improve the prompt, tools, rubric, or context pack.

    Compounding rule
    The strongest loop is not the one that runs most often. It is the one whose traces make the next run better.
    Loop Patterns

    Six useful loop patterns

    Start with a pattern before you invent a custom system. Most useful loops are one of these shapes with different tools attached.

    Support triage

    Classify the request, gather account context, draft a reply, escalate refunds or angry customers.

    Sales follow-up

    Read the thread, draft the next message, check voice and accuracy, queue for approval.

    Research brief

    Collect sources, reject weak links, summarize only claims backed by evidence.

    Content improvement

    Draft, run a validator or rubric, revise until the score clears the line.

    Data cleanup

    Normalize rows, check required fields, quarantine anything the schema rejects.

    Code repair

    Run the failing proof, patch one cause, rerun, stop at green or hand off.

    Pattern rule
    If the loop needs more than one pattern on day one, it is probably too large. Split it into a smaller loop with one verifier.
    Eval Patterns

    Two eval backbones

    Scorer with threshold

    Best for content and knowledge work where quality is graded. The score must clear a hard line before output moves forward.

    • Newsletter and essay: 80+
    • LinkedIn: 75+
    • Email: 70+ plus binary reject gates

    Binary proof gate

    Best for code, security, data integrity, and anything where one failure should block shipping.

    • PROVEN, NOT_PROVEN, or INCONCLUSIVE
    • Artifact on disk for each claim
    • Any fail blocks ship
    Build story
    In a code loop, a separate reviewer should answer one yes/no question per check and point at the artifact. No composite score should hide a failed security or build gate.
    Proof Contract

    Write the proof before the work starts

    A proof contract turns vague acceptance criteria into checks the loop can run and artifacts a reviewer can inspect.

    example proof contract
    Intent: Add a new gated resource page.
    
    Acceptance criteria:
    1. Landing page and access page exist.
    2. Email capture accepts the new resource slug.
    3. Resource appears in navigation, sitemap, OG preview, and outreach manifest.
    4. TypeScript and production build pass.
    
    Proof mode:
    1. File existence check.
    2. Unit test for resource slug and email subject.
    3. Static route and registry inspection.
    4. tsc plus npm run build.
    
    Evidence:
    - Changed file list.
    - Passing test output.
    - Build output.
    
    Review:
    - Separate reviewer checks one criterion at a time.
    - Verdict is PROVEN, NOT_PROVEN, or INCONCLUSIVE.
    
    Outcome:
    - Ship only when every criterion is PROVEN.
    Contract rule
    Acceptance criteria describe the promise. Proof mode describes how the promise will be tested. Keep those separate or the loop will negotiate with itself.
    Loop Shape

    Open vs closed loops

    Closed loop

    Known input, known steps, known check, clear stop condition. Start here.

    good first loop
    Each morning:
    1. Read inbox notes
    2. Extract tasks
    3. Rank by deadline and value
    4. Verify every task has an owner and next action
    5. Stop after one daily plan is written

    Open loop

    Broad goal, fuzzy finish line, lots of exploration. Useful, but expensive and harder to trust.

    convert it before automating
    Bad: Research the market until you find something interesting.
    
    Better: Find 10 recent examples, discard dead links,
    score each against 5 criteria, and stop.
    Default rule
    If you cannot name the stop condition before the loop starts, it is not ready to run unattended.
    Risk Control

    Understanding debt

    A self-running system can produce more than you can read. That feels productive until you approve work you no longer understand.

    Spot-check cadence

    Review a random sample from every loop run, even when the gate passes.

    Rule ownership

    Keep the verifier rules in a human-owned file the agent cannot quietly rewrite.

    Cost cap

    Set max attempts, time, spend, or tokens before the loop starts.

    Recovery path

    Write restart, replay, and rollback instructions before the first unattended run.

    loop safety card
    Loop name:
    Owner:
    What it may change:
    What it may never change:
    Max attempts:
    Max spend:
    Verifier:
    Human gate trigger:
    Rollback path:
    Last spot-check date:
    Failure Modes

    The mistakes that make loops expensive

    No state file

    Tomorrow's run restarts from zero. Keep a markdown file, issue, board, or database row with last run, failures, lessons, and next action.

    Maker grades maker

    The agent that wrote the output is too generous reviewing it. Use a fixed rule, separate verifier, or human gate for anything important.

    Silent early exit

    The loop says done before the work is done. Soft completion words are not gates. Use a test, build, type check, file check, or substance check.

    Permission creep

    A loop tested read-only gets one write permission for convenience, then never gets re-audited. Review tools, secrets, and write access on a schedule.

    Compounding drift
    Each pass gets smoother but less true.
    Rewrite the smallest failing section.
    Reviewer theater
    Critique sounds smart but changes nothing.
    Require exact lines and concrete fixes.
    Eval vibes
    The test checks adjectives.
    Turn quality into observable behavior.
    Router tax
    Simple tasks get heavy workflows.
    Add a direct low-risk path.
    Hidden human labor
    Automation still needs steering.
    Track operator minutes per run.
    Source laundering
    Weak evidence becomes confident prose.
    Use cite, narrow, qualify, or remove.
    Cost rule
    Model cost is not the main cost. Operator minutes decide whether a workflow survives.
    minimal state file
    Loop name:
    Last run:
    What changed:
    What passed:
    What failed:
    Human review needed:
    Next run should:
    Lessons added:
    Build Track

    Build your first closed loop in 7 days

    Day 1

    Pick one repeated task with a clear output.

    Day 2

    Write the loop skeleton: goal, context, action, check, retry, stop.

    Day 3

    Choose the lowest verifier rung and write the exact check.

    Day 4

    Add the context pack: files, examples, rules, and source data.

    Day 5

    Run once with a human gate. Record every failure.

    Day 6

    Turn the failures into rules, tests, or checklist items.

    Day 7

    Run again with a cost cap and spot-check the output.

    Reference

    What to pair with this playbook

    Loop engineering does not replace the rest of the system. It sits between context, agents, memory, and review. Use these resources when the playbook points at a missing layer.

    Claude Code Tutorial

    Use this when you need the practical substrate: files, terminal, agents, skills, hooks, MCP, and repeatable project workflows.

    Open tutorial

    yalla proof contract

    Study a real binary gate in code: PROVEN, NOT_PROVEN, or INCONCLUSIVE, backed by artifacts. Use this only if your loop is technical enough to need code-level proof.

    Open GitHub

    Want the Full System?

    The playbook gives you the loop discipline. Second Brain 2.0 gives you the configured repo, memory layer, specialist agents, and tool setup to run it every day.

    Second Brain 2.0

    The complete Claude Code system. 30+ agents, memory that compounds, pre-configured MCPs.

    DIY $197 / Kickstart $597 / DWY $2,497

    See Packages
    MemoryOS

    The memory layer your loop writes lessons into. Patterns persist and recall across future sessions.

    Free / Standard $199/yr / Pro $349/yr

    Get MemoryOS