The Navigator · 21 min mission
Loop Engineering in Claude Code
Compose /goal, /loop, hooks, subagents, and state files into production-grade agent loops.
On this page
- Who this is for
- Build the loop file layout
- Write the goal as a testable contract
- Add a state file that the agent cannot fake later
- Use hooks for hard rules
- Add fresh-context reviewers
- Product-from-scratch loop
- Backlog and production-error loop
- Engineering-manager operating loop
- Verify the loop before trusting it
- Limitations
- Glossary
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
/goalavailable. - A repo-level
CLAUDE.mdor 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.mdwhen 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.
| Primitive | Use it for | What it must not own |
|---|---|---|
/goal | The active objective and completion condition | Long run logs or task history |
/loop | Repeated local prompts while the session is open | Durable cloud scheduling |
| Scheduled routine | Recurring work that must run away from your laptop | Uncommitted local context |
| Stop hook | Deterministic rules that a shell command can enforce | Product judgment or root-cause quality |
| Subagent | Fresh-context review, specialist checks, parallel investigation | The final merge decision by itself |
| State file | Evidence and decisions across turns | Repo policy that belongs in CLAUDE.md |
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.
.
+-- 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.mdThe split is deliberate:
CLAUDE.mdholds stable repo policy: tests, protected paths, review expectations..claude/agents/holds fresh-context reviewers..claude/settings.jsonholds deterministic gates..claude/loop.mdholds 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.
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.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.
/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.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.
# 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?"
{
"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; }"
}
]
}
]
}
}{
"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.
---
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---
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 stepProduct-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.
| Loop | Input | Verifier | Exit condition |
|---|---|---|---|
| Brief loop | User notes, support tickets, repo constraints | Brief names user, first-value moment, non-goals, first slice | First slice is clear enough to implement |
| Architecture loop | Brief, repo map, data model, risky files | Files in scope and out of scope are explicit | Implementation plan fits one slice |
| Implementation loop | Plan, state file, verifier | Tests, lint, build, browser check | Slice works end to end |
| Review loop | Diff, state file, original goal | Fresh reviewer reports no P0/P1 finding | Ready for release loop |
| Release loop | Diff, docs, monitoring, rollback note | Release checklist has owner and post-deploy check | Next slice can be selected |
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.
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.
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.| Loop | Cadence | Reads | Output |
|---|---|---|---|
| Aging PR sweep | Daily | PR age, CI, review state, conflicts | Owner, blocker, next action |
| Promise-to-proof sweep | Twice weekly | Planning notes, issues, PRs, docs | Commitments without evidence |
| Incident follow-up | After incidents | Postmortem, action items, regression checks | Stale tasks and blocked follow-ups |
| Docs drift | Weekly | Recent code changes and nearest docs | Docs PR or no-docs-needed note |
| Release risk | Before deploy | Diff, flags, migrations, alerts, rollback | Go/no-go brief |
Verify the loop before trusting it
Run a one-pass dry run before a long loop:
- Start the goal with read-only exploration.
- Require Claude to create the state file.
- Ask for a plan before edits.
- Let it make one scoped change.
- Run the verifier yourself if the task is high risk.
- Ask the reviewer subagent to inspect the result.
- 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.
| Symptom | Likely cause | Fix |
|---|---|---|
| Claude keeps expanding scope | Goal is a roadmap, not one objective | Clear the goal and restart with one slice and explicit non-goals |
| Loop repeats the same failure | No repeated-failure ceiling | Add "escalate after the same failure repeats twice" |
| Final answer sounds good but evidence is missing | State file is optional or ignored | Add a Stop hook that requires the state file |
| Tests pass because assertions changed | Verifier can be weakened silently | Add a reviewer check for test deletion, assertion weakening, and log suppression |
| Scheduled work touches risky files | Permission boundary is too broad | Start read-only and require owner approval for protected paths |
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.