# Iteration Lifecycle

Each iteration of the autobuilder follows a deterministic sequence of steps. This document describes the complete lifecycle from start to finish.

## Overview

```
┌─────────────┐
│ Pre-checks  │  Load config, sync skills, check stop signal
└──────┬──────┘
       ▼
┌─────────────┐
│ Phase       │  Determine which phases to run based on task state
│ Selection   │  (review → plan → execute, plan → execute, or execute only)
└──────┬──────┘
       ▼
┌─────────────┐
│ Review      │  Select mode, strategy, max_tasks from config
│ Config      │  Set up screenshot dir, dev server check, credentials
└──────┬──────┘
       ▼
┌─────────────┐
│ Hooks       │  Run pre-iteration, augment-review/plan/execute hooks
└──────┬──────┘
       ▼
┌─────────────┐
│ Prompt      │  Build the full prompt with all context
│ Build       │  (header → backlog → steps → rules → reference material)
└──────┬──────┘
       ▼
┌─────────────┐
│ Agent       │  Invoke AI agent (cursor/codex CLI)
│ Execution   │  Stream output, enforce hard timeout (3h)
└──────┬──────┘
       ▼
┌─────────────┐
│ Post-agent  │  Parse output, detect created/executed tasks
│ Processing  │  Run post-agent hook (quality gate)
└──────┬──────┘
       ▼
┌─────────────┐
│ Git Push    │  Push commits (if enabled and pre-push hook passes)
└──────┬──────┘
       ▼
┌─────────────┐
│ Journal     │  Record iteration outcome to journal.jsonl
│ Update      │  Update memory index, status file
└─────────────┘
```

## Detailed Steps

### 1. Pre-Checks

Before each iteration, the daemon:

- **Loads project config** from `.autobuilder/config.yaml` (hot-reloadable)
- **Syncs skills** by ensuring the symlink at `.cursor/skills/autobuilder` points to `skills/`
- **Syncs AGENTS.md** by ensuring the symlink at project root
- **Ensures gitignore** entries for all autobuilder-managed files
- **Cleans up stale MCP config** (`.cursor/mcp.json`) from prior runs
- **Checks stop signal** — if `.autobuilder/stop` exists, exits gracefully
- **Consumes backlog** — reads and deletes `.autobuilder/backlog.md` (one-shot user feedback)
- **Resolves active initiative** — reads `.autobuilder/active-initiative` to determine scope

### 2. Phase Selection

The daemon inspects the current task state to decide which phases to run:

```python
unplanned = find_all_unplanned(tasks_dir, root_id)
planned_pending = find_planned_not_executed(tasks_dir, root_id)

if unplanned:
    phases = ["plan", "execute"]     # Tasks exist but need planning
elif planned_pending:
    phases = ["execute"]              # Tasks planned, need execution
else:
    phases = ["review", "plan", "execute"]  # Full cycle
```

### 3. Review Configuration

When the review phase is included:

1. **Mode selection** — `random() < review_polish_weight` → polish or feature
2. **Strategy pool** — Built-in strategies filtered by `review_strategies` config + any `custom_review_strategies`
3. **Strategy selection** — Journal-weighted random from the effective pool
4. **Max tasks** — Cascade: custom strategy → per-strategy config → per-mode config → default
5. **Screenshot directory** — Created at `initiatives/<active>/review-screenshots/`
6. **Screenshot numbering** — Scans existing PNGs, next prefix = max existing + 1
7. **Dev server check** — Tests if the configured port is accepting connections
8. **Credentials** — Loaded from `.autobuilder/.env` (`TEST_USERNAME`, `TEST_PASSWORD`)

### 4. Hook Execution

If `.autobuilder/hooks/` exists, the daemon runs applicable hooks:

- **pre-iteration** — Health check, verify dev server (blocking: failure skips iteration)
- **augment-review** — Inject review context into prompt (fail-safe)
- **augment-plan** — Inject planning context into prompt (fail-safe)
- **augment-execute** — Inject execution context into prompt (fail-safe)

Augmentation hooks receive JSON context on stdin and print text on stdout. The output is appended to the agent prompt.

### 5. Prompt Build

The prompt is assembled from multiple sources:

| Section | Content | Source |
|---|---|---|
| Header | Role, project ID, iteration number | Computed |
| Backlog | User feedback (highest priority) | `.autobuilder/backlog.md` |
| Review step | Mode, strategy, browser commands, credentials | Config + project env |
| Plan step | Task numbering, dependency rules | Task state |
| Execute step | Implementation instructions | Task state |
| Critical rules | Commit format, file organization | Static |
| Reference | Initiative spec, constraints, memory index | Initiative files |

The prompt structure places action items first and lengthy reference material last.

### 6. Agent Execution

The daemon invokes the AI agent as a subprocess:

```bash
# Cursor executor
cursor agent --print --model claude-opus-4-7-thinking-xhigh --max-turns 100

# Codex executor
codex --model o4-mini --full-auto
```

The prompt is passed via stdin. Agent output is streamed to the log file and captured for post-processing. A hard timeout of 3 hours prevents runaway executions.

### 7. Post-Agent Processing

After the agent completes:

1. **Parse output** — Detect task files created or modified
2. **Identify created tasks** — New `.md` files in the tasks directory
3. **Identify executed tasks** — Tasks with `executed: true` frontmatter change
4. **Run post-agent hook** — Quality gate (tests, lint, type-check). If it fails, the failure details are written to `backlog.md` for the next iteration.
5. **Clean up browsers** — Kill any orphaned browser processes from `agent-browser`

### 8. Git Push

If pushing is enabled (`no_push: false` and no `--no-push` flag):

1. **Check for unpushed commits** — Only push if there are new commits
2. **Run pre-push hook** — Ship gate (E2E tests, security scan). Failure blocks push.
3. **Push to remote** — `git push`
4. **Run post-push hook** — Deploy, CI monitoring. Failure writes to backlog.

### 9. Journal Update

Every iteration records its outcome:

```json
{
  "iter": 42,
  "strategy": "deep-dive",
  "mode": "polish",
  "phases": ["review", "plan", "execute"],
  "initiative": "0001-my-app",
  "created": ["0042-fix-tooltip"],
  "executed": ["0038-add-skeleton"],
  "outcome": "productive",
  "rc": 0,
  "ts": 1712700000
}
```

Outcome classification:
- **productive** — Created or executed at least one task
- **idle** — No tasks created, no tasks executed
- **failed** — Agent returned non-zero exit code

The memory index is regenerated after each iteration, providing the agent with a compact summary of project state for the next iteration.

## Error Handling

### Agent Failures

If the agent process fails (non-zero exit, timeout, crash):

1. Increment `consecutive_agent_failures` counter
2. If counter ≤ 5, exponential backoff (60s → 30min) and retry
3. If counter > 5, raise `AgentFailed` exception (daemon handles)

### Nothing to Improve

When a full review cycle finds no issues:

1. Increment `consecutive_idle` counter
2. Exponential backoff (2min → 30min)
3. Strategy rotation continues (different angle each time)
4. Run `on-idle` hook if present

### Graceful Shutdown

The daemon exits cleanly on:
- `.autobuilder/stop` file detected
- SIGINT / SIGTERM signal
- `--max-iterations` limit reached
- `NothingToImprove` raised after exhausting all strategies
