# System Loops

> Repeat-until definitions for automated fix and verification cycles.
> These loops ensure quality gates are met before proceeding.

---

## Loop Definitions

### `verify_loop`

**Purpose:** Run verification until it passes or max iterations reached
**Max Iterations:** 10
**Commands:** `npm run verify` (typecheck + lint)

```
LOOP: verify_loop
├── MAX_ITERATIONS: 10
├── COMMAND: npm run verify
│
├── DO:
│   1. Run: npm run verify
│   2. Capture: output and exit code
│   3. Parse: errors if any
│
├── UNTIL: exit_code == 0
│
├── ON_SUCCESS:
│   └── Report: "✅ Verification passed"
│   └── Trigger: on:verification_passed
│
├── ON_FAIL (errors exist):
│   └── Report: errors with file:line
│   └── Enter: fix_loop
│   └── Return to: verify_loop
│
└── ON_MAX_ITERATIONS:
    └── Report: "⛔ Max fix attempts reached"
    └── List: remaining errors
    └── Ask: user for guidance
```

**Output Format (Success):**
```
✅ VERIFICATION PASSED

Iteration: 1/10
TypeScript: ✓ No errors
ESLint: ✓ No warnings

Ready to proceed.
```

**Output Format (Failure):**
```
❌ VERIFICATION FAILED (Iteration 2/10)

Found 3 error(s):

1. src/components/Button.tsx:15
   Error: Property 'onClick' is missing in type...

2. src/hooks/useAuth.ts:42
   Error: Type 'string' is not assignable to type 'number'

3. src/pages/Home.tsx:8
   Warning: 'unused' is defined but never used

Entering fix loop...
```

---

### `fix_loop`

**Purpose:** Fix errors one by one until all resolved
**Max Iterations:** 10 (shared with verify_loop)
**Strategy:** Fix most critical errors first

```
LOOP: fix_loop
├── MAX_ITERATIONS: 10 (total with verify)
├── INPUT: parsed_errors[]
│
├── DO:
│   1. Sort: errors by severity (error > warning)
│   2. For each error:
│      a. Identify: file and line
│      b. Read: surrounding context
│      c. Determine: fix strategy
│      d. Apply: fix
│      e. Mark: error as addressed
│   3. After all fixes: return to verify_loop
│
├── UNTIL: all errors fixed OR max_iterations
│
├── ON_ERROR_FIXED:
│   └── Report: "Fixed: [error description]"
│   └── Continue: to next error
│
├── ON_ALL_FIXED:
│   └── Report: "All errors addressed"
│   └── Return to: verify_loop
│
└── ON_STUCK (can't fix):
    └── Report: "Unable to fix: [error]"
    └── Ask: user for guidance
```

**Output Format:**
```
🔧 FIX LOOP (Iteration 3/10)

Fixing 3 errors...

[1/3] src/components/Button.tsx:15
      Error: Property 'onClick' is missing
      Fix: Added onClick prop to interface
      Status: ✅ Fixed

[2/3] src/hooks/useAuth.ts:42
      Error: Type mismatch
      Fix: Changed return type to string
      Status: ✅ Fixed

[3/3] src/pages/Home.tsx:8
      Warning: Unused variable
      Fix: Removed unused import
      Status: ✅ Fixed

All errors addressed. Re-running verification...
```

---

### `audit_loop`

**Purpose:** Run all audit checks until they pass
**Max Iterations:** 5
**Commands:** UI enforcement, circular deps, etc.

```
LOOP: audit_loop
├── MAX_ITERATIONS: 5
├── CHECKS:
│   1. npm run audit:ui (orphan features)
│   2. npm run audit:cycles (circular deps)
│
├── DO:
│   1. Run: npm run audit:ui
│   2. If fail → Enter: ui_fix_loop
│   3. Run: npm run audit:cycles
│   4. If fail → Enter: cycle_fix_loop
│
├── UNTIL: all audits pass
│
├── ON_SUCCESS:
│   └── Report: "✅ All audits passed"
│   └── Proceed to: pre_commit_gate
│
├── ON_UI_FAIL:
│   └── Report: orphan features found
│   └── BLOCK: "Must add UI for: [features]"
│   └── Enter: ui_fix_loop
│
├── ON_CYCLE_FAIL:
│   └── Report: circular dependencies found
│   └── BLOCK: "Must resolve cycles: [A → B → A]"
│   └── Enter: cycle_fix_loop
│
└── ON_MAX_ITERATIONS:
    └── Report: "⛔ Cannot resolve audit issues"
    └── Ask: user for guidance
```

**Output Format:**
```
🔍 AUDIT LOOP (Iteration 1/5)

[1/2] UI Enforcement Check
      Command: npm run audit:ui
      Result: ⛔ FAILED

      Orphan features detected:
      - /api/users endpoint has no UI
      - useAuth hook is not used by any component

      BLOCKED: Must add UI before commit.

[2/2] Circular Dependencies Check
      Command: npm run audit:cycles
      Result: ✅ PASSED

      No circular dependencies found.

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
⛔ AUDIT BLOCKED

Missing UI for:
- [ ] UserList component for /api/users
- [ ] Component using useAuth hook

Build these components to proceed.
```

---

### `ui_fix_loop`

**Purpose:** Ensure all backend features have corresponding UI
**Strategy:** Build missing UI components

```
LOOP: ui_fix_loop
├── MAX_ITERATIONS: 3
├── INPUT: orphan_features[]
│
├── DO:
│   For each orphan feature:
│   1. Identify: what UI is needed
│   2. Create: component/page
│   3. Connect: to backend/API
│   4. Add: route/navigation
│   5. Verify: user can access it
│
├── UNTIL: no orphan features
│
├── ON_UI_ADDED:
│   └── Report: "Added UI for: [feature]"
│   └── Re-run: audit:ui
│
└── ON_CANNOT_ADD (needs clarification):
    └── Ask: "How should [feature] be exposed to users?"
```

---

### `cycle_fix_loop`

**Purpose:** Resolve circular dependencies
**Strategy:** Refactor imports to break cycles

```
LOOP: cycle_fix_loop
├── MAX_ITERATIONS: 3
├── INPUT: circular_deps[]
│
├── DO:
│   For each cycle:
│   1. Identify: cycle path (A → B → C → A)
│   2. Analyze: which import can be removed/moved
│   3. Refactor: extract shared code or reorder imports
│   4. Verify: cycle is broken
│
├── UNTIL: no circular dependencies
│
├── ON_CYCLE_BROKEN:
│   └── Report: "Resolved cycle: [path]"
│   └── Re-run: audit:cycles
│
└── ON_CANNOT_BREAK (architectural issue):
    └── Report: "Cycle requires architectural change"
    └── Ask: user for guidance
```

---

### `pre_commit_check_loop`

**Purpose:** Run all pre-commit checks
**Strategy:** Check each blocking rule

```
LOOP: pre_commit_check_loop
├── MAX_ITERATIONS: 1 (check only, no auto-fix)
├── CHECKS:
│   1. TODO/FIXME comments
│   2. console.log statements
│   3. TypeScript errors
│   4. ESLint warnings
│   5. Orphan features
│   6. Circular dependencies
│
├── DO:
│   1. Check: git diff for TODO/FIXME
│   2. Check: git diff for console.log
│   3. Run: npm run verify
│   4. Run: npm run audit:ui
│   5. Run: npm run audit:cycles
│
├── ON_ALL_PASS:
│   └── Report: "✅ All pre-commit checks passed"
│   └── Proceed to: commit
│
└── ON_ANY_FAIL:
    └── Report: blocking issues
    └── BLOCK: cannot commit
    └── Route to: appropriate fix loop
```

---

## Loop Nesting

Loops can trigger other loops:

```
verify_loop
    └── on fail → fix_loop
                      └── return → verify_loop

audit_loop
    └── on ui_fail → ui_fix_loop
    │                    └── return → audit_loop
    └── on cycle_fail → cycle_fix_loop
                            └── return → audit_loop
```

---

## Iteration Tracking

Claude MUST track iterations across loops:

```
## Current Loop Status

| Loop | Iteration | Max | Status |
|------|-----------|-----|--------|
| verify_loop | 3 | 10 | running |
| fix_loop | 2 | 10 | completed |
| audit_loop | 1 | 5 | pending |

Total fix attempts: 5/10
```

---

## Emergency Exit

If loops cannot resolve issues:

1. Report all remaining issues
2. List what was tried
3. Ask user: "I've attempted to fix these issues X times. Should I continue, or would you like to handle this manually?"
4. Respect user's decision

Never enter infinite loops. Always have an exit condition.
