PTENES
MODULE 2.2

🔄 Loop Engineering

Loop Engineering is the design of execution and correction cycles. It doesn’t mean telling AI to keep going until it works — it means creating a controlled, measurable, and verifiable sequence that knows when to stop.

6
Topics
55
Minutes
Core
Level
Practical
Type
0%0 of 6
1

🔄 Design the execution cycle

An agent works in a loop: observe → understand → plan → execute → test → evaluate → fix → repeat. What separates an engineering loop from a loop of hope is the evaluate: that's where you decide whether the next iteration makes sense.

failed → fix and repeat (with a limit) observe plan run test and evaluate success · delivery limit reached · stop no progress · ask

How to read: the circle on the left is the loop; the three boxes on the right are the only ways to exit it. If your loop today only has the first one (success), it has no way out when things go wrong — and that's exactly when it burns through your budget all night long.

🆕 New here?

Loop here, it’s the automatic cycle the agent runs on its own between one instruction from you and the next. Stop condition is the rule that closes the cycle. Rollback is undoing what was done; fallback is following an alternative path when the main one fails. They’re different things: one goes back, the other works around the failure.

Evaluate

The step that almost disappears

New signal

Each iteration needs a

Three outputs

Success, limit, abandonment

Measurable

A blind loop means blind costs

2

🎯 Establish a verifiable goal and persistent state

The agent needs to know what it must achieve—in terms that a command can answer. And the system needs to record what has already been done, so an interruption doesn’t erase everything.

✓ An objective that closes the loop

  • ✓"npm test returns 0 and test X, which currently fails, passes."
  • ✓"The linter reports no new issues."
  • ✓"No files outside src/x/ appears in the diff."

✗ An objective that never closes

  • ✗"Make the module more robust."
  • ✗"Keep improving until it’s good."
  • ✗"Fix all the problems you find."

Minimum state worth recording between runs

tentativa: 2 de 3
hipótese atual: chave de idempotência não considera o valor
já tentado: (1) índice único simples — falhou, mesma duplicidade
arquivos tocados: src/pagamentos/idempotencia.ts, tests/idempotencia.test.ts
último resultado: 128 passaram, 1 falhou

With this written down, anyone (or the agent itself after an interruption) can pick up where things left off without repeating what already failed.

The command decides

Not the impression

Hypothesis

Each iteration has a

Already tried

Avoids repetition

Resumable

Interruption doesn't reset progress

3

🛑 Define the Stop Conditions

Every loop needs to know when to end. There are three outcomes — and the third, stopping for lack of progress, is the one almost nobody implements.

1

Success

The verifiable objective has been met, and the evidence is recorded (actual command output). The loop ends and hands off for review.

2

Limit reached

Attempts, time, or cost exceeded the limit. The loop stops, preserves the state, and reports what it tried—the partial work isn’t lost.

3

No progress (the forgotten output)

Two consecutive attempts with the same failure, or the diff started growing without the test advancing. The loop stops and asks—a valid outcome, not a failure.

⚠️ Attention

A cornered agent tends to “fix” the failure the wrong way: by relaxing the assertion, marking the test as skipped, or silently catching the exception. If the loop can edit tests, it can redefine its own success criteria—explicitly prohibit this.

Success

With attached evidence

Limit

Preserves the partial result

Stop and ask

It’s a valid result

Untouchable test

Otherwise, the criterion disappears

4

💸 Manage attempts, time, and cost

An attempt limit prevents the agent from repeating the same action. A cost cap controls consumption of tokens, time, and resources. Together, they turn an open-ended risk into a predictable value per task.

🧪 Copyable exercise — bug-fix loop with a limit

Objective: run a real correction cycle with a stopping condition and no test edits. Use a real bug from your repository.

Bug: <descreva o comportamento errado>
Como reproduzir: <passos ou comando>

Siga EXATAMENTE este loop, sem pular etapas:
1. reproduza o erro e cole a saída real;
2. localize a causa e escreva a hipótese em uma frase;
3. escreva um teste NOVO que falha por causa desse bug (não altere testes existentes);
4. implemente a MENOR correção que faz esse teste passar;
5. rode <comando de teste> e cole a saída real completa;
6. me mostre o diff.

Limites (obrigatórios):
- no máximo 3 tentativas de correção;
- se a mesma falha aparecer 2 vezes seguidas, PARE e me diga o que tentou;
- não altere nem remova nenhum teste existente;
- não adicione dependências;
- no máximo 5 arquivos alterados.

Se qualquer limite for atingido, pare e relate o estado — não continue.

How to verify: check three things in the result—(1) there’s a new test that failed before; (2) no existing test was modified (git diff --stat in the test files); (3) the pasted output is real, not a summary. If the agent stopped at the limit, the exercise still worked: the loop worked.

Same failure twice

Change the strategy

Smallest fix

Keeps the diff reviewable

Actual output

A summary is not evidence

Cost per task

Becomes a predictable number

5

↩️ Prepare rollback and fallback

Rollback lets you return to the previous state. Fallback defines an alternative when the primary path doesn’t work. If there’s no rollback, there shouldn’t be any autonomy.

🧯 Reversibility by action type

  • •Easy to undo: commit on a branch, new file, discarded container. It can be autonomous.
  • •Expensive to undo: database migration, public API contract change. Requires a written rollback plan before.
  • •Impossible to undo: email sent, payment processed, data deleted without a backup. Always a human.

💡 Practical tip

Before authorizing any autonomous loop, answer: "If this goes wrong at 3 a.m., what exact command undoes it?" If you can’t answer in one line, the loop isn’t ready to run on its own.

Rollback

Return to the previous state

Fallback

Works around the path

Migration

Reversible, or it doesn’t go

Autonomy

Limited by reversibility

6

🙋 Add Human Approval at the Right Point

Human approval stops the loop before critical actions. Put it everywhere, and it becomes an automatic rubber stamp; put it in the right place—immediately before the irreversible action—and it’s the last real control you have.

✓ Approval that works

  • ✓Few, and always before something irreversible
  • ✓With evidence attached: diff, test output, rollback plan
  • ✓With an easy "no": rejecting must take less effort than approving
  • ✓Recorded: who approved it, when, and on what basis

✗ Decorative approval

  • ✗One at each step—nobody reads past the fifth
  • ✗Without evidence: “approve?” with a summary from the agent itself
  • ✗After the fact ("I already applied it—can you confirm?")
  • ✗For trivial, reversible changes that could be automated

Quick check: the loop tried the same fix twice and failed the same way both times. What should happen?

Before the damage

Never afterward

With evidence

Not based on trust

Few

Many become rubber stamps

Recorded

Who, when, why

📌 Module Summary

✓
The cycle includes an evaluation step - without it, repeating is just a waste.
✓
Objective is a command - and the state records the hypothesis, attempts, and result.
✓
Three outputs - success, limit, and “no progress, ask.”
✓
Limits make costs predictable - attempts, time, files.
✓
Rollback before autonomy - anything that can't be undone must not run on its own.
✓
Evidence-based approval - few, serious, and before anything irreversible.

Next track:

Track 3 - Workflow & Quality: automations, AI code review, and quality gates.