The Navigator · 21 min mission

Loop Engineering in Claude Code

Compose /goal, /loop, hooks, subagents, and state files into production-grade agent loops.

loop engineeringgoalautomationhookssubagentsFact-checked 2026-06-21
On this page

This guide shows you how to build Claude Code loops that can plan, edit, verify, record evidence, and stop without drifting from the original objective.

Who this is for

Use this guide if you already know the basics of Claude Code and want to run longer work safely: product slices, backlog repair, production-error sweeps, documentation drift checks, or engineering-manager operating loops. The examples assume a repository with tests, a working git branch, and permission to create files under docs/agent-runs/.

You need:

  • Claude Code with /goal available.
  • A repo-level CLAUDE.md or equivalent project memory.
  • A verifier command such as tests, lint, build, CI, screenshot checks, or a review rubric.
  • Permission to add .claude/agents/, .claude/settings.json, or .claude/loop.md when you want reusable gates.

Expected result: after this guide, you can build one loop that has an objective, state file, verifier, review gate, escalation rule, and stopping condition.

Start with the short version in Loop Engineering for AI Coding Agents, or compare the companion Codex Loop Engineering guide when your workflow uses /goal, automations, AGENTS.md, and skills.

PrimitiveUse it forWhat it must not own
/goalThe active objective and completion conditionLong run logs or task history
/loopRepeated local prompts while the session is openDurable cloud scheduling
Scheduled routineRecurring work that must run away from your laptopUncommitted local context
Stop hookDeterministic rules that a shell command can enforceProduct judgment or root-cause quality
SubagentFresh-context review, specialist checks, parallel investigationThe final merge decision by itself
State fileEvidence and decisions across turnsRepo policy that belongs in CLAUDE.md
Claude Code loop primitives. The useful pattern is composition, not picking one feature.

Build the loop file layout

Do not keep loop state only in the transcript. A long loop needs files that a resumed session, subagent, or reviewer can read without trusting the implementing agent's summary.

Suggested Claude Code loop file layout
bash
.
+-- CLAUDE.md
+-- .claude/
|   +-- agents/
|   |   +-- backlog-verifier.md
|   |   +-- release-risk-reviewer.md
|   |   +-- product-slice-reviewer.md
|   +-- commands/
|   |   +-- manager-sweep.md
|   |   +-- backlog-loop.md
|   +-- loop.md
|   +-- settings.json
+-- docs/
    +-- agent-runs/
        +-- product-slice-loop.md
        +-- backlog-loop.md
        +-- incident-loop.md

The split is deliberate:

  • CLAUDE.md holds stable repo policy: tests, protected paths, review expectations.
  • .claude/agents/ holds fresh-context reviewers.
  • .claude/settings.json holds deterministic gates.
  • .claude/loop.md holds the default local recurring prompt.
  • docs/agent-runs/ holds run state, evidence, decisions, and open risks.

Build and audit a Claude Code loop

Loop engineering lab

Build, simulate, and audit an agent loop

Use this when a prompt has to survive more than one pass. The lab emits a reusable contract, animates the execution path, builds nested loop runbooks, and checks whether the loop is safe to run.

Audit score15/17
DecisionHuman-supervised only
Trigger
Verifier
Risk gate

Contract output

/goal ship the smallest working onboarding-to-first-value slice without expanding into adjacent features

Role:
Act as the implementer for one bounded loop pass. Do not grade your own final answer.

Context to read first:
- Nearest repo instructions: AGENTS.md, CLAUDE.md, or package-level rules.
- State file: docs/agent-runs/product-slice-loop.md.
- Current diff, linked issue, relevant tests, and recent failing output.

Scope:
- Work inside: one user path, one data model, one happy path, one failure state.
- Final artifact: feature branch, run log, screenshots, test output, and review notes.
- Invariant: do not add the next feature until this slice is usable and verified.

Pass protocol:
1. Write a pass plan with files in scope, files out of scope, risk, and verifier.
2. Make the smallest useful change.
3. Run verifier: npm test && npm run lint && npm run build
4. Update docs/agent-runs/product-slice-loop.md with commands, evidence, changed files, and next decision.
5. Ask for fresh review before claiming done.

Stop when:
- the selected test, lint, and build commands exit 0 with no ignored failures.
- The run log has changed files, commands, evidence, and remaining risks.
- Fresh review finds no P0/P1 issue.

Escalate when:
- The same failure repeats twice.
- The work leaves scope: one user path, one data model, one happy path, one failure state.
- The agent proposes weakening tests, logs, or monitoring.
- pause before schema changes, external API changes, broad refactors, or dependency upgrades.
Use the lab before you copy a prompt. The contract builder emits the goal, state file, and review gate. The runner simulator shows where evidence enters the pass. The audit gate catches unsafe autonomy before you start.

Write the goal as a testable contract

/goal should not contain the whole roadmap. It should contain one objective with a completion check. If the completion check needs a long log, put the log in a state file and reference it from the goal.

Claude Code /goal contract for a product slice
markdown
/goal Ship the private-beta invite request slice.
 
Read first:
- CLAUDE.md
- docs/product/private-beta.md
- app/invite/**
- lib/db/**
- current diff
 
State:
- Update docs/agent-runs/product-slice-loop.md after every pass.
 
Scope:
- Build one path: request invite, persist pending request, show duplicate-request error.
- Do not add billing, team roles, email delivery, or admin dashboards.
 
Verifier:
- npm test
- npm run lint
- npm run build
- browser check for happy path and duplicate-request error
 
Stop when:
- The invite request path works end to end.
- The verifier passes.
- product-slice-reviewer reports no P0/P1 issue.
- The state file lists changed files, commands, screenshots, and remaining risk.
 
Escalate when:
- Auth/session behavior changes.
- A migration or permission change is needed.
- The same failure repeats twice.
Run the loop in two layers
… scroll to run this session
The goal owns completion. The local loop only repeats observation while this session is open.

Add a state file that the agent cannot fake later

The state file should make the next pass boring. A new session should be able to answer: what was attempted, what changed, what passed, what failed, and what decision comes next.

docs/agent-runs/product-slice-loop.md
markdown
# Product slice loop
 
## Objective
A private-beta user can request an invite, see the saved pending state, and see duplicate-request feedback.
 
## Scope
- In scope: invite request UI, API handler, persistence, duplicate-request state, tests.
- Out of scope: billing, roles, email provider, admin dashboard.
 
## Verifier
`npm test && npm run lint && npm run build`
 
Browser checks:
- /invite accepts a new request.
- /invite shows duplicate-request feedback for an existing email.
 
## Pass log
| pass | hypothesis | changed files | verifier | evidence | decision |
| --- | --- | --- | --- | --- | --- |
| 1 | | | | | |
 
## Risks
| risk | owner needed | trigger | next check |
| --- | --- | --- | --- |
 
## Fresh review
| reviewer | result | blocking findings |
| --- | --- | --- |
 
## Final evidence
- Changed files:
- Commands:
- Screenshots:
- Remaining risks:

Use hooks for hard rules

Hooks are useful when a rule can be checked by code. Use them to block missing state, protected file edits, or forbidden commands. Do not use hooks for judgment such as "is this a good product decision?"

.claude/settings.json - require a state file before stopping
json
{
  "hooks": {
    "Stop": [
      {
        "matcher": "*",
        "hooks": [
          {
            "type": "command",
            "command": "test -f docs/agent-runs/product-slice-loop.md || { echo 'Missing product slice loop state file'; exit 2; }"
          }
        ]
      }
    ]
  }
}
.claude/settings.json - block risky shell shortcuts
json
{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": "case "$CLAUDE_TOOL_INPUT" in *'rm -rf '*|*'--force'*) echo 'Destructive command blocked by loop policy'; exit 2;; esac"
          }
        ]
      }
    ]
  }
}

Add fresh-context reviewers

The implementing agent is anchored to its own plan. Use a subagent with read-only tools to check the diff against the original goal, not against the implementer's final summary.

.claude/agents/product-slice-reviewer.md
markdown
---
name: product-slice-reviewer
description: Read-only reviewer for a product-slice loop. Use after implementation claims the slice is done.
tools: Read, Grep, Bash
---
 
You review the diff against the original product-slice goal.
You do not edit files.
 
Check:
1. The implemented path matches the objective in docs/agent-runs/product-slice-loop.md.
2. The diff stays inside the stated scope.
3. The verifier was run and not weakened.
4. Tests cover the happy path and at least one failure state.
5. Screenshots or browser notes prove the user path.
6. No P0/P1 risk remains.
 
Return:
- pass: true or false
- p0_p1_findings: list
- missing_evidence: list
- next_action: one concrete step
.claude/agents/backlog-verifier.md
markdown
---
name: backlog-verifier
description: Read-only reviewer for backlog and production-error loops. Use after the implementing agent claims an issue is fixed.
tools: Read, Grep, Bash
---
 
You verify backlog fixes. You do not edit files.
 
Check:
1. The issue was reproduced or explicitly proven stale or duplicate.
2. The fix addresses root cause, not only symptoms.
3. Tests were added or updated for the failing behavior.
4. Existing tests, logs, and monitoring were not weakened.
5. The issue update contains commands, output, files, and remaining risk.
 
Return:
- pass: true or false
- blocking_findings: prioritized list
- missing_evidence: list
- suggested_next_action: one concrete step

Product-from-scratch loop

Product work needs nested loops because "build the product" is not one verifier. Split the work into small loops where each one has its own proof.

LoopInputVerifierExit condition
Brief loopUser notes, support tickets, repo constraintsBrief names user, first-value moment, non-goals, first sliceFirst slice is clear enough to implement
Architecture loopBrief, repo map, data model, risky filesFiles in scope and out of scope are explicitImplementation plan fits one slice
Implementation loopPlan, state file, verifierTests, lint, build, browser checkSlice works end to end
Review loopDiff, state file, original goalFresh reviewer reports no P0/P1 findingReady for release loop
Release loopDiff, docs, monitoring, rollback noteRelease checklist has owner and post-deploy checkNext slice can be selected
Nested product loop stack for Claude Code.

Backlog and production-error loop

Backlog repair should not start with editing. Start with classification and reproduction. The loop can close an issue only when it has evidence.

.claude/commands/backlog-loop.md
markdown
Run a backlog repair loop for the top P0/P1 issue batch.
 
Inputs:
- Open P0/P1 issues older than 14 days
- Recent production errors
- Current branch diff
- docs/agent-runs/backlog-loop.md
 
Protocol:
1. Sort by customer impact, age, and reproducibility.
2. Pick one issue.
3. Reproduce it with a failing test, script, log query, or explicit non-repro note.
4. Patch only the root cause.
5. Add or update a regression check.
6. Run the verifier named in the state file.
7. Ask backlog-verifier to review the result.
8. Close, duplicate, or escalate with evidence.
 
Forbidden:
- Closing from summary alone.
- Weakening tests.
- Silencing logs.
- Broadening catch blocks without root-cause evidence.

Engineering-manager operating loop

A manager loop should produce decisions, not prose summaries. It reads systems of record, compares them to evidence, and returns owner actions.

.claude/loop.md - daily manager sweep
markdown
Read docs/agent-runs/manager-operating-loop.md and update it.
 
Check:
1. Pull requests older than two business days.
2. Failed or stuck CI checks.
3. Incident follow-up items without recent evidence.
4. Recently changed code paths whose docs or runbooks are stale.
5. Promises in planning notes that lack an owner or proof.
 
Output:
- owner
- blocker
- latest evidence
- next observable check
- escalation date
 
Do not change code unless the sweep finds a low-risk docs-only update. Record any proposed code change as a separate action.
LoopCadenceReadsOutput
Aging PR sweepDailyPR age, CI, review state, conflictsOwner, blocker, next action
Promise-to-proof sweepTwice weeklyPlanning notes, issues, PRs, docsCommitments without evidence
Incident follow-upAfter incidentsPostmortem, action items, regression checksStale tasks and blocked follow-ups
Docs driftWeeklyRecent code changes and nearest docsDocs PR or no-docs-needed note
Release riskBefore deployDiff, flags, migrations, alerts, rollbackGo/no-go brief
Manager loops that are worth scheduling.

Verify the loop before trusting it

Run a one-pass dry run before a long loop:

  1. Start the goal with read-only exploration.
  2. Require Claude to create the state file.
  3. Ask for a plan before edits.
  4. Let it make one scoped change.
  5. Run the verifier yourself if the task is high risk.
  6. Ask the reviewer subagent to inspect the result.
  7. Check the state file for evidence, not just a final message.

If the state file is thin, the loop is not ready for more autonomy.

SymptomLikely causeFix
Claude keeps expanding scopeGoal is a roadmap, not one objectiveClear the goal and restart with one slice and explicit non-goals
Loop repeats the same failureNo repeated-failure ceilingAdd "escalate after the same failure repeats twice"
Final answer sounds good but evidence is missingState file is optional or ignoredAdd a Stop hook that requires the state file
Tests pass because assertions changedVerifier can be weakened silentlyAdd a reviewer check for test deletion, assertion weakening, and log suppression
Scheduled work touches risky filesPermission boundary is too broadStart read-only and require owner approval for protected paths
Common loop failures and fixes.

Limitations

Claude Code loops still need human judgment when the work changes product scope, customer data, auth behavior, billing logic, migrations, deletion paths, production deploys, or incident communication. /loop is local to the session; use scheduled routines or CI when the task must run after your machine closes. Hooks can enforce deterministic rules, but they do not replace review.

Glossary

  • Loop: a repeated agent pass with state, verifier, and stop rule.
  • State file: a file that records objective, scope, pass log, evidence, and open risk.
  • Verifier: a command, CI check, log query, screenshot check, or review rubric that proves progress.
  • Fresh-context review: review performed outside the implementing agent's working context.
  • Gate: a condition that blocks continuation until a human, test, hook, or reviewer approves the next step.
  • Ceiling: a max pass, max turn, max time, or repeated-failure rule that prevents runaway work.

Reach the end and this star joins your charted sky.