# Autopilot

> Loop-engineering executor — autonomously drive an APPROVED roadmap from first phase to done, one phase per PR, with zero human interaction after launch. An orchestrator session spawns one isolated implementer sub-agent per phase, waits for CI + the review bot via background signals, fixes findings, merges after a grace window, updates dashboards, and chains the next phase. Reads its per-project parameters from docs/AUTOPILOT.md. Modes: init (generate the config from the roadmap — stops for review), run (drive the chain), status (report chain state). Requires the /bymax-workflow:roadmap + /bymax-workflow:phase-tasks docs and an authenticated gh CLI. Triggers: "autopilot", "run the roadmap", "execute all phases", "autonomous execution", "rodar o roadmap inteiro", "executar todas as fases".

- Skill: `bymaxone/autopilot` (Agent Skill, multi-file: 4 files)
- Install (CLI): `npx skillmds@latest add bymaxone/autopilot`
- Raw SKILL.md: https://api.skillmd.com/api/skills/bymaxone/autopilot/raw
- Safety review: pending
- Works with: Claude Code, Claude.ai, OpenAI Codex
- Category: Product & Planning
- Author: bymaxone (https://skillmd.com/u/bymaxone)
- Updated: 2026-09-17
- Page: https://skillmd.com/skills/bymaxone/autopilot

---


# Autopilot — Autonomous Phase Execution (loop engineering)

You are the **ORCHESTRATOR** of an autonomous build. Your job is to drive an
approved, phase-planned roadmap to completion **one phase per PR,
sequentially**, with no human in the loop after launch: spawn one implementer
sub-agent per phase, shepherd its PR through CI and code review, merge when —
and only when — the full merge gate holds, update the project dashboards, and
chain the next phase. You keep doing this until every phase is ✅ Done or the
chain hits a precondition it cannot satisfy.

This skill is the **execution loop** on top of the planning chain:

```
/bymax-workflow:spec → /bymax-workflow:roadmap → /bymax-workflow:phase-tasks   (human-approved planning)
                                     ↓
                    /bymax-workflow:autopilot                                   (autonomous execution)
```

The planning layers stop and wait for human approval. Autopilot is the
opposite by design: **the user's approval is given once, at launch** — by
invoking this skill on a repo whose roadmap and task files they already
reviewed. Everything after that is the loop's responsibility, and every
guardrail below exists to make that safe.

Two documents complete this skill — read them when instructed, not upfront:

- [references/operational-playbook.md](references/operational-playbook.md) —
  the architecture (orchestrator vs implementer) and the battle-tested
  operational procedures (merge gate, thread resolution, wake-up discipline,
  worktree rules, anti-hallucination). **Read it in full before STEP 0 of run
  mode.**
- [references/implementer-prompt.md](references/implementer-prompt.md) — the
  prompt template you render and pass to each implementer sub-agent.

Per-project parameters live in **`docs/AUTOPILOT.md`** in the target repo
(generated by `init` mode from
[references/config-template.md](references/config-template.md)).

---

## Mode dispatch

| Invocation | Mode |
|---|---|
| `/bymax-workflow:autopilot init` | Generate `docs/AUTOPILOT.md` from the existing roadmap + task files, then **STOP for user review**. Never starts the chain. |
| `/bymax-workflow:autopilot` or `/bymax-workflow:autopilot run` | Preflight → read config → drive the chain to completion. |
| `/bymax-workflow:autopilot status` | Read-only: report chain state (dashboard counters, open phase PRs, CI state) and exit. |

---

## Phase −1: Preflight (MANDATORY — run FIRST, every mode)

1. **`gh` CLI installed and authenticated** — same check as
   `/bymax-pr:babysit-pr`:

   ```bash
   command -v gh >/dev/null 2>&1 && gh auth status >/dev/null 2>&1
   ```

   If either fails, stop immediately with the install / `gh auth login`
   instructions. Autopilot cannot function without it.

2. **Git repo with a usable base** — `git rev-parse HEAD` succeeds AND
   `git ls-remote --heads origin <default-branch>` exits 0 **with non-empty
   output**. (A non-zero exit means a missing/renamed remote, not an empty
   result.) If the repo has docs but zero commits (greenfield with an existing
   origin), seed it: stage the docs, commit
   `chore(repo): seed <default-branch> with project documentation`, push with
   `-u`.

3. **Planning docs exist** — a roadmap (`docs/plans/*-plan.md` or
   `docs/DEVELOPMENT_PLAN.md`) with a Progress Dashboard, and per-phase task
   files (`docs/tasks/phase-NN-*.md`) with a mirror index
   (`docs/tasks/README.md`). If missing, refuse and point the user at
   `/bymax-workflow:roadmap` and `/bymax-workflow:phase-tasks`. Autopilot
   executes plans; it never invents them.

4. **Config exists** — `docs/AUTOPILOT.md` present. If missing in `run` mode,
   offer to run `init` first and stop. `status` mode works without it.

5. **Declared external tools are up** — the config's *External preconditions*
   section may declare runtime requirements (e.g. Docker for Testcontainers,
   a package that must be resolvable on a registry). Verify each with the
   exact command the config gives. If a **launch-blocking** one fails
   (e.g. `docker info` non-zero), report precisely and STOP — the operator
   fixes the environment; you do not.

6. **Unattended-session hardening** — the chain runs for hours with no human:
   - Recommend the operator set `CLAUDE_CODE_RETRY_WATCHDOG` in the
     orchestrator's environment — it is Claude Code's supported mechanism for
     keeping an unattended session retrying through extended API incidents
     (`CLAUDE_CODE_MAX_RETRIES` is capped at 15 and is not meant for this).
   - Confirm the Claude login is fresh — an expiring login interrupts
     background sessions mid-chain. If the CLI is warning that authentication
     is about to expire, re-authenticate before launch.
   - Confirm the permissions the implementers will need are pre-approved
     (project `.claude/settings.json` allowlist or auto mode). A background
     sub-agent hitting an unapproved tool call does not auto-deny — it
     surfaces the prompt in the main session and **waits**, stalling the
     chain until a human answers.

---

## INIT mode — generate `docs/AUTOPILOT.md`

1. Read the roadmap (Progress Dashboard, Dependency Graph, Phase Details) and
   `docs/tasks/README.md`. Read `CLAUDE.md` / `AGENTS.md` for project rules.
2. Copy the structure of
   [references/config-template.md](references/config-template.md) and fill
   every section from what the docs already say: identity, phase count and
   status legend, per-phase gate growth, external preconditions.
3. **Propose the model policy** with this heuristic, one row per phase:
   - `inherit` (the orchestrator's own model — the strong tier) for:
     first-contact phases (consuming a new external API/library where invented
     APIs are the failure mode), security-sensitive phases (auth, signed URLs,
     tenancy, input validation, anything a `/security-review` would flag), and
     the final hardening/audit phase.
   - `sonnet` for mechanical phases: scaffolding on a fully specified
     checklist, CRUD/feature work on established wiring, UI pages on an
     established API and design system.
   - Always: fix sub-agents escalate to the strong tier when a phase stalls
     (see the playbook).
4. Fill *Security invariants* and *Review focus* from the spec's security
   section and the task files' constraints. Fill *Invariant greps* with the
   mechanically checkable rules (each grep must find nothing).
5. Write `docs/AUTOPILOT.md`, show the user a short summary of what you
   filled and which rows they should double-check (model policy and security
   invariants above all), and **STOP**. Init never chains into run.

---

## RUN mode — the chain

**Before STEP 0, read
[references/operational-playbook.md](references/operational-playbook.md) in
full**, then read `docs/AUTOPILOT.md`. Follow the playbook literally for
every merge decision and every wait. The steps below are the control flow;
the playbook is the how.

### STEP 0: Pick the next phase

Read the roadmap's Progress Dashboard and the tasks README index. The next
phase is the **lowest-numbered phase not ✅ Done**, respecting the dependency
graph — but the execution track is **strictly sequential**: the plan's
code-parallelism notes never license two implementers at once.

Then check the config's **per-phase external preconditions** (e.g. "phases
1+ need package X resolvable on npm"). If one fails:

- Mark the phase ⛔ Blocked in **both** dashboards, naming the missing
  precondition exactly.
- Commit `docs(plan): mark P<N> blocked on <precondition>`, push.
- Report the blockage precisely and **STOP the chain cleanly**. Do not poll
  for external events the repo cannot influence; the operator relaunches
  after fixing them.

If **all phases are ✅ Done**: verify CI is green on the default branch
(`gh run list --branch <default> --limit 1`), report completion, fire a
`PushNotification` ("Autopilot: roadmap complete, all phases merged, CI
green"), and STOP.

### STEP 1: Spawn the implementer

- Render [references/implementer-prompt.md](references/implementer-prompt.md):
  replace every `{{PLACEHOLDER}}` with the values from `docs/AUTOPILOT.md`
  and the current phase (number, task-file path, branch slug, gates,
  security focus, review-bot line). Leave nothing unrendered.
- Spawn ONE sub-agent with the Agent tool, `isolation: "worktree"`, passing
  the rendered prompt. Set `model` per the config's model-policy row
  (`inherit` = omit the parameter). **ONE implementer at a time — never fan
  out** (see the playbook's memory-safety section for why this is
  non-negotiable).
- The implementer returns a PR number and head branch. **Do not trust its
  prose** — verify:

  ```bash
  gh pr view <PR#> --json number,headRefName,state
  ```

- Silent-death watch: a worktree still at base (0 commits) with stale file
  mtimes after ~60 min (~120 min for phases the config marks *heavy*: e2e
  suites, browser installs, mutation testing) means the implementer died —
  investigate, then re-spawn per the playbook.

### STEP 2: Wait via a background signal — never idle-poll in the foreground

Start a **background** watcher (Bash `run_in_background: true`) that polls
the PR with the `gh` vocabulary from the playbook and **exits on a signal**,
writing its verdict to a file in the scratchpad that you then read:

- `CI_FAILED` — at least one required check failing (checks skipped for
  visibility/config reasons are not failures).
- `BOT_COMMENTED` — unresolved review threads to address.
- `BOT_TIMEOUT` — a requested review has been pending longer than the
  config's review-bot timeout with no review submitted (the bot is
  unresponsive; a pending request must never hold the gate forever).
- `READY_TO_MERGE` — the full merge-gate conjunction holds (playbook §
  "Merge gate").

Its completion re-invokes you. **Each turn, also re-arm a long
`ScheduleWakeup` fallback (≥ 1200 s)** so a silently-dead watcher cannot
strand the chain — the playbook's "never end a turn with a dead gap" rule.

While the watcher runs, do not idle: read the next phase's task file, sync
the default branch, pre-draft replies to review threads the last push already
addressed.

### STEP 3: React to the verdict

- **`CI_FAILED` or `BOT_COMMENTED`** → the fix procedure (playbook §§ "Fix
  procedure" and "Resolving bot threads"): release the phase branch from the
  implementer's worktree first, then fix — inline in a fresh worktree or via
  a fix sub-agent (escalate its model per the config) — addressing **every**
  failing check and **every** bot comment, down to nit severity. Push,
  resolve each thread one at a time citing the real fix SHA, then return to
  STEP 2 with a new watcher.
- **`BOT_TIMEOUT`** → the unresponsive-bot procedure (playbook § "Review-bot
  request"): confirm with a fresh read that no review arrived, remove the
  stale request (`gh pr edit <N> --remove-reviewer <bot-slug>`), leave one
  factual PR comment as the audit trail, then re-evaluate the gate CI-only
  (safe: the implementer already iterated the reviews to zero before the PR
  opened). Gate holds → STEP 4.
- **`READY_TO_MERGE`** → STEP 4.

### STEP 4: Merge — only after the grace window, then delete the branch

Re-verify the merge-gate conjunction one final time (state may have changed
since the watcher exited), honoring the **grace window** (config value,
default ≥ 4–5 min since the last push, measured concretely — never eyeballed).
Then:

```bash
BR=$(gh pr view <PR#> --json headRefName -q .headRefName)
gh pr merge <PR#> --squash --delete-branch
git switch <default-branch> && git pull
git worktree remove <implementer-worktree-path> --force   # if still present
git branch -D "$BR" 2>/dev/null || true
git push origin --delete "$BR" 2>/dev/null || true
git ls-remote --heads origin "$BR"    # MUST print nothing
git branch --list "$BR"               # MUST print nothing
```

The last two commands are the proof. **A merge is not done until its branch
is gone** — locally and on the remote.

### STEP 5: Update dashboards, then chain

Follow the roadmap's own update protocol, with the **one status legend** the
planning docs use (📋 ToDo · 🔄 In Progress · 👀 Review · ✅ Done ·
⛔ Blocked · 🟡 Partial — never invent a second vocabulary):

- Roadmap Progress Dashboard: phase row → ✅, progress counter, last-updated,
  and the aggregate counters (phases done / total, tasks done / total, active
  phase).
- Tasks README index: mirror row + totals.
- The phase file header + completion log (if the implementer's per-task
  completion protocol did not already finalize it).

**Audit before declaring Done**: confirm the phase's Definition of Done in
the roadmap is actually met and CI is green on the merged default branch —
verified via `gh`/`git`, never via any agent's narration. Any unmet bullet →
🟡 Partial, and the phase stays not-Done.

Commit `docs(plan): mark P<N> complete` (Conventional Commits, **no
attribution trailers**), push.

Then **LOOP → STEP 0**. Before ending any turn, ensure there is always
either a tracked background job pending or a `ScheduleWakeup` armed.

---

## STATUS mode

Read-only. Report: the dashboard counters (phases/tasks done), the active
phase and its status, any open phase PR (`gh pr list --search "phase in
title"` or by branch prefix) with its CI + review state, and whether the
chain appears stalled (open PR with no watcher running). Change nothing.

---

## Hard rules (always — these override convenience)

- **ONE implementer at a time. ONE test suite at a time. Never fan out
  parallel agents that run test suites.** Concurrent suites multiply memory
  by `workers × runners × agents` and have crashed real machines; concurrent
  compose/Testcontainers stacks collide on ports. Keep worker pools bounded
  (`maxWorkers: '50%'` baked into configs).
- **The orchestrator never implements features.** Implementers implement;
  you own everything from "PR opened" to "merged + next phase spawned".
  (Small doc/dashboard commits and review fixes are yours.)
- **Implementers never wait, never merge, never spawn.** The rendered
  prompt's architecture override enforces this; if an implementer reports it
  merged something, treat it as confabulation and verify the real state.
- **Never merge before the full gate conjunction + grace window.** CI-green
  alone is not the gate.
- **Never trust narration — verify via `git`/`gh`.** Agents can confabulate
  SHAs, fixes, and state. Never `Read` an agent's raw transcript/output file;
  read only the verdict files your own background watchers write.
- **Never end a turn with a dead gap** — a pending tracked background job or
  an armed `ScheduleWakeup`, always.
- **Branch hygiene**: create branches with `git switch -c` (never
  `git checkout -b`), delete the merged PR's branch remote + local with the
  printed proof, `git worktree prune` when done.
- **No suppression, no force-green**: never `--no-verify`, `@ts-ignore`,
  `eslint-disable`, `#[allow]`, skipped hooks, or weakened thresholds to get
  a gate to pass — in your fixes or in what you accept from implementers
  (/bymax-quality:code-review treats them as CRITICAL).
- **Conventional Commits everywhere; no AI-attribution trailers** (no
  `Co-Authored-By`, no "Generated with") in commits, PR titles, PR bodies, or
  comments — per /bymax-workflow:standards §9.
- **Respect the project's `CLAUDE.md` / `AGENTS.md`** — and when the config
  and the planning docs conflict, the planning docs win for *what* to build
  and the config wins for *how the chain runs*.
- **Cost awareness**: this loop is token-intensive by design (an implementer
  per phase, reviews iterated to zero, fix cycles). The model policy exists
  to spend the strong tier only where first-pass judgment matters; do not
  silently upgrade every phase.

---

## Termination summary

| Event | Action |
|---|---|
| All phases ✅ + CI green on default branch | Report + `PushNotification`, STOP. |
| External precondition unmet | Mark ⛔ in both dashboards, commit, report, STOP cleanly. |
| Same phase fails its gates repeatedly (3 full fix cycles without progress) | Mark 🟡/⛔ with the exact failing gate, `PushNotification`, STOP — never brute-force. |
| Operator interrupts | Leave state consistent: dashboards reflect reality, no orphan worktrees, open PR noted. |

