loop-engineering
Turn a repeatable task into a bounded, evidence-driven agent loop. Use when Codex needs to decide whether a task merits looping, define a loop contract, choose single-agent versus maker-checker versus manager-workers topology, prevent runaway iteration, or repair a loop that stalls, self-grades, exceeds budget, or writes without verified evidence.
git clone --depth 1 https://github.com/Mark393295827/third-brain-v5-skills /tmp/loop-engineering && cp -r /tmp/loop-engineering/skills/loop-engineering ~/.claude/skills/loop-engineeringSKILL.md
# Loop Engineering
Design a loop as a control system, not a repeated prompt. Its only valid form is:
```text
goal + state + tools + budget
|
v
plan -> act -> observe -> independently verify -> decide
^ |
|---------------- continue / stop / escalate ---|
```
Use `scripts/validate_loop_contract.py` before starting a loop. Do not bypass a failed contract.
## Usage Template
```text
Use loop-engineering for this task.
Objective: [measurable outcome]
Scope: [owned files, systems, or outputs]
Evidence: [test, metric, fixture, review, or inspection]
Limits: [iterations, time, tool/token/request budget]
Permission boundary: [allowed writes and approval gates]
```
## Success Metrics
- A valid contract names the metric, independent verifier, finite caps, recovery path, and durable write-back.
- The selected topology is the lowest-complexity topology that can produce independent evidence.
- The final receipt distinguishes verified success, budget stop, stall, and blocked state.
## 1. Admit Or Reject The Loop
Use a loop only when the work is repeatable, the output can be checked, and each iteration can leave inspectable evidence.
| Situation | Default |
|---|---|
| One reversible edit or answer | Do the task once; do not create a loop. |
| Objective metric and cheap verification | Use a single-agent loop. |
| Builder cannot objectively verify its own output | Use maker-checker. |
| Independent workstreams with explicit file/output ownership | Use manager-workers with an integration gate. |
| Taste-only, ambiguous, irreversible, or production-changing task | Keep a human approval gate; do not run unattended. |
Reject a loop when its only stopping rule is “until satisfied,” “keep improving,” or “run forever.” Convert those requests into a metric, an acceptance fixture, a review queue, or a one-shot draft.
## 2. Create The Loop Contract
Create `.agent-state/loop-contract.md` or an equivalent durable state file before the first action. Use this exact shape:
```markdown
# Loop Contract
- Objective: Reduce the selected test suite's failures to zero.
- Scope: `packages/payments/**` and its tests only.
- Non-goals: No API redesign, dependency upgrades, or production deployment.
- Owner: Primary agent; checker owns verification only.
- Inputs: Failing test output and repository guidance files.
- State path: `.agent-state/payments-loop.md`.
- Success metric: Selected test command exits 0 with no skipped failures.
- Evidence: `pnpm test --filter payments` output and changed-file diff.
- Verifier: Independent test command plus a checker agent or reviewer.
- Topology: maker-checker.
- Max iterations: 5.
- Time limit: 45 minutes.
- Budget: 20 tool calls; stop before context or cost cap.
- Stop condition: Success metric passes, or any cap/stall condition fires.
- Write-back: Update `.agent-state/payments-loop.md` and the task log.
- Permission boundary: Local branch writes only; no push, merge, or production action.
- Recovery: Revert the last iteration if tests regress; escalate with evidence after two repeated failures.
```
Run:
```powershell
python scripts/validate_loop_contract.py .agent-state/loop-contract.md --strict
```
Treat a budget cap or stall condition as a controlled stop, not success.
## 3. Run The Thin Loop
For each iteration:
1. Read only the contract, current state, last evidence, and minimum task context.
2. Plan one smallest reversible action that can affect the metric.
3. Act inside the contract's file, tool, and permission boundary.
4. Observe tool output, diffs, logs, tests, screenshots, or telemetry.
5. Have the declared verifier evaluate the evidence. The builder cannot be the sole verifier.
6. Record metric delta, changed files, evidence path, budget used, and next decision in state.
7. Stop, continue, or escalate according to the contract.
Keep context lean. Persist state and evidence in files rather than replaying a long chat transcript.
## 4. Select Topology Conservatively
| Topology | Use when | Required controls |
|---|---|---|
| Single-agent | One owner and an objective check exist. | External test/linter/fixture; finite budget. |
| Maker-checker | Generation and evaluation need separate judgment. | Checker has a separate prompt or tool evidence and cannot edit before reporting. |
| Manager-workers | Work decomposes into independent territories. | Per-worker ownership, integration order, shared-state rule, and final evaluator. |
Do not use manager-workers merely to make a task feel more autonomous. Escalate to `agent-teams-command` when real multi-agent ownership, IPC, or integration work is required. Escalate to `harness-engineering` when permissions, credentials, scheduling, or production observability are the primary problem.
## 5. Stop, Recover, Or Escalate
Stop successfully only when the declared verifier accepts the declared evidence. Stop without success when a hard cap fires.
| Signal | Action |
|---|---|
| Success metric passes | Record proof, write back learning, stop. |
| Same failure twice | Stop editing that hypothesis; choose a different diagnosis or escalate. |
| No measurable progress for three iterations | Stop and request a human decision or redefine the metric. |
| Time, tool, token, or request cap reached | Preserve evidence and state; report budget stop. |
| Regression, permission denial, or shared-state conflict | Revert or isolate the last action; escalate with the receipt. |
| Need to push, merge, deploy, publish, pay, message, or mutate shared production state | Stop for explicit approval. |
## 6. Close The Memory Loop
At termination, write one compact receipt:
```markdown
Result: success | budget-stop | stalled | blocked
Metric: before -> after
Evidence: command, output path, screenshot, or diff
Iterations: N / cap
Changes: files or external actions
Residual risk: what remains unverified
Next action: only if not successful
```
Promote reusable constrainExecute a daily knowledge compound closed loop — 7 Key Results from input to feedback with scoring. Use when the user wants to do a daily review, plan their day, or run a knowledge workflow.
Extract reusable knowledge from a work session and save concepts, entities, corrections, patterns, ideas, decisions, and gaps to the wiki. Use when ending a session or when the user says to extract knowledge.
Estimate and track token usage and cost across the knowledge pipeline. Run before expensive tasks to budget, after tasks to log actuals.
Health-check the knowledge wiki — find orphans, broken links, missing frontmatter, contradictions, stale content, and statistical drift. Use when the user says "lint the wiki", "health check", or periodically for maintenance.
Command multi-agent work with bounded roles, ownership, integration gates, and verification loops. Use when the user needs Claude Code Agent Teams, parallel agents, delegation strategy, or multi-agent orchestration.
Design or refactor agent skills, workflows, and operating loops for model-native Agentic Engineering. Use when making skills more autonomous, concise, verifiable, long-horizon capable, token-efficient, and lower-friction for human-LLM collaboration.
Design an AI Six Sigma Black Belt operating model for property service, maintenance dispatch, environmental testing, quote generation, CRM follow-up, and workflow quality dashboards. Use when the user needs a Property Agent OS, AI + Ontology + DMAIC management system, CTQ metrics, agent-team roles, work-order states, or MVP roadmap for operations quality.
Improve a personal or team operating system with self-evolving loops, CASH allocation, 3B creativity, predictive coding, and diagnostics. Use when the user wants to redesign a work method, learning loop, or cognitive operating system.