← Course home · Module 05 · Week 3

Loop Engineering & Automations

D1 D3 TS 1.7 · 3.4 · 3.5 · 3.6  ·  ~6 hrs  ·  Skip to quiz →

1 · The dial of autonomy

▶ Watch: a loop with a stop condition · 2 min

Every module so far had you at the keyboard, watching. This module is about the moments you step away, and how far away you can safely go. Think of it as a dial with five positions, each giving Claude more room to run:

PositionWhat Claude doesYou are
One turnAnswers, stops, waitsWatching every step
Iterative refinementImproves work over repeated passesChecking each pass
Plan modeExplores and proposes before touching anythingApproving the plan
A loopRepeats a task until a condition is metReading the log afterward
Headless and scheduledRuns with nobody at the keyboard at allAsleep

One principle governs the whole dial, and every section below is an application of it: every notch of autonomy you grant must be matched by a notch of defined stopping and checking. A session you watch needs neither, because you are the stop condition. A session that runs at 7am on a Monday with nobody in the building needs its stopping rules written down in advance, because nothing else will supply them.

2 · Plan mode versus direct execution (TS 3.4)

Claude Code has a mode where it does not touch anything. In plan mode, Claude explores the repo, reads whatever it needs, and produces a proposal: here are the files I would change, here is what I would do to each, here is the order. Nothing is written, nothing runs. You read the plan, adjust it, and approve it; only then does execution begin. (In the terminal, shift+tab cycles the modes.)

Direct execution is the default everything so far has used: you ask, Claude acts.

The exam tests whether you can pick between them, and the sorting question is the cost of a wrong first move:

SituationModeBecause
Fix a typo, rename a file, add one ruleDirectA wrong move is trivially reversible
A change that touches many files at oncePlan firstYou want to see the whole blast radius before anything moves
Working in a repo you do not know yetPlan firstThe exploration IS the value; the plan proves Claude understood the terrain
Anything near data you cannot recoverPlan firstThe proposal costs a minute; the mistake costs the engagement
A task you will repeat many timesPlan once, then directThe approved plan becomes the template

Plan mode is the cheapest insurance in the whole tool. A proposal you reject costs one minute of reading. The same mistake executed costs an afternoon, and sometimes a client's confidence.

3 · Iterative refinement (TS 3.5)

The second habit the exam tests sounds humble and changes everything: stop asking for finished work in one prompt, and start improving work over deliberate passes.

The pattern, using a real deliverable:

  1. Draft. "Write the first draft of the assessment summary from the six reports."
  2. Check against something concrete. "Compare the draft against the checklist in the deliverables folder: every claim cited, every section under a page, the July reversal footnoted." A pass needs a measuring stick; without one, "improve this" just reshuffles sentences.
  3. Revise the failures only. "Fix the three items that failed the checklist."
  4. Repeat until the check passes clean.

Why passes beat one giant prompt: each pass is small enough to verify, so errors get caught while they are one pass old instead of buried under everything built on top of them. The reviewer agent pattern from the orchestration module is this same idea with the critic split into its own worker; here, the critic can simply be a checklist and a fresh pass.

One warning: refinement without a measuring stick is the seed of a runaway. "Keep improving until it is great" has no pass that can be the last one. Hold that thought; the loop guardrails a few sections ahead are built on it.

4 · Session state: resume and fork (TS 1.7)

Sessions end. Windows fill, laptops close, days end. What survives is session state: Claude Code keeps the transcript of every session on your machine, and you can reopen one and continue where it left off.

You want toDo thisWhat happens
Pick up this morning's workContinue the most recent session (claude --continue)Same conversation, same context, as if you never left
Pick up last Tuesday's workResume a chosen session (claude --resume, then pick)That session's conversation reloads
Try a risky direction without losing the originalResume the session and take it the new direction; the original transcript stays intactTwo branches from one starting point: the fork the exam asks about
Start cleanA fresh claudeEmpty window; the context layer loads from files as always

The deeper discipline sits underneath the mechanics, and it echoes what the context module taught: transcripts are a convenience; files are the record. A resumed session still carries all the noise of its past, and a forked one inherits it twice. The habit that makes any future session cheap to start is writing decisions to disk as they happen: a NOTES file, a LOG line, an updated index. A fresh session that reads a good NOTES file in thirty seconds beats a resumed session dragging three hours of scrollback, and it works for a teammate's session too, which no resume can do.

5 · Loops, schedules, and stop conditions

A loop is any arrangement that runs a task repeatedly until it is done: within one session (keep filing notes until the folder is empty) or across time (run the filing task every Monday). Loops are where the autonomy dial turns furthest, so this section is really about one thing: what makes a loop safe to walk away from.

Three guardrails, and a loop is not done being built until it has all three:

Guardrail one: a finish line a script could check

A loop stops itself only when it can tell that it is done, so the finish line has to be a condition a script could check: a yes or no question with no judgment call in it. Four finish lines follow, on two cards. Before you flip each card, decide for yourself: could a script check this?

Guardrail two: a hard cap on turns

Some of the runs this module builds happen with nobody watching. A headless run is Claude started by a script instead of a person: a scheduled job launches it at 7am, it works alone, writes its result, and exits. "Headless" is old computing shorthand for software running without its screen attached, and here it means without its conversation attached: no chat window, no human to ask.

Every headless run takes a hard turn limit: --max-turns 20 means twenty rounds of thinking and acting, then a forced stop. Set the cap every time, even with a good finish line, because some mornings produce a condition nobody predicted:

On those mornings the finish line never arrives. The cap ends the run anyway.

A normal run finish line reached at turn 8, the run stops itself turns 9 to 20 never used The bad day the finish line never arrives, every turn gets used --max-turns 20, forced stop
The finish line stops the run on a normal day. The cap exists for the day it cannot.

Guardrail three: a log you can read over coffee

Every run appends one line per action to its own log file: what it processed, what it skipped, why it stopped. A finished run's log reads like this:

2026-08-17 07:00  run started, 3 notes waiting in incoming
2026-08-17 07:01  filed 2026-08-15-vendor-call.md to research
2026-08-17 07:01  filed 2026-08-16-standup.md to research
2026-08-17 07:02  moved one undated note to needs-review, flagged for a human
2026-08-17 07:02  stopped: incoming is empty

Monday at 7:05 you skim those five lines with your coffee, and in thirty seconds you know the weekend run behaved. This file is separate from the audit log, and the two do different jobs:

The audit logThe loop's log
Written byA hook: a small script that fires after every tool callThe loop itself, as it works
RecordsEvery tool call, timestamped. The mechanical trailIntent: one line per action, in plain words
Read it whenSomething needs forensics: what exactly did Claude touch?Every Monday, to confirm the run behaved
Reads likeA transcriptA story

Without the loop's log an automation sends you no news at all until something breaks, and then you are reconstructing what it did from file timestamps.

One more pattern, flagged honestly as practice rather than a built-in feature: stop when nothing changes. Write it into the task itself: if a pass completes without processing anything new, or hits the same error twice, stop and log why. It costs one sentence in the task file and catches the failure caps are too blunt for.

6 · Headless mode and CI/CD (TS 3.6)

Every run in this module so far began with a person: you opened a terminal, typed claude, and stayed in the conversation while the work happened. Headless mode is how Claude runs with nobody at the keyboard. One command starts it:

claude -p "file any new notes from the incoming folder, then stop" --max-turns 20

What the -p flag does

One command, and Claude runs the same loop a normal session runs:

The name is old computing shorthand: a machine running without its screen was running headless, and this is Claude running without its conversation.

Who can start a headless run

Anything that can run a shell command can now run Claude. Three starters, in rising order of autonomy:

CI/CD, spelled out for the non-developers in the room: Continuous Integration and Continuous Delivery, the assembly line that runs automatically when a team's code changes: tests run, checks pass, software ships. Claude slots into that line as a step. Real examples:

Headless runs raise two governance questions: which rules apply when nobody is watching, and who is accountable for a task that runs itself. One at a time.

The same rules apply

Hooks and permission rules are stored in the settings files inside the repo (.claude/settings.json). A headless run starts in that same repo, reads those same files, and gets the same protection. Nothing is configured twice:

ProtectionYour afternoon sessionThe 7am headless run
The command blocker hookFiresFires
The credential scanner hookFiresFires
The deny rule on the secrets fileEnforcedEnforced

One thing does change: permissions.

The flag with a warning in its name: --dangerously-skip-permissions turns permission checking off completely. It is acceptable in one situation only: a disposable sandbox, meaning an isolated environment with no real data, no credentials, and nothing that would matter if it were deleted.

A scheduled task must be treated as a production system

Think about what scheduling changed:

Before schedulingAfter scheduling
Starts whenYou start itMonday at 7, by itself
Who is watchingYou areNobody
PermissionsGranted as you approve themAlready granted, always on

That always-on permission is called standing access: access that does not have to be requested each time because it is never turned off. Software that runs unattended, on a schedule, with standing access is a production system, meaning software the organization depends on and has to keep track of. Production systems get three things:

The rule in one line: the moment you schedule it is the moment to register it.

7 · Case study: the sync that went on vacation

The setup

The five consultant team at the regional health plan, whose second brain now has discoverable skills, written descriptions, and three hooks standing guard. Their weekly rhythm has a soft spot nobody has noticed: every Monday morning, one consultant runs the sync commands by hand. New meeting notes get filed, the index gets updated, the week starts clean. It works beautifully, in the way things work beautifully right up until they depend on one person's calendar.

The two quiet weeks

That consultant takes two weeks of leave in July. Nobody runs the syncs; nobody notices, because absence of filing looks like absence of news. The team preps a steering committee deck against a research folder that is two weeks stale, and a partner quotes a decision that an unfiled note had quietly reversed. The client corrects the partner, in the meeting. The problem was never the tooling. It was that the tooling had a single human moving part.

The first automation, and its lesson

The team's first fix: schedule a headless run every Monday with the task "keep the research folder organized and up to date, and improve the summaries where needed." Read that task the way a script would. Which condition says finished? None. So:

The rebuild

The second version applied the three guardrails:

Monday runs now finish in minutes, and most weeks the log reads like a receipt: three filed, zero skipped, stopped because incoming was empty.

The registration

The automation runs unattended, on a schedule, with standing access to the shared brain. So the team treated it as what it now is, a standing system: a named owner, the log reviewed at Monday standup, and changes to the task file through the same review any settings change gets. Registration took a row in a spreadsheet and ten minutes.

What changed

The Monday human moving part became a Monday human check: read one log line over coffee. And the two week vacation problem is gone, because the calendar the automation depends on belongs to the machine.

8 · Demo: watch the automation get built, then build yours

▶ Watch the demo: building your first automation · 4 min

The prompt pack: every demo prompt, cleaned and explained

The demo applies this chapter prompt by prompt: the task file with all three guardrails written in plain language, the small runner script that starts Claude headless with a turn cap, the Monday schedule, a run that does real filing work and stops itself, and three guardrail tests, including a run that hits the cap on purpose and logs what remains for next time.

Then run the pack in your own repo. The prompt pack linked above holds every prompt from the demo, cleaned up and explained. Copied as is or rephrased in your own words, check what the demo checked as you go:

9 · Wrap-up: what you should be able to do cold

Readings

Claude Code docs on headless mode, CLI flags (--continue, --resume, --max-turns), permissions, and CI integrations (code.claude.com/docs).

Take the Module 05 quiz →  then hit the Study App for Domain 1 lesson 1.7 and Domain 3 lessons 3.4 through 3.6.