<!-- ferrox:loop-host
step: execute
points: execute:pre, execute:wave:pre, execute:wave:post, execute:post
agent-roles: executor, verifier
produces: SUMMARY.md
consumes: PLAN.md
-->
<purpose>
Execute all plans in a phase using wave-based parallel execution. Orchestrator stays lean — delegates plan execution to subagents.
</purpose>

<core_principle>
Orchestrator coordinates, not executes. Each subagent loads the full execute-plan context. Orchestrator: discover plans → analyze deps → group waves → spawn agents → handle checkpoints → collect results.
</core_principle>

<runtime_compatibility>
**Subagent spawning is runtime-specific:**
- **Claude Code:** Uses `Agent(subagent_type="ferrox-executor", ...)` — blocks until complete, returns result
- **Copilot:** Subagent spawning does not reliably return completion signals. **Default to
  sequential inline execution**: read and follow execute-plan.md directly for each plan
  instead of spawning parallel agents. Only attempt parallel spawning if the user
  explicitly requests it — and in that case, rely on the spot-check fallback in step 3
  to detect completion.
- **Other runtimes:** If `Agent`/`agent` tool is genuinely unavailable (e.g. a backgrounded
  Claude Code agent per #853, or a non-Claude runtime), use sequential inline execution as
  the fallback for executor parallelization only. If `Agent` IS available (top-level Claude
  Code), you MUST spawn ferrox-executor agents — inline execution is not authorized. Check for
  actual tool availability, not runtime name.

**Fallback rule:** If a spawned agent completes its work (commits visible, SUMMARY.md exists) but
the orchestrator never receives the completion signal, treat it as successful based on spot-checks
and continue to the next wave/plan. Never block indefinitely waiting for a signal — always verify
via filesystem and git state.
</runtime_compatibility>

<required_reading>
Read STATE.md before any operation to load project context.
@~/.claude/ferrox-core/references/agent-contracts.md
@~/.claude/ferrox-core/references/context-budget.md
@~/.claude/ferrox-core/references/gates.md
</required_reading>

<available_agent_types>
These are the valid Ferrox subagent types registered in .claude/agents/ (or equivalent for your runtime).
Always use the exact name from this list — do not fall back to 'general-purpose' or other built-in types:

- ferrox-executor — Executes plan tasks, commits, creates SUMMARY.md
- ferrox-verifier — Verifies phase completion, checks quality gates
- ferrox-planner — Creates detailed plans from phase scope
- ferrox-phase-researcher — Researches technical approaches for a phase
- ferrox-plan-checker — Reviews plan quality before execution
- ferrox-debugger — Diagnoses and fixes issues
- ferrox-codebase-mapper — Maps project structure and dependencies
- ferrox-integration-checker — Checks cross-phase integration
- ferrox-nyquist-auditor — Validates verification coverage
- ferrox-ui-researcher — Researches UI/UX approaches
- ferrox-ui-checker — Reviews UI implementation quality
- ferrox-ui-auditor — Audits UI against design requirements
</available_agent_types>

<process>

<step name="parse_args" priority="first">
Parse `$ARGUMENTS` before loading any context:

- First positional token → `PHASE_ARG`
- Optional `--wave N` → `WAVE_FILTER`
- Optional `--gaps-only` keeps its current meaning
- Optional `--cross-ai` → `CROSS_AI_FORCE=true` (force all plans through cross-AI execution)
- Optional `--no-cross-ai` → `CROSS_AI_DISABLED=true` (disable cross-AI for this run, overrides config and frontmatter)
- Optional `--fleet` → `BACKEND_FLAG=--fleet` (execute this phase as a fleet of worker processes)
- Optional `--inline` → `BACKEND_FLAG=--inline` (execute this phase inline in this session)

`--fleet` and `--inline` together is a REFUSAL, not last token wins. Do not pick one. The
`resolve_execution_backend` step below refuses the run for you and names why.

**The flag is the machine surface. The surface people use is a sentence.** Set
`BACKEND_INTENT` to the text the user actually wrote, so the switch can read a backend
out of it:

- If the user expressed the backend in the arguments (`/ferrox-execute-phase 21 use the ferrox fleet`), `BACKEND_INTENT="$ARGUMENTS"`.
- If the user expressed it in the surrounding request instead ("build phase 21 with the ferrox fleet"), set `BACKEND_INTENT` to that sentence VERBATIM. Do not paraphrase it, do not summarise it, and do not decide the backend yourself. Hand the words to the switch and let it answer.
- If the user said nothing about a backend, `BACKEND_INTENT="$ARGUMENTS"` is still correct. A sentence with no backend request in it resolves nothing, which is the ordinary case.

**Never infer the backend in your own head.** The matcher is deliberately narrow, it refuses
contradictions, and it echoes what it understood. An inference you make silently has none of
those 3 properties.

If `--wave` is absent, preserve the current behavior of executing all incomplete waves in the phase.
</step>

<step name="resolve_execution_backend" priority="first">
**Every run names its execution backend out loud before it executes anything.**

Run the switch. It is the only place a backend is chosen, and it prints the reason on
every path:

```bash
# BACKEND_FLAG is "--fleet", "--inline", or empty (from parse_args).
# BACKEND_INTENT is the user's own words (from parse_args).
# Canonical resolver, see ferrox-core/references/ferrox-script-resolver.md.
# RUNTIME_DIR first, then the project tree, then the install root per runtime.
ferrox_script() { _n="$1"; _p="${RUNTIME_DIR:-$(git rev-parse --show-toplevel 2>/dev/null || pwd)}"; for _c in "${_p}/scripts/${_n}" "${_p}/.claude/scripts/${_n}" "${_p}/.codex/scripts/${_n}" "${CLAUDE_CONFIG_DIR:-$HOME/.claude}/scripts/${_n}" "${HERMES_HOME:-$HOME/.hermes}/scripts/${_n}" "${CURSOR_CONFIG_DIR:-$HOME/.cursor}/scripts/${_n}" "${CODEX_HOME:-$HOME/.codex}/scripts/${_n}" "${GEMINI_CONFIG_DIR:-$HOME/.gemini}/scripts/${_n}" "${COPILOT_CONFIG_DIR:-$HOME/.copilot}/scripts/${_n}" "${WINDSURF_CONFIG_DIR:-$HOME/.codeium/windsurf}/scripts/${_n}" "${AUGMENT_CONFIG_DIR:-$HOME/.augment}/scripts/${_n}" "${TRAE_CONFIG_DIR:-$HOME/.trae}/scripts/${_n}" "${QWEN_CONFIG_DIR:-$HOME/.qwen}/scripts/${_n}" "${CODEBUDDY_CONFIG_DIR:-$HOME/.codebuddy}/scripts/${_n}" "${CLINE_CONFIG_DIR:-$HOME/.cline}/scripts/${_n}" "${GROK_AGENTS_HOME:-$HOME/.agents}/scripts/${_n}" "${ANTIGRAVITY_CONFIG_DIR:-$HOME/.gemini/antigravity}/scripts/${_n}" "${OPENCODE_CONFIG_DIR:-${XDG_CONFIG_HOME:-$HOME/.config}/opencode}/scripts/${_n}" "${KILO_CONFIG_DIR:-${XDG_CONFIG_HOME:-$HOME/.config}/kilo}/scripts/${_n}"; do [ -f "$_c" ] && { printf '%s\n' "$_c"; return 0; }; done; printf '%s\n' "${_p}/scripts/${_n}"; return 1; }
SWITCH=$(ferrox_script execution-backend-switch.cjs)
VERDICT=$(ferrox_script parallelism-verdict.cjs)

# Precedence level 4, live rather than inert (FF-B410). A phase with no readable
# work graph leaves this empty and the switch names that as the reason it degraded.
RECOMMENDATION=$(node "$VERDICT" "${PHASE_ARG}" --pick 2>/dev/null || true)

BACKEND_JSON=$(node "$SWITCH" ${BACKEND_FLAG:-} \
  ${BACKEND_INTENT:+--intent "$BACKEND_INTENT"} \
  ${RECOMMENDATION:+--recommendation "$RECOMMENDATION"} --json)
BACKEND_EXIT=$?
```

**Obey the exit code.**

- Exit `2` is a REFUSAL. **STOP.** Execute nothing. Report the stderr line to the user
  verbatim. This happens when `--fleet` was asked for explicitly and cannot be honored,
  when the fleet was asked for IN WORDS and cannot be honored, when `--fleet` and
  `--inline` were both given, or when one sentence asked for both backends.
- Exit `0` means a backend was resolved. Read `executed_backend` from the JSON and
  execute that way. Read `reason` and `precedence` and **state both to the user in one
  line before the first wave spawns.**

Precedence, highest first, resolved inside the switch:

1. the explicit flag on this invocation
2. the backend the user asked for IN WORDS, read out of `BACKEND_INTENT`
3. `claude_orchestration.execution_backend` in `.planning/config.json`
4. the parallelism verdict's recommendation
5. inline, naming why level 4 was not usable

**Echo every inference before acting.** When `precedence` is `language`, the switch emits a
notice reading `understood "<phrase>" as backend <backend>. Say --inline or "run it inline"
to override.` **Repeat that line to the user before the first wave spawns.** A silent
inference is strictly worse than a flag, because the reader cannot see that it was made.

**When a flag and the words disagree, the flag wins and the switch says so.** Repeat that
notice too. A person who typed both should be told which one this run obeyed.

**The asymmetry is deliberate.** An explicit `--fleet` that cannot be honored refuses,
because a person made a decision and running inline behind their back would be lying to
them. **A fleet asked for in words refuses exactly the same way**, because that person
decided just as much. A CONFIG default that cannot be honored falls back to inline and says
so loudly, because a configuration value must never break an unattended build. Config is
the only level that falls back.

**When `executed_backend` is `inline` while `resolved_backend` is `fleet`,** the switch
reports `fleet backend resolved, no dispatch manifest consumer is installed in this tree
(scripts/fleet-dispatch.cjs is absent or declares a different manifest kind), executing
inline`. Repeat that line to the user and execute inline.
**Never report a fleet run that did not happen.**

**Resolution is not execution.** A resolved fleet has spawned nothing. The switch says
`dispatching through scripts/fleet-dispatch.cjs`, and the next step is what actually
dispatches. Do not tell the user a fleet ran until that step reports it.
</step>

<step name="dispatch_the_fleet">
**Run this step ONLY when `executed_backend` is `fleet`.** Skip it entirely on every
inline path.

The fleet does not dispatch from this prompt. It dispatches from a MANIFEST, emitted by
the same orchestration capability the inline path uses, and consumed by
`scripts/fleet-dispatch.cjs`, which validates it, refuses overlapping write lanes, and
drives the shipped fleet driver.

```bash
# Canonical resolver, see ferrox-core/references/ferrox-script-resolver.md.
# RUNTIME_DIR first, then the project tree, then the install root per runtime.
ferrox_script() { _n="$1"; _p="${RUNTIME_DIR:-$(git rev-parse --show-toplevel 2>/dev/null || pwd)}"; for _c in "${_p}/scripts/${_n}" "${_p}/.claude/scripts/${_n}" "${_p}/.codex/scripts/${_n}" "${CLAUDE_CONFIG_DIR:-$HOME/.claude}/scripts/${_n}" "${HERMES_HOME:-$HOME/.hermes}/scripts/${_n}" "${CURSOR_CONFIG_DIR:-$HOME/.cursor}/scripts/${_n}" "${CODEX_HOME:-$HOME/.codex}/scripts/${_n}" "${GEMINI_CONFIG_DIR:-$HOME/.gemini}/scripts/${_n}" "${COPILOT_CONFIG_DIR:-$HOME/.copilot}/scripts/${_n}" "${WINDSURF_CONFIG_DIR:-$HOME/.codeium/windsurf}/scripts/${_n}" "${AUGMENT_CONFIG_DIR:-$HOME/.augment}/scripts/${_n}" "${TRAE_CONFIG_DIR:-$HOME/.trae}/scripts/${_n}" "${QWEN_CONFIG_DIR:-$HOME/.qwen}/scripts/${_n}" "${CODEBUDDY_CONFIG_DIR:-$HOME/.codebuddy}/scripts/${_n}" "${CLINE_CONFIG_DIR:-$HOME/.cline}/scripts/${_n}" "${GROK_AGENTS_HOME:-$HOME/.agents}/scripts/${_n}" "${ANTIGRAVITY_CONFIG_DIR:-$HOME/.gemini/antigravity}/scripts/${_n}" "${OPENCODE_CONFIG_DIR:-${XDG_CONFIG_HOME:-$HOME/.config}/opencode}/scripts/${_n}" "${KILO_CONFIG_DIR:-${XDG_CONFIG_HOME:-$HOME/.config}/kilo}/scripts/${_n}"; do [ -f "$_c" ] && { printf '%s\n' "$_c"; return 0; }; done; printf '%s\n' "${_p}/scripts/${_n}"; return 1; }
CONSUMER=$(ferrox_script fleet-dispatch.cjs)

# 1. The waves file: the SAME wave/plan model the inline path dispatches, with each
#    plan's `files_modified` declared accurately. An undeclared write lane cannot be
#    checked for overlap, and the consumer refuses a plan that omits the list.
#    Shape: {"phaseDir": "...", "runId": "...", "waves":[{"id":"w1","plans":[
#             {"id":"21-01","brief":"...","files_modified":["src/a.cts"]}]}]}
# 2. The manifest, emitted rather than hand written:
ferrox_run claude-orchestration emit-workflow \
  --waves "$WAVES_JSON" --run-id "$RUN_ID" \
  --phase-dir "$PHASE_DIR" --backend fleet --raw > "$MANIFEST_JSON"

# 3. Read it back BEFORE dispatching anything. --plan-only validates the manifest,
#    reconciles it against the phase work graph and dispatches NOTHING.
node "$CONSUMER" --manifest "$MANIFEST_JSON" --plan-only

# 4. Dispatch.
node "$CONSUMER" --manifest "$MANIFEST_JSON" --json
DISPATCH_EXIT=$?
```

**Obey the exit code, and report the OUTCOME, never your own summary of it.**

- Exit `2` is a REFUSAL. Nothing was dispatched, no card was minted and no worktree was
  cut. Report the stderr line verbatim. The common refusals are a manifest of the wrong
  kind, a manifest whose nodes are not the phase work graph's nodes, and **overlapping
  write lanes**, which is 2 plans in 1 stage declaring the same file. Never work around a
  lane refusal by dispatching anyway.
- Exit `0` means `verdict.outcome` is `dispatched_fleet`, the graph drained and nothing
  parked.
- Exit `1` means dispatch was attempted and this is NOT a clean fleet run. Read
  `verdict.outcome` and say which one it is:
  - `preflight_refused`: the fleet preconditions refused, **no worker was spawned**.
  - `dispatched_nothing`: dispatch was allowed and 0 workers were observed.
  - `dispatched_single_worker`: **1 worker is not a fleet.** Say so in those words.
  - `dispatched_sequentially`: workers ran, and **never 2 at the same time.** That is a
    queue. Report the spawn total AND the width, because the total on its own reads like
    a fleet and the width is what refutes it.
  - `dispatched_fleet` with a non zero exit: workers ran, and the run stopped on a bound
    or drained with parked nodes. Name the parked nodes.
  - `driver_failed`: the driver failed, and the reason travels with the verdict.

**Report all 3 counters to the user: `verdict.counters.observed_spawns`,
`verdict.counters.distinct_nodes` and `verdict.counters.demonstrated_width`.** They are
folded out of the run log the driver wrote, and they are the only evidence that a fleet
ran. The width is the one that distinguishes a fan out from a queue, so it is never
dropped for brevity.
**Never describe a run as a fleet run when `verdict.fleet` is `false`**, whatever the
resolved backend said.

**`proof_harness` is not null?** Then the preflight, the control plane or the worker seam
were supplied by a test harness rather than by the shipped fleet. Say so in the same
breath as the numbers. Those counters describe the dispatch mechanism, not a production
run, and quoting them without the harness is how a rehearsal becomes a published figure.
</step>

<step name="initialize" priority="first">
Load all context in one call:

```bash
_FERROX_SHIM_NAME="ferrox-tools.cjs"; _FERROX_RUNTIME_ROOT="${RUNTIME_DIR:-$(git rev-parse --show-toplevel 2>/dev/null || pwd)}"; FERROX_TOOLS="${_FERROX_RUNTIME_ROOT}/ferrox-core/bin/${_FERROX_SHIM_NAME}"; if [ -f "$FERROX_TOOLS" ]; then ferrox_run() { node "$FERROX_TOOLS" "$@"; }; elif [ -f "${_FERROX_RUNTIME_ROOT}/.claude/ferrox-core/bin/${_FERROX_SHIM_NAME}" ]; then FERROX_TOOLS="${_FERROX_RUNTIME_ROOT}/.claude/ferrox-core/bin/${_FERROX_SHIM_NAME}"; ferrox_run() { node "$FERROX_TOOLS" "$@"; }; elif [ -f "${_FERROX_RUNTIME_ROOT}/.codex/ferrox-core/bin/${_FERROX_SHIM_NAME}" ]; then FERROX_TOOLS="${_FERROX_RUNTIME_ROOT}/.codex/ferrox-core/bin/${_FERROX_SHIM_NAME}"; ferrox_run() { node "$FERROX_TOOLS" "$@"; }; elif command -v ferrox-tools >/dev/null 2>&1; then FERROX_TOOLS="$(command -v ferrox-tools)"; ferrox_run() { "$FERROX_TOOLS" "$@"; }; elif [ -f "${CLAUDE_CONFIG_DIR:-$HOME/.claude}/ferrox-core/bin/${_FERROX_SHIM_NAME}" ]; then FERROX_TOOLS="${CLAUDE_CONFIG_DIR:-$HOME/.claude}/ferrox-core/bin/${_FERROX_SHIM_NAME}"; ferrox_run() { node "$FERROX_TOOLS" "$@"; }; elif [ -f "${HERMES_HOME:-$HOME/.hermes}/ferrox-core/bin/${_FERROX_SHIM_NAME}" ]; then FERROX_TOOLS="${HERMES_HOME:-$HOME/.hermes}/ferrox-core/bin/${_FERROX_SHIM_NAME}"; ferrox_run() { node "$FERROX_TOOLS" "$@"; }; elif [ -f "${CURSOR_CONFIG_DIR:-$HOME/.cursor}/ferrox-core/bin/${_FERROX_SHIM_NAME}" ]; then FERROX_TOOLS="${CURSOR_CONFIG_DIR:-$HOME/.cursor}/ferrox-core/bin/${_FERROX_SHIM_NAME}"; ferrox_run() { node "$FERROX_TOOLS" "$@"; }; elif [ -f "${CODEX_HOME:-$HOME/.codex}/ferrox-core/bin/${_FERROX_SHIM_NAME}" ]; then FERROX_TOOLS="${CODEX_HOME:-$HOME/.codex}/ferrox-core/bin/${_FERROX_SHIM_NAME}"; ferrox_run() { node "$FERROX_TOOLS" "$@"; }; elif [ -f "${GEMINI_CONFIG_DIR:-$HOME/.gemini}/ferrox-core/bin/${_FERROX_SHIM_NAME}" ]; then FERROX_TOOLS="${GEMINI_CONFIG_DIR:-$HOME/.gemini}/ferrox-core/bin/${_FERROX_SHIM_NAME}"; ferrox_run() { node "$FERROX_TOOLS" "$@"; }; elif [ -f "${COPILOT_CONFIG_DIR:-$HOME/.copilot}/ferrox-core/bin/${_FERROX_SHIM_NAME}" ]; then FERROX_TOOLS="${COPILOT_CONFIG_DIR:-$HOME/.copilot}/ferrox-core/bin/${_FERROX_SHIM_NAME}"; ferrox_run() { node "$FERROX_TOOLS" "$@"; }; elif [ -f "${WINDSURF_CONFIG_DIR:-$HOME/.codeium/windsurf}/ferrox-core/bin/${_FERROX_SHIM_NAME}" ]; then FERROX_TOOLS="${WINDSURF_CONFIG_DIR:-$HOME/.codeium/windsurf}/ferrox-core/bin/${_FERROX_SHIM_NAME}"; ferrox_run() { node "$FERROX_TOOLS" "$@"; }; elif [ -f "${AUGMENT_CONFIG_DIR:-$HOME/.augment}/ferrox-core/bin/${_FERROX_SHIM_NAME}" ]; then FERROX_TOOLS="${AUGMENT_CONFIG_DIR:-$HOME/.augment}/ferrox-core/bin/${_FERROX_SHIM_NAME}"; ferrox_run() { node "$FERROX_TOOLS" "$@"; }; elif [ -f "${TRAE_CONFIG_DIR:-$HOME/.trae}/ferrox-core/bin/${_FERROX_SHIM_NAME}" ]; then FERROX_TOOLS="${TRAE_CONFIG_DIR:-$HOME/.trae}/ferrox-core/bin/${_FERROX_SHIM_NAME}"; ferrox_run() { node "$FERROX_TOOLS" "$@"; }; elif [ -f "${QWEN_CONFIG_DIR:-$HOME/.qwen}/ferrox-core/bin/${_FERROX_SHIM_NAME}" ]; then FERROX_TOOLS="${QWEN_CONFIG_DIR:-$HOME/.qwen}/ferrox-core/bin/${_FERROX_SHIM_NAME}"; ferrox_run() { node "$FERROX_TOOLS" "$@"; }; elif [ -f "${CODEBUDDY_CONFIG_DIR:-$HOME/.codebuddy}/ferrox-core/bin/${_FERROX_SHIM_NAME}" ]; then FERROX_TOOLS="${CODEBUDDY_CONFIG_DIR:-$HOME/.codebuddy}/ferrox-core/bin/${_FERROX_SHIM_NAME}"; ferrox_run() { node "$FERROX_TOOLS" "$@"; }; elif [ -f "${CLINE_CONFIG_DIR:-$HOME/.cline}/ferrox-core/bin/${_FERROX_SHIM_NAME}" ]; then FERROX_TOOLS="${CLINE_CONFIG_DIR:-$HOME/.cline}/ferrox-core/bin/${_FERROX_SHIM_NAME}"; ferrox_run() { node "$FERROX_TOOLS" "$@"; }; elif [ -f "${GROK_AGENTS_HOME:-$HOME/.agents}/ferrox-core/bin/${_FERROX_SHIM_NAME}" ]; then FERROX_TOOLS="${GROK_AGENTS_HOME:-$HOME/.agents}/ferrox-core/bin/${_FERROX_SHIM_NAME}"; ferrox_run() { node "$FERROX_TOOLS" "$@"; }; elif [ -f "${ANTIGRAVITY_CONFIG_DIR:-$HOME/.gemini/antigravity}/ferrox-core/bin/${_FERROX_SHIM_NAME}" ]; then FERROX_TOOLS="${ANTIGRAVITY_CONFIG_DIR:-$HOME/.gemini/antigravity}/ferrox-core/bin/${_FERROX_SHIM_NAME}"; ferrox_run() { node "$FERROX_TOOLS" "$@"; }; elif [ -f "${OPENCODE_CONFIG_DIR:-${XDG_CONFIG_HOME:-$HOME/.config}/opencode}/ferrox-core/bin/${_FERROX_SHIM_NAME}" ]; then FERROX_TOOLS="${OPENCODE_CONFIG_DIR:-${XDG_CONFIG_HOME:-$HOME/.config}/opencode}/ferrox-core/bin/${_FERROX_SHIM_NAME}"; ferrox_run() { node "$FERROX_TOOLS" "$@"; }; elif [ -f "${KILO_CONFIG_DIR:-${XDG_CONFIG_HOME:-$HOME/.config}/kilo}/ferrox-core/bin/${_FERROX_SHIM_NAME}" ]; then FERROX_TOOLS="${KILO_CONFIG_DIR:-${XDG_CONFIG_HOME:-$HOME/.config}/kilo}/ferrox-core/bin/${_FERROX_SHIM_NAME}"; ferrox_run() { node "$FERROX_TOOLS" "$@"; }; else echo "ERROR: ferrox-tools.cjs not found at $FERROX_TOOLS and ferrox-tools is not on PATH. Run: npx -y ferrox-factory@latest --claude --local" >&2; exit 1; fi; if [ -n "${CLAUDE_ENV_FILE:-}" ] && [ -n "${FERROX_TOOLS:-}" ]; then printf "export PATH='%s':\"\$PATH\"\n" "${FERROX_TOOLS%/*}" >> "$CLAUDE_ENV_FILE" 2>/dev/null || true; fi
INIT=$(ferrox_run query init.execute-phase "${PHASE_ARG}")
if [[ "$INIT" == @file:* ]]; then INIT=$(cat "${INIT#@file:}"); fi
AGENT_SKILLS=$(ferrox_run query agent-skills ferrox-executor)
```

Parse JSON for: `executor_model`, `verifier_model`, `commit_docs`, `parallelization`, `branching_strategy`, `branch_name`, `phase_found`, `phase_dir`, `phase_number`, `phase_name`, `phase_slug`, `plans`, `incomplete_plans`, `plan_count`, `incomplete_count`, `state_exists`, `roadmap_exists`, `phase_req_ids`, `response_language`.

**Model resolution:** If `executor_model` is `"inherit"`, omit the `model=` parameter from all `Agent()` calls — do NOT pass `model="inherit"` to Agent. Omitting the `model=` parameter causes Claude Code to inherit the current orchestrator model automatically. Only set `model=` when `executor_model` is an explicit model name (e.g., `"claude-sonnet-5"`, `"claude-opus-4-8"`).

**If `response_language` is set:** Include `response_language: {value}` in all spawned subagent prompts so any user-facing output stays in the configured language.

**Risk-graded model routing at spawn (MODEL-03 / SPEED-02 — APPLIED, not advisory).**
Before spawning the executor for a plan, consult `model.risk-grade` with that plan's
declared files and categories. A plan touching a risk boundary
(auth/crypto/payments/PII/deserialization/network-file) is **force-upgraded to the
frontier tier regardless of `executor_model` or the plan's self-grade**, and its wave
is flagged for Trident. This is what makes risk-graded routing real rather than a
decorative core:

```bash
# PLAN_PATHS = comma-joined `files_modified` from the plan frontmatter;
# PLAN_CATS  = comma-joined plan categories/tags (e.g. "auth,crypto"); SELF_GRADE default "low".
RISK=$(ferrox_run query model.risk-grade --self-grade "${SELF_GRADE:-low}" \
  --paths "${PLAN_PATHS}" --categories "${PLAN_CATS}" --raw)
FORCE_FRONTIER=$(printf '%s' "$RISK" | ferrox_run query - --pick forcesFrontier 2>/dev/null || printf '%s' "$RISK" | grep -q '"forcesFrontier": *true' && echo true || echo false)
FORCE_TRIDENT=$(printf '%s' "$RISK" | grep -q '"forcesTrident": *true' && echo true || echo false)
# If FORCE_FRONTIER=true, override this plan's executor model to the frontier tier
# (the configured frontier model, e.g. opus) for its Agent() call — even when
# executor_model resolved to sonnet/haiku/inherit. If FORCE_TRIDENT=true, mark the
# wave so the high-risk wave-audit runs Trident (MODEL-04 checkpoint 2).
```

A plan that self-grades `low` but writes `src/auth/*` still runs on frontier — the
boundary match wins over the self-grade, closing the "auth plan not force-upgraded" gap.

**Adaptive discipline depth + audit tier at spawn (FAST-01/FAST-03 — the v1.2 speed path).**
Immediately after the risk consult, resolve the *process depth* and *audit tier* for the plan
via the single authoritative decider `strength.depth-decide` (it composes the same risk-grade,
so depth/audit and model routing can never disagree):

```bash
# Persists an auditable decision AND returns it. REQ = the plan's primary requirement id.
DEPTH_JSON=$(ferrox_run query strength.depth-decide --requirement "${REQ}" \
  --self-grade "${SELF_GRADE:-low}" --paths "${PLAN_PATHS}" --categories "${PLAN_CATS}" \
  --declared-depth "${PLAN_DECLARED_DEPTH:-}" --raw)
DEPTH=$(printf '%s' "$DEPTH_JSON"      | ferrox_run query - --pick depth)      # fast | full
AUDIT_TIER=$(printf '%s' "$DEPTH_JSON" | ferrox_run query - --pick auditTier)  # internal | cross
```

Then branch the rituals — this is where the speed comes from. **The cheap gates
(halting caps, fail-closed merge-gate, floors) ALWAYS run on both paths; only the
expensive rituals are tiered:**

- **`DEPTH=fast`, `AUDIT_TIER=internal`** (low-risk) → skip RED-first, skip mutation. Implement →
  verify (test-after) → an **internal fresh-context adversarial subagent** (no external round-trip) →
  cheap gates. The executor prompt drops `@…/tdd.md`. Merge at `strength.merge-gate --depth fast`
  (receipts+mutation replaced by the audited depth decision; the gate re-grades the ACTUAL diff so a
  fast claim on boundary files is refused).
- **`DEPTH=full`, `AUDIT_TIER=cross`** (genuine high-risk — boundary hit / high-risk self-grade) → the
  **3-eye parallel cross-audit** and **NO RED-first, NO mutation ritual**. The 5-lane benchmark
  (`.planning/BENCHMARK-v1.2-5LANE.md`) proved RED+mutation stacked on top of a cross-audit buy zero
  correctness (B4==B5==19/19) — so the cross-audit REPLACES them. Run all three eyes **in parallel**:
    1. **codex** — `codex exec --skip-git-repo-check "<security review prompt>"`
    2. **gemini** — `gemini --skip-trust -p "<security review prompt>"`
    3. **internal adversarial** — a fresh-context subagent (claude lineage) told to REFUTE the change.
  Three distinct lineages (openai + google + claude) — exceeds Trident's ≥2-distinct-lineage rule and
  adds a third perspective the external pair can miss. Fire all three at once (they're independent);
  wall-clock is the slowest eye (~codex 43s), not the sum. Apply every legitimate finding, then merge at
  `strength.merge-gate --audit-tier cross --cross-audit passed` (only after the panel actually ran and
  its critical/high findings are resolved). Measured: this pulls the high-risk path from ~995s toward
  ~450s while holding 19/19 (`BENCHMARK-v1.2-5LANE.md`).
- **`DEPTH=full`, `AUDIT_TIER=internal`** (full-but-not-high-risk — declared/ratchet/ungradeable) →
  RED-first + mutation receipt + the full evidence manifest, exactly as before. No cross-audit is
  scheduled here, so the RED+mutation floor is NOT redundant — it stays.

**Cross-audit CADENCE (XAUD-01, v1.6 — never trust one AI, but batch the expensive audit).** The
per-increment 3-eye cross-audit above is the **mid-milestone risk-boundary trigger** of the cadence
policy — a boundary/high-risk phase gets its expensive multi-lineage audit *immediately*, security never
waits. Every OTHER phase **defers** its expensive audit to the milestone boundary, where it is run once
over the accumulated work (that is where the "never trust one AI over the whole body of work" guarantee
lives — see `audit-milestone.md`). The cheap gate + internal adversarial subagent still run every phase.
Consult the decider so the choice is auditable:

```bash
# crossesRiskBoundary is true exactly when AUDIT_TIER=cross (a boundary/high-risk grade).
XAUD=$(ferrox_run query strength.cross-audit-cadence --event phase-complete \
        $( [ "$AUDIT_TIER" = "cross" ] && printf -- '--crosses-risk-boundary' ) \
        --phases-since-audit "${PHASES_SINCE_AUDIT:-0}" --raw 2>/dev/null | ferrox_run query - --pick crossAudit 2>/dev/null || echo false)
# XAUD=true  -> run the 3-eye cross-audit inline now (risk-boundary / max-phases trigger).
# XAUD=false -> DEFER: record that the milestone owes a cross-audit; keep the cheap gate + internal eye.
```

**Executor model tier by depth (FAST-05 — the biggest *typical-increment* lever).** The measured
cost of a Ferrox increment is dominated by executor MODEL reasoning, not test machinery (see
`.planning/OVERNIGHT-v1.2-SPEED.md` EXP-1b). So the fast path routes the executor to a faster,
cheaper model — safe precisely because the work is low-risk AND the merge-gate still verifies it
(low-risk + fast model + gate = the Anvil thesis: pedigree stops mattering once the gate holds):

```bash
# Precedence: a forced-frontier (boundary) plan ALWAYS wins — safety over speed.
# A fast plan resolves its executor through the LIGHT lane; full-but-not-high-risk
# keeps the default execute (mid) resolution.
if [ "$FORCE_FRONTIER" = "true" ]; then
  EXECUTOR_TIER=frontier          # high-risk: the strongest model, no compromise
elif [ "$DEPTH" = "fast" ]; then
  EXECUTOR_TIER=light             # low-risk: the fast/cheap lane (dynamic_routing.tier_models.light)
else
  EXECUTOR_TIER=standard          # full-but-not-high-risk: the default execute tier
fi
```

The tier→model-id mapping rides the **existing `dynamic_routing.tier_models` seam** that
ROUTE-FLUX-01 already locks (`heavy→flux-reasoning`, `standard→flux-standard`, `light→flux-fast`),
resolved provider-agnostically by `model-resolver`. **FF-B26 is CLOSED (v1.13 P2 W3, A13):** the thin
bare-tier resolver landed as the `model.resolve-tier` verb, and this seam resolves through it. 1 seam,
no inline `tier_models` mapping here anymore:

```bash
RT=$(ferrox_run query model.resolve-tier --tier "$EXECUTOR_TIER" --raw 2>/dev/null || echo '{}')
EXECUTOR_MODEL_ID=$(printf '%s' "$RT" | ferrox_run query - --pick modelId 2>/dev/null || echo "")
RT_NOTICE=$(printf '%s' "$RT" | ferrox_run query - --pick notice 2>/dev/null || echo "")
# A10 loud ladder miss: when the tier is not in the ladder the verb returns modelId null
# plus a NOT IN LADDER notice. SURFACE the notice verbatim in the wave log, then dispatch
# on the default executor model (executor_model from init). Never pass a null/empty model
# id silently.
if [ -n "$RT_NOTICE" ] && [ "$RT_NOTICE" != "null" ]; then echo "$RT_NOTICE"; fi
```

Pass the resolved id as `model=` on the executor `Agent()` call. **This is the one place "faster"
could cost "better,"** so it is fenced hard: only low-risk plans take the fast model, a boundary plan
can never be routed down, and every increment still passes the same fail-closed merge-gate.

**Universal gate-first router (UGE-08, v1.8 — gate-first is the DEFAULT executor for every
gateable increment).** The v1.4 anvil branch (`DEPTH=fast` + python-single-file, opt-in) is
generalized: ANY increment whose domain admits a real gate (tiers 1–4) and that ships a gate
script routes through the NATIVE gated cheap-loop (`model.gate-first-run`, no shell-out) by
default; tier-6/unknown domains route to the Crucible judge panel when available; everything
else takes the ordinary model executor. This is the Anvil thesis at full strength — *pedigree
stops mattering once the gate holds* (BENCHMARK-v1.7: cheap-pool+gate = 100% correct at
1/7–1/38 frontier cost). The result is **only ever a candidate** — it faces the SAME verify +
merge-gate as any diff, waiving nothing:

```bash
# Gate metadata rides this plan's entry in the phase-plan-index output (UGE-02):
# DOMAIN / DELIVERABLE_KIND / GATE_PRESENT / GATE_SCRIPT = the plan's `domain`,
# `deliverable_kind`, `gate_present`, `gate_script` fields (absent → empty / "false").

# ONE routing consult (the UGE-06 predicate + the UGE-07 crucible PATH probe ride together).
# --executor-available / --enabled are omitted ON PURPOSE: the router probes the provider key
# (presence-only) and reads `model.gate_first.enabled` — DEFAULT TRUE. Gate-first is the default;
# disable it via config, never by editing this seam.
GF=$(ferrox_run query model.gate-first-eligibility --domain "${DOMAIN:-}" --depth "${DEPTH}" \
      --gate-present "${GATE_PRESENT:-false}" --raw 2>/dev/null || echo '{}')
GF_ROUTE=$(printf '%s' "$GF" | ferrox_run query - --pick route 2>/dev/null || echo "normal")
CRUCIBLE_OK=$(printf '%s' "$GF" | ferrox_run query - --pick crucibleAvailable 2>/dev/null || echo "false")

case "$GF_ROUTE" in
  gate-first)
    # THE DEFAULT for eligible increments. Emit spec.md for this increment into the executor's
    # SCRATCH dir; GATE_CMD wraps the plan's gate script with its interpreter (comma-separated argv).
    case "$GATE_SCRIPT" in
      *.py)             GATE_CMD="python3,$GATE_SCRIPT" ;;
      *.cjs|*.js|*.mjs) GATE_CMD="node,$GATE_SCRIPT" ;;
      *)                GATE_CMD="$GATE_SCRIPT" ;;
    esac
    if [ "${ANVIL_EXTERNAL:-0}" = "1" ]; then
      # ESCAPE HATCH — the v1.4 EXTERNAL anvil loop (ANV-01..05) stays reachable as an explicit
      # opt-in: ANVIL_EXTERNAL=1 + model.anvil_executor.enabled=true + the narrow ANV-01 predicate
      # (fast + python-single-file + gate.py + anvil available). Same acceptance, same merge-gate.
      ANVIL_ENABLED=$(ferrox_run query config-get model.anvil_executor.enabled --raw 2>/dev/null || echo "false")
      if [ "$ANVIL_ENABLED" = "true" ] && [ "$DEPTH" = "fast" ] \
         && [ "$DELIVERABLE_KIND" = "python-single-file" ] && [ "$GATE_PRESENT" = "true" ]; then
        ANVIL=$(ferrox_run query model.anvil-run \
                  --label "$PLAN_LABEL" --spec-file "$SCRATCH/spec.md" \
                  --gate-file "$SCRATCH/gate.py" --scratch "$SCRATCH" --raw 2>/dev/null || echo '{}')
        GF_ACTION=$(printf '%s' "$ANVIL" | ferrox_run query - --pick action 2>/dev/null || echo "fallback-normal")
        GF_CANDIDATE=$(printf '%s' "$ANVIL" | ferrox_run query - --pick candidatePath 2>/dev/null || echo "")
      else
        GF_ACTION="fallback-normal"; GF_CANDIDATE=""
      fi
    else
      GF_RUN=$(ferrox_run query model.gate-first-run \
                --spec-file "$SCRATCH/spec.md" --gate-cmd "$GATE_CMD" --domain "$DOMAIN" \
                --scratch "$SCRATCH" --raw 2>/dev/null || echo '{}')
      GF_ACTION=$(printf '%s' "$GF_RUN" | ferrox_run query - --pick action 2>/dev/null || echo "fallback-normal")
      GF_CANDIDATE=$(printf '%s' "$GF_RUN" | ferrox_run query - --pick candidatePath 2>/dev/null || echo "")
    fi
    # accept-candidate → the candidate file becomes the increment's proposed diff, then STILL runs the
    #   normal verify + fail-closed merge-gate (receipts/coverage/ownership/security all required).
    # reject | fallback-normal → the ordinary model executor builds this increment as usual.
    ;;
  crucible)
    # Tier-6 / unknown domains — judge-panel territory (UGE-07, consume-only, fail-safe).
    if [ "$CRUCIBLE_OK" = "true" ]; then
      CRUX=$(node -e 'const c=require(process.argv[1]),f=require("node:fs");const r=c.runCrucible({prompt:f.readFileSync(process.argv[2],"utf8")});if(r.ok)f.writeFileSync(process.argv[3],r.text);process.stdout.write(JSON.stringify({ok:r.ok,reason:r.reason}));' \
              "${FERROX_TOOLS%/*}/lib/crucible-route.cjs" "$SCRATCH/spec.md" "$SCRATCH/crucible-candidate.txt" 2>/dev/null || echo '{}')
      CRUX_OK=$(printf '%s' "$CRUX" | ferrox_run query - --pick ok 2>/dev/null || echo "false")
      # CRUX_OK=true → $SCRATCH/crucible-candidate.txt is this increment's proposed-diff CANDIDATE,
      #   with the SAME fencing: normal verify + the UNCHANGED fail-closed merge-gate.
      # anything else (probe lied, timeout, no usable output) → the ordinary model executor.
    fi
    # crucible unavailable → the ordinary model executor builds this increment (fail-safe).
    ;;
  *)
    : # normal → the existing model executor path (risk/depth/tier routing above already applies).
    ;;
esac
```

**Fences (non-negotiable):** a gate-first, crucible, or anvil candidate never waives a merge-gate
criterion; any doubt (missing gate, un-gateable domain, executor/crucible unavailable, disabled)
falls straight through to the normal executor. Builders only ever see check IDENTIFIERS — never
gate source, never expected values (the spec §4 trust boundary). `~/dev/anvil` is consume-only —
never modified, its `.keys.env` never read. Evidence: `BENCHMARK-v1.4-ANVIL.md` (external loop
A/B), `BENCHMARK-v1.7.md` (cheap-pool+gate objective re-score that justifies the default).

Read runtime/worktree config and fail closed before any executor dispatch:

```bash
RUNTIME=$(ferrox_run query config-get runtime --default claude --raw 2>/dev/null || echo "claude")
USE_WORKTREES=$(ferrox_run query config-get workflow.use_worktrees --raw 2>/dev/null || echo "true")
EXECUTOR_STALL_INTERVAL_MINUTES=$(ferrox_run query config-get executor.stall_detect_interval_minutes 2>/dev/null || echo "5")
EXECUTOR_STALL_THRESHOLD_MINUTES=$(ferrox_run query config-get executor.stall_threshold_minutes 2>/dev/null || echo "10")

if [ "$RUNTIME" != "claude" ] && [ "$USE_WORKTREES" != "false" ]; then
  echo "FATAL: git worktree isolation (isolation=\"worktree\") is unsupported on runtime '$RUNTIME' — it would run executor agents unisolated against the main checkout. Set workflow.use_worktrees=false." >&2
  exit 1
fi
# Sweep orphaned locked worktrees from prior crashed sessions before spawning executors (#3707).
[ "$USE_WORKTREES" != "false" ] && ferrox_run query worktree.reap-orphans 2>/dev/null || true
# Auto-degrade to sequential if HEAD has diverged from the worktree fork base (#683).
# Only applies to Claude Code (isolation="worktree" is Claude-Code-specific).
if [ "$RUNTIME" = "claude" ] && [ "$USE_WORKTREES" != "false" ]; then
  _SHOULD_DEGRADE=$(ferrox_run query worktree.base-check --pick shouldDegrade 2>/dev/null || true)
  if [ "$_SHOULD_DEGRADE" = "true" ]; then
    _DEGRADE_MSG=$(ferrox_run query worktree.base-check --pick message 2>/dev/null || true)
    [ -n "$_DEGRADE_MSG" ] && printf '%s\n' "$_DEGRADE_MSG" >&2
    USE_WORKTREES=false
  fi
fi
```
`isolation="worktree"` is a Claude-Code-specific agent primitive; no other runtime can honor it (Codex maps subagents to `spawn_agent`, others prohibit or omit worktree binding). Failing closed prevents main-checkout edits while the workflow believes agents are isolated.

If the project uses git submodules, worktree isolation is unsafe **only when a plan touches a submodule path** — the executor commit protocol cannot correctly handle submodule commits inside isolated worktrees. The previous behavior unconditionally disabled worktree isolation whenever `.gitmodules` existed, which penalised every plan in a submodule project even when the plan was nowhere near a submodule. Compute submodule paths once and intersect them per-plan with the plan's declared `files_modified` frontmatter.

```bash
# Parse submodule paths from .gitmodules once (empty if no .gitmodules).
# SUBMODULE_PATHS is a newline-separated list of repo-relative paths.
if [ -f .gitmodules ]; then
  SUBMODULE_PATHS=$(git config --file .gitmodules --get-regexp '^submodule\..*\.path$' 2>/dev/null | awk '{print $2}')
else
  SUBMODULE_PATHS=""
fi
```

`SUBMODULE_PATHS` is exported to the `execute_waves` step, where the per-plan decision actually happens (see "Per-plan worktree decision" sub-step inside `execute_waves`). The decision is per-plan because different plans in the same wave can touch different files — only plans whose paths intersect a submodule must drop worktree isolation; plans nowhere near a submodule keep parallel isolation.

When `USE_WORKTREES` (project-level) is `false`, all executor agents run without `isolation="worktree"` — they execute sequentially on the main working tree instead of in parallel worktrees. The per-plan decision below has no effect when worktrees are project-disabled.

`USE_WORKTREES` is also automatically set to `false` for the duration of a run when `worktree base-check` detects that the orchestrator HEAD has diverged from the worktree fork base (the #683 condition — e.g. an unmerged milestone or feature branch). This check runs only when `RUNTIME=claude` because `isolation="worktree"` is a Claude Code-specific feature; other runtimes do not use it. The auto-degrade prints a one-line warning to stderr and falls through to the sequential path so executors do not hit the exit-42 worktree-branch-check halt. To restore parallel worktree execution, set `worktree.baseRef:"head"` in `.claude/settings.local.json` (or run `ferrox-tools worktree set-baseref`) — this makes the fork base track the live HEAD instead of a fixed remote ref. The `worktree-branch-check` exit-42 guard inside each executor remains in place as a backstop.

Read context window size for adaptive prompt enrichment:

```bash
CONTEXT_WINDOW=$(ferrox_run query config-get context_window 2>/dev/null || echo "200000")
```

When `CONTEXT_WINDOW >= 500000` (1M-class models), subagent prompts include richer context:
- Executor agents receive prior wave SUMMARY.md files and the phase CONTEXT.md/RESEARCH.md
- Verifier agents receive all PLAN.md, SUMMARY.md, CONTEXT.md files plus REQUIREMENTS.md
- This enables cross-phase awareness and history-aware verification

When `CONTEXT_WINDOW < 200000` (sub-200K models), subagent prompts are thinned to reduce static overhead:
- Executor agents omit extended deviation rule examples and checkpoint examples from inline prompt — load on-demand via @~/.claude/ferrox-core/references/executor-examples.md
- Planner agents omit extended anti-pattern lists and specificity examples from inline prompt — load on-demand via @~/.claude/ferrox-core/references/planner-antipatterns.md
- Core rules and decision logic remain inline; only verbose examples and edge-case lists are extracted
- This reduces executor static overhead by ~40% while preserving behavioral correctness

**If `phase_found` is false:** Error — phase directory not found.
**If `plan_count` is 0:** Error — no plans found in phase.
**If `state_exists` is false but `.planning/` exists:** Offer reconstruct or continue.

When `parallelization` is false, plans within a wave execute sequentially.

**Runtime detection for Copilot:**
Check if the current runtime is Copilot by testing for the `@ferrox-executor` agent pattern
or absence of the `Agent()` subagent API. If running under Copilot, force sequential inline
execution regardless of the `parallelization` setting — Copilot's subagent completion
signals are unreliable (see `<runtime_compatibility>`). Set `COPILOT_SEQUENTIAL=true`
internally and skip the `execute_waves` step in favor of `check_interactive_mode`'s
inline path for each plan.

**REQUIRED — Sync chain flag with intent.** If user invoked manually (no `--auto`), clear the ephemeral chain flag from any previous interrupted `--auto` chain. This prevents stale `_auto_chain_active: true` from causing unwanted auto-advance. This does NOT touch `workflow.auto_advance` (the user's persistent settings preference). You MUST execute this bash block before any config reads:
```bash
# REQUIRED: prevents stale auto-chain from previous --auto runs
if [[ ! "$ARGUMENTS" =~ --auto ]]; then
  ferrox_run query config-set workflow._auto_chain_active false || true
fi
```

Resolve `MVP_MODE` once via the centralized `phase.mvp-mode` query verb (precedence chain: CLI flag → ROADMAP `**Mode:** mvp` → `workflow.mvp_mode` config → false):
```bash
MVP_FLAG_ARG=""
if [[ "$ARGUMENTS" =~ (^|[[:space:]])--mvp([[:space:]]|$) ]]; then MVP_FLAG_ARG="--cli-flag"; fi
MVP_MODE=$(ferrox_run query phase.mvp-mode "${PHASE_NUMBER}" $MVP_FLAG_ARG --pick active)
EXECUTE_POST_HOOKS_JSON=$(ferrox_run loop render-hooks execute:post --raw)
TDD_MODE=$(ferrox_run loop render-hooks execute:post --active-cap tdd)
```

<step name="safe_resume_gate">
Before trusting `STATE.md` or dispatching any executor, derive `CURRENT_PLAN_ID`
from the active incomplete plan in `INIT`, then search recent history:
```bash
CURRENT_PLAN_ID="{phase_number}-{plan_padded}"
SUMMARY_PATH="{phase_dir}/{plan_padded}-SUMMARY.md"
PLAN_COMMITS=$(git log --oneline --grep="${CURRENT_PLAN_ID}" -30)
```
If production commits exist and `SUMMARY.md is missing` (no `.planning/async-jobs/*.json` manifest matches it: a match is a legal `external_job_waiting` deferral - reconcile per `docs/reference/planning-artifacts.md`, never re-dispatch), stop before spawning a
new executor; continuing risks duplicate work and stale `STATE.md`/ROADMAP progress.
Offer these recovery options:
- `close out manually` — inspect commits, write SUMMARY.md, then update STATE/ROADMAP.
- `re-execute from scratch` — revert or supersede partial commits before dispatch.
- `mark-and-skip` — record the anomaly and move on only with explicit confirmation.
</step>

**MVP+TDD gate.** Task-scoped enforcement runs inside plan execution (immediately before each implementation step), where `TASK_FILE`, `PLAN_ID`, and `TASK_ID` are defined. Keep the same predicate and RED-commit contract:
```bash
if [ "$MVP_MODE" = "true" ] && [ "$TDD_MODE" = "true" ]; then
  IS_BEHAVIOR_ADDING=$(ferrox_run query task.is-behavior-adding "$TASK_FILE" --pick is_behavior_adding)
  if [ "$IS_BEHAVIOR_ADDING" = "true" ]; then
    RED_COMMIT=$(git log --oneline --grep="^test(${PHASE_NUMBER}-${PLAN_ID}):" -- "**/*.test.*" "**/*.spec.*" "tests/" | head -1)
    if [ -z "$RED_COMMIT" ]; then
      ferrox_run query state.update last_gate_trip "${PLAN_ID}/${TASK_ID}" || true
      echo "MVP+TDD GATE TRIPPED: missing RED commit for ${PLAN_ID}/${TASK_ID}"
      exit 1
    fi
  fi
fi
```
Pure doc-only / config-only / test-only tasks return `is_behavior_adding=false` and are exempt. When the gate trips, Read `~/.claude/ferrox-core/references/execute-mvp-tdd.md` for the exact halt report format.
</step>

<step name="check_blocking_antipatterns" priority="first">
**MANDATORY — Check for blocking anti-patterns before any other work.**

Look for a `.continue-here.md` in the current phase directory:

```bash
ls ${phase_dir}/.continue-here.md 2>/dev/null || true
```

If `.continue-here.md` exists, parse its "Critical Anti-Patterns" table for rows with `severity` = `blocking`.

**If one or more `blocking` anti-patterns are found:**

This step cannot be skipped. Before proceeding to `check_interactive_mode` or any other step, the agent must demonstrate understanding of each blocking anti-pattern by answering all three questions for each one:

1. **What is this anti-pattern?** — Describe it in your own words, not by quoting the handoff.
2. **How did it manifest?** — Explain the specific failure that caused it to be recorded.
3. **What structural mechanism (not acknowledgment) prevents it?** — Name the concrete step, checklist item, or enforcement mechanism that stops recurrence.

Write these answers inline before continuing. If a blocking anti-pattern cannot be answered from the context in `.continue-here.md`, stop and ask the user for clarification.

**If no `.continue-here.md` exists, or no `blocking` rows are found:** Proceed directly to `check_interactive_mode`.
</step>

<step name="check_interactive_mode">
**Parse `--interactive` flag from $ARGUMENTS.**

**If `--interactive` flag present:** Switch to interactive execution mode.

Interactive mode executes plans sequentially **inline** (no subagent spawning) with user
checkpoints between tasks. The user can review, modify, or redirect work at any point.

**Interactive execution flow:**

1. Load plan inventory as normal (discover_and_group_plans)
2. For each plan (sequentially, ignoring wave grouping):

   a. **Present the plan to the user:**
      ```
      ## Plan {plan_id}: {plan_name}

      Objective: {from plan file}
      Tasks: {task_count}

      Options:
      - Execute (proceed with all tasks)
      - Review first (show task breakdown before starting)
      - Skip (move to next plan)
      - Stop (end execution, save progress)
      ```

   b. **If "Review first":** Read and display the full plan file. Ask again: Execute, Modify, Skip.

   c. **If "Execute":** Read and follow `~/.claude/ferrox-core/workflows/execute-plan.md` **inline**
      (do NOT spawn a subagent). Execute tasks one at a time.

   d. **After each task:** Pause briefly. If the user intervenes (types anything), stop and address
      their feedback before continuing. Otherwise proceed to next task.

   e. **After plan complete:** Show results, commit, create SUMMARY.md, then present next plan.

3. After all plans: proceed to verification (same as normal mode).

**Benefits of interactive mode:**
- No subagent overhead — dramatically lower token usage
- User catches mistakes early — saves costly verification cycles
- Maintains Ferrox's planning/tracking structure
- Best for: small phases, bug fixes, verification gaps, learning Ferrox

**Skip to handle_branching step** (interactive plans execute inline after grouping).
</step>

<step name="handle_branching">
Check `branching_strategy` from init:

**"none":** Skip, continue on current branch.

**"phase" or "milestone":** Use pre-computed `branch_name` from init.

Fork the new phase branch off `origin/HEAD` (the project's default branch), not the current HEAD — otherwise consecutive phases compound and stay unpushed (#2916). If `$BRANCH_NAME` already exists locally, reuse it as-is.

```bash
DEFAULT_BRANCH=$(ferrox_run query git.base-branch 2>/dev/null \
  || git symbolic-ref --quiet --short refs/remotes/origin/HEAD 2>/dev/null | sed 's|^origin/||' \
  || echo main)

if git show-ref --verify --quiet "refs/heads/$BRANCH_NAME"; then
  git switch "$BRANCH_NAME" || { echo "ERROR: Could not switch to existing branch '$BRANCH_NAME'." >&2; exit 1; }
else
  if ! git fetch --quiet origin "$DEFAULT_BRANCH"; then  # #2916
    git show-ref --verify --quiet "refs/remotes/origin/$DEFAULT_BRANCH" \
      || { echo "ERROR: fetch origin/$DEFAULT_BRANCH failed and no local copy exists. Refusing to create '$BRANCH_NAME' off current HEAD (#2916)." >&2; exit 1; }
    echo "WARNING: fetch origin/$DEFAULT_BRANCH failed; using local copy as base." >&2
  fi
  if [ -n "$(git status --porcelain)" ]; then
    echo "WARNING: Uncommitted changes will be carried onto '$BRANCH_NAME' (branched off origin/$DEFAULT_BRANCH, not previous HEAD)."
  else
    git switch --quiet "$DEFAULT_BRANCH" 2>/dev/null && git merge --ff-only --quiet "origin/$DEFAULT_BRANCH" 2>/dev/null || true
  fi
  # Pinned base + fail-fast: on success HEAD is exactly at origin/$DEFAULT_BRANCH,
  # so a post-creation merge-base or "ahead-of" guard would be unreachable. The
  # explicit base argument here is the single source of correctness for #2916.
  git checkout -b "$BRANCH_NAME" "origin/$DEFAULT_BRANCH" \
    || { echo "ERROR: Could not create '$BRANCH_NAME' from origin/$DEFAULT_BRANCH (#2916)." >&2; exit 1; }
fi
```

All subsequent commits go to this branch. User handles merging.
</step>

<step name="validate_phase">
From init JSON: `phase_dir`, `plan_count`, `incomplete_count`.

Report: "Found {plan_count} plans in {phase_dir} ({incomplete_count} incomplete)"

**Update STATE.md for phase start:**
```bash
ferrox_run query state.begin-phase --phase "${PHASE_NUMBER}" --name "${PHASE_NAME}" --plans "${PLAN_COUNT}"
```
This updates Status, Last Activity, Current focus, Current Position, and plan counts in STATE.md so frontmatter and body text reflect the active phase immediately.
</step>

<step name="discover_and_group_plans">
Load plan inventory with wave grouping in one call:

```bash
PLAN_INDEX=$(ferrox_run query phase-plan-index "${PHASE_NUMBER}")
```

Parse JSON for: `phase`, `plans[]` (each with `id`, `wave`, `autonomous`, `objective`, `files_modified`, `task_count`, `has_summary`), `waves` (map of wave number → plan IDs), `incomplete`, `has_checkpoints`.

**Filtering:** Skip plans where `has_summary: true`. If `--gaps-only`: also skip non-gap_closure plans. If `WAVE_FILTER` is set: also skip plans whose `wave` does not equal `WAVE_FILTER`.

**Wave safety check:** If `WAVE_FILTER` is set and there are still incomplete plans in any lower wave that match the current execution mode, STOP and tell the user to finish earlier waves first. Do not let Wave 2+ execute while prerequisite earlier-wave plans remain incomplete.

If all filtered: "No matching incomplete plans" → exit.

Report:
```
## Execution Plan

**Phase {X}: {Name}** — {total_plans} matching plans across {wave_count} wave(s)

{If WAVE_FILTER is set: `Wave filter active: executing only Wave {WAVE_FILTER}`.}

| Wave | Plans | What it builds |
|------|-------|----------------|
| 1 | 01-01, 01-02 | {from plan objectives, 3-8 words} |
| 2 | 01-03 | ... |
```

**Then render the glass, so the user SEES the shape of what is about to run:**

```bash
# Canonical resolver, see ferrox-core/references/ferrox-script-resolver.md.
# RUNTIME_DIR first, then the project tree, then the install root per runtime.
ferrox_script() { _n="$1"; _p="${RUNTIME_DIR:-$(git rev-parse --show-toplevel 2>/dev/null || pwd)}"; for _c in "${_p}/scripts/${_n}" "${_p}/.claude/scripts/${_n}" "${_p}/.codex/scripts/${_n}" "${CLAUDE_CONFIG_DIR:-$HOME/.claude}/scripts/${_n}" "${HERMES_HOME:-$HOME/.hermes}/scripts/${_n}" "${CURSOR_CONFIG_DIR:-$HOME/.cursor}/scripts/${_n}" "${CODEX_HOME:-$HOME/.codex}/scripts/${_n}" "${GEMINI_CONFIG_DIR:-$HOME/.gemini}/scripts/${_n}" "${COPILOT_CONFIG_DIR:-$HOME/.copilot}/scripts/${_n}" "${WINDSURF_CONFIG_DIR:-$HOME/.codeium/windsurf}/scripts/${_n}" "${AUGMENT_CONFIG_DIR:-$HOME/.augment}/scripts/${_n}" "${TRAE_CONFIG_DIR:-$HOME/.trae}/scripts/${_n}" "${QWEN_CONFIG_DIR:-$HOME/.qwen}/scripts/${_n}" "${CODEBUDDY_CONFIG_DIR:-$HOME/.codebuddy}/scripts/${_n}" "${CLINE_CONFIG_DIR:-$HOME/.cline}/scripts/${_n}" "${GROK_AGENTS_HOME:-$HOME/.agents}/scripts/${_n}" "${ANTIGRAVITY_CONFIG_DIR:-$HOME/.gemini/antigravity}/scripts/${_n}" "${OPENCODE_CONFIG_DIR:-${XDG_CONFIG_HOME:-$HOME/.config}/opencode}/scripts/${_n}" "${KILO_CONFIG_DIR:-${XDG_CONFIG_HOME:-$HOME/.config}/kilo}/scripts/${_n}"; do [ -f "$_c" ] && { printf '%s\n' "$_c"; return 0; }; done; printf '%s\n' "${_p}/scripts/${_n}"; return 1; }
GLASS=$(ferrox_script fleet-glass.cjs)
node "$GLASS" graph "${PHASE_NUMBER}" 2>/dev/null || true
```

Print its output verbatim. It is READ ONLY: it takes no lease, writes no file, and
changes nothing. It names the waves, the nodes, how many files are in each node's write
lane, the declared edges, and which of those edges the scan could not reach. **An edge
reported as unproven is the instrument reporting its own reach, never a defect count.**
Say that when you show it, rather than letting an audience read `unproven` as `broken`.

If the command fails or the phase has no readable graph, say so in 1 line and continue.
The glass is a view, and a view that cannot render is not a reason to refuse a run.
</step>

<step name="cross_ai_delegation">
**Optional step 2.5 — Delegate plans to an external AI runtime.**

This step runs after plan discovery and before normal wave execution. It identifies plans
that should be delegated to an external AI command and executes them via stdin-based prompt
delivery. Plans handled here are removed from the execute_waves plan list so the normal
executor skips them.

**Activation logic:**

1. If `CROSS_AI_DISABLED` is true (`--no-cross-ai` flag): skip this step entirely.
2. If `CROSS_AI_FORCE` is true (`--cross-ai` flag): mark ALL incomplete plans for cross-AI execution.
3. Otherwise: check each plan's frontmatter for `cross_ai: true` AND verify config
   `workflow.cross_ai_execution` is `true`. Plans matching both conditions are marked for cross-AI.

```bash
CROSS_AI_ENABLED=$(ferrox_run query config-get workflow.cross_ai_execution 2>/dev/null || echo "false")
CROSS_AI_CMD=$(ferrox_run query config-get workflow.cross_ai_command 2>/dev/null || echo "")
CROSS_AI_TIMEOUT=$(ferrox_run query config-get workflow.cross_ai_timeout 2>/dev/null || echo "300")
```

**If no plans are marked for cross-AI:** Skip to execute_waves.

**If plans are marked but `cross_ai_command` is empty:** Error — tell user to set
`workflow.cross_ai_command` via `ferrox-tools.cjs query config-set workflow.cross_ai_command "<command>"`.

**For each cross-AI plan (sequentially):**

1. **Construct the task prompt** from the plan file:
   - Extract `<objective>` and `<tasks>` sections from the PLAN.md
   - Append PROJECT.md context (project name, description, tech stack)
   - Format as a self-contained execution prompt

2. **Check for dirty working tree before execution:**
   ```bash
   if ! git diff --quiet HEAD 2>/dev/null; then
     echo "WARNING: dirty working tree detected — the external AI command may produce uncommitted changes that conflict with existing modifications"
   fi
   ```

3. **Run the external command** from the project root, writing the prompt to stdin.
   Never shell-interpolate the prompt — always pipe via stdin to prevent injection:
   ```bash
   echo "$TASK_PROMPT" | timeout "${CROSS_AI_TIMEOUT}s" ${CROSS_AI_CMD} > "$CANDIDATE_SUMMARY" 2>"$ERROR_LOG"
   EXIT_CODE=$?
   ```

4. **Evaluate the result:**

   **Success (exit 0 + valid summary):**
   - Read `$CANDIDATE_SUMMARY` and validate it contains meaningful content
     (not empty, has at least a heading and description — a valid SUMMARY.md structure)
   - Write it as the plan's SUMMARY.md file
   - Update STATE.md plan status to complete
   - Update ROADMAP.md progress
   - Mark plan as handled — skip it in execute_waves

   **Failure (non-zero exit or invalid summary):**
   - Display the error output and exit code
   - Warn: "The external command may have left uncommitted changes or partial edits
     in the working tree. Review `git status` and `git diff` before proceeding."
   - Offer three choices:
     - **retry** — run the same plan through cross-AI again
     - **skip** — fall back to normal executor for this plan (re-add to execute_waves list)
     - **abort** — stop execution entirely, preserve state for resume

5. **After all cross-AI plans processed:** Remove successfully handled plans from the
   incomplete plan list so execute_waves skips them. Any skipped-to-fallback plans remain
   in the list for normal executor processing.
</step>

<step name="execute_waves">
Execute each selected wave in sequence. Within a wave: parallel if `PARALLELIZATION=true`, sequential if `false`.

**Orchestrator cwd-drift guard (FIRST ACTION at execute_waves entry — #48):**

A prior `Agent(isolation="worktree")` dispatch can silently leave the orchestrator's
cwd inside an agent worktree (or a subdirectory of one). Every subsequent
orchestrator-side git call would then target the wrong tree — this is how a wrong-base
merge nearly shipped ~1000 files. Resolve the *worktree root* (so a subdirectory cwd
cannot skew the check) and refuse if it is an agent worktree. The discriminator is the
per-agent branch namespace `worktree-agent-*`, NOT the `.claude/worktrees/` path: the
orchestrator may itself be legitimately invoked from a feature worktree under
`.claude/worktrees/`, so a path-substring refusal would break legitimate runs. Do NOT
pin to `git worktree list`'s first entry — that is the main worktree, the wrong target
when the orchestrator legitimately runs from a feature worktree.

```bash
ORCHESTRATOR_WT=$(git rev-parse --show-toplevel 2>/dev/null) || {
  echo "FATAL: execute_waves entry is not inside a git worktree (#48)." >&2; exit 1; }
ORCH_BRANCH=$(git rev-parse --abbrev-ref HEAD 2>/dev/null)
if printf '%s' "$ORCH_BRANCH" | grep -Eq '^worktree-agent-'; then
  echo "FATAL: orchestrator cwd is inside an agent worktree (branch '$ORCH_BRANCH', root '$ORCHESTRATOR_WT') — refusing to execute waves (#48). A prior isolation=\"worktree\" dispatch drifted the cwd; re-run from the orchestrator's own worktree." >&2
  exit 1
fi
# Pin to the worktree root; each later orchestrator-side block re-pins the same way
# (see the #3174 cleanup guard). Treat $ORCHESTRATOR_WT as the canonical root for the
# rest of the phase — prefer `git -C "$ORCHESTRATOR_WT"` for cross-step git calls,
# since a bare `cd` does not persist across separate tool invocations.
export ORCHESTRATOR_WT
cd "$ORCHESTRATOR_WT" || { echo "FATAL: cannot cd to orchestrator worktree '$ORCHESTRATOR_WT' (#48)." >&2; exit 1; }
```

**Stream-idle-timeout prevention — checkpoint heartbeats (#2410):**

Multi-plan phases can accumulate enough subagent context that the Claude API
SSE layer terminates with `Stream idle timeout - partial response received`
between a large tool_result and the next assistant turn (seen on Claude Code
+ Opus 4.7 at ~200K+ cache_read). To keep the stream warm, emit short
assistant-text heartbeats — **no tool call, just a literal line** — at every
wave and plan boundary. Each heartbeat MUST start with `[checkpoint]` so
tooling and `/ferrox:manager`'s background-completion handler can grep partial
transcripts. `{P}/{Q}` is the phase-wide completed/total plans counter and
increases monotonically across waves. `{status}` is `complete` (success),
`failed` (executor error), or `checkpoint` (human-gate returned).

```
[checkpoint] phase {PHASE_NUMBER} wave {N}/{M} starting, {wave_plan_count} plan(s), {P}/{Q} plans done
[checkpoint] phase {PHASE_NUMBER} wave {N}/{M} plan {plan_id} starting ({P}/{Q} plans done)
[checkpoint] phase {PHASE_NUMBER} wave {N}/{M} plan {plan_id} {status} ({P}/{Q} plans done)
[checkpoint] phase {PHASE_NUMBER} wave {N}/{M} complete, {P}/{Q} plans done ({wave_success}/{wave_plan_count} ok)
```

**For each wave:**

@~/.claude/ferrox-core/references/execute-phase-wave-guard.md

@~/.claude/ferrox-core/references/execute-phase-context-guard.md

**Wave boundary glass (BEFORE the overlap check below):**

```bash
node "$GLASS" graph "${PHASE_NUMBER}" 2>/dev/null || true
```

Render it again at each wave boundary and print the output verbatim. The same read only
view, re-read: a node that landed since the last wave changes what the graph says, and a
boundary is exactly where a person wants to see the remaining shape rather than recall it.
If it fails, say so in 1 line and continue.

1. **Intra-wave files_modified overlap check (BEFORE spawning):**

   Before spawning any agents for this wave, inspect the `files_modified` list of all plans
   in the wave. Check every pair of plans in the wave — if any two plans share even one file
   in their `files_modified` lists, those plans have an implicit dependency and MUST NOT run
   in parallel.

   **Detection algorithm (pseudocode):**
   ```
   seen_files = {}
   overlapping_plans = []
   for each plan in wave_plans:
     for each file in plan.files_modified:
       if file in seen_files:
         overlapping_plans.add(plan, seen_files[file])  # both plans overlap on this file
       else:
         seen_files[file] = plan
   ```

   **If overlap is detected:**
   - Warn the user:
     ```
     ⚠ Intra-wave files_modified overlap detected in Wave {N}:
       Plan {A} and Plan {B} both modify {file}
       Running these plans sequentially to avoid parallel worktree conflicts.
     ```
   - Override `PARALLELIZATION` to `false` for this wave only — run all plans in the wave
     sequentially regardless of the global parallelization setting.
   - This is a safety net for plans that were incorrectly assigned to the same wave.
     The planner should have caught this; flag it as a planning defect so the user can
     replan the phase if desired.

   **If no overlap:** proceed normally (parallel if `PARALLELIZATION=true`).

1b. **Coordination consult (BEFORE spawning — locked decision 4):**

   The overlap check above is a files-intersection heuristic. The authoritative
   coordination protocol lives in the five coord verbs documented in
   [coordination.md](../references/coordination.md) — the single source of truth for
   the coordination model. Consult them, do not restate their logic inline:

   - **Hot-seam serialization — consult `coord.hot-seam-check` before this wave
     parallelizes.** Any plan that touches a registered hot seam (a shared-write
     surface such as `STATE.md`, `ROADMAP.md`, `BACKLOG.md`, or a migration
     sequence) MUST run serial regardless of its wave assignment:

     ```bash
     ferrox_run query coord.hot-seam-check --files "$(printf '%s,' "${WAVE_FILES[@]}")"
     ```

     If the decision is `serialize-global`, force `PARALLELIZATION=false` for this
     wave — a hot-seam plan runs serial even when the files-overlap heuristic found
     no pairwise conflict.

   - **Migration/sequence allocation — never self-assign in a worktree.** For any
     plan that needs a migration or monotonic sequence number, allocate it through
     `coord.alloc-migration` rather than letting a parallel worktree pick its own
     (which would collide):

     ```bash
     ferrox_run query coord.alloc-migration        # returns { "number": <n> }
     ferrox_run query coord.check-migration --number <n>   # validates it is the expected next
     ```

   These consults are documented **protocol** this phase, not yet un-bypassable
   runtime enforcement — see the mechanism-vs-protocol note in coordination.md
   (the fail-closed strength-gate is Phase-5 / FF-B10). The greppable
   `ferrox_run query coord.*` citations make the required consult inspectable.

2. **Describe what's being built (BEFORE spawning):**

   **First, emit the wave-start checkpoint heartbeat as a literal assistant-text
   line — no tool call (#2410). Do NOT skip this even for single-plan waves; it
   is required before any further reasoning or spawning:**

   ```
   [checkpoint] phase {PHASE_NUMBER} wave {N}/{M} starting, {wave_plan_count} plan(s), {P}/{Q} plans done
   ```

   Then read each plan's `<objective>`. Extract what's being built and why.

   ```
   ---
   ## Wave {N}

   **{Plan ID}: {Plan Name}**
   {2-3 sentences: what this builds, technical approach, why it matters}

   Spawning {count} agent(s)... (runs in a subagent — no output until it returns, ~1–5 min; expected, not a freeze)
   ---
   ```

   - Bad: "Executing terrain generation plan"
   - Good: "Procedural terrain generator using Perlin noise — creates height maps, biome zones, and collision meshes. Required before vehicle physics can interact with ground."

2.5. **Per-plan worktree decision (run for each plan in this wave BEFORE its dispatch):**

   Read and execute `ferrox-core/workflows/execute-phase/steps/per-plan-worktree-gate.md` for each plan. It extracts `PLAN_FILES` from the plan's JSON, intersects against `SUBMODULE_PATHS` (with normalization, bidirectional matching, and glob-prefix handling), and sets `USE_WORKTREES_FOR_PLAN` to `false` when the plan touches a submodule path. Append `plan_id` to a `WAVE_WORKTREE_PLANS` accumulator when `USE_WORKTREES_FOR_PLAN != false`.

   The dispatch branches in step 3 below MUST gate on `USE_WORKTREES_FOR_PLAN` for the current plan, not on the project-level `USE_WORKTREES`.

2.6. **Role-stamp dispatch preflight (v1.13 P2 W3; run for each plan in this wave BEFORE its dispatch):**

   Read the 3 team stamp keys from the plan frontmatter: `role_id`, `role_charter`,
   `team_manifest_hash`. All 3 absent: set `ROLE_ASSIGNED=false`, skip this whole step,
   zero behavior change (A9). Any subset present without the other 2 is a partial stamp
   (plan-checker Check T5 territory): STOP and route the plan back to plan-phase rather
   than dispatch on a half stamp.

   **A2 dispatch re-validation: the stamp must match the LIVE `.planning/TEAM.md` at
   dispatch time,** not only at plan-check time; a roster mutation between stamping and
   dispatch makes the stamp stale. The deterministic contract is
   `ferrox-core/bin/lib/team-manifest.cjs` (exports `parseTeamManifest`,
   `verifyTeamManifestHash`, `computeTeamManifestHash`):

   ```bash
   TEAM_LIB=""; for _tl in "${FERROX_TOOLS%/*}/lib/team-manifest.cjs" "$HOME/.claude/ferrox-core/bin/lib/team-manifest.cjs" "./.claude/ferrox-core/bin/lib/team-manifest.cjs" "./ferrox-core/bin/lib/team-manifest.cjs"; do if [ -f "$_tl" ]; then TEAM_LIB="$_tl"; break; fi; done
   if [ -z "$TEAM_LIB" ]; then echo "ERROR: team-manifest.cjs not found; tried: ${FERROX_TOOLS%/*}/lib/team-manifest.cjs, $HOME/.claude/ferrox-core/bin/lib/team-manifest.cjs, ./.claude/ferrox-core/bin/lib/team-manifest.cjs, ./ferrox-core/bin/lib/team-manifest.cjs" >&2; exit 1; fi
   # STAMPED_HASH, ROLE_ID, and STAMPED_CHARTER come from this plan frontmatter
   # (team_manifest_hash, role_id, role_charter).
   ROLE_CHECK=$(node -e '
   const fs = require("node:fs");
   const tm = require(process.argv[1]);
   const path = require("node:path");
   // A10: inject the known-agent roster from the model catalog beside the lib,
   // so W_UNKNOWN_AGENT is live and "bound" counts only real agents; a missing
   // catalog degrades to no roster check (the prior behavior).
   let agents;
   try { agents = Object.keys(require(path.join(path.dirname(process.argv[1]), "model-catalog.cjs")).AGENT_DEFAULT_TIERS); } catch { agents = undefined; }
   const stampedHash = process.argv[2];
   const roleId = process.argv[3];
   const stampedCharter = process.argv[4];
   let md = null;
   try { md = fs.readFileSync(".planning/TEAM.md", "utf8"); } catch { /* absent */ }
   if (md === null) { console.log(JSON.stringify({ verdict: "degrade", reason: "team-md-absent" })); process.exit(0); }
   const parsed = tm.parseTeamManifest(md, agents === undefined ? undefined : { agents });
   if (!parsed.ok) { console.log(JSON.stringify({ verdict: "stop", reason: "team-md-invalid", errors: parsed.errors })); process.exit(0); }
   const self = tm.verifyTeamManifestHash(parsed.manifest);
   const live = tm.computeTeamManifestHash(parsed.manifest);
   if (!self.ok || live !== stampedHash) { console.log(JSON.stringify({ verdict: "stop", reason: "stale-stamp", stamped_hash: stampedHash, live_hash: live })); process.exit(0); }
   const seat = parsed.manifest.roles.find((r) => r.id === roleId);
   if (seat === undefined) { console.log(JSON.stringify({ verdict: "degrade", reason: "role-missing" })); process.exit(0); }
   if (seat.charter !== stampedCharter) { console.log(JSON.stringify({ verdict: "stop", reason: "charter-drift", role_id: roleId })); process.exit(0); }
   console.log(JSON.stringify({ verdict: "role", tier: seat.tier, binding: seat.binding, charter: seat.charter }));
   ' "$TEAM_LIB" "$STAMPED_HASH" "$ROLE_ID" "$STAMPED_CHARTER")
   ```

   Handle the verdict:

   - **`stop` with `stale-stamp`:** STOP. Do NOT dispatch this plan. This mirrors
     plan-checker Check T3 exactly, with the same NAMED fix: **re-stamp** the plans
     against the live TEAM.md (the roster is right, the stamps are old) or **re-bless**
     the roster (the roster drifted without a blessing). Never dispatch on a stale stamp,
     and never silently strip the stamp to force a dispatch.
   - **`stop` with `charter-drift`:** STOP. Do NOT dispatch this plan. The plan's inlined
     `role_charter` stamp is no longer byte-identical to the live TEAM.md charter for
     that role. This mirrors plan-checker Check T2 exactly, with the same NAMED fix:
     **re-stamp** the plan's charter from the blessed TEAM.md (the roster is right, the
     stamp drifted) or **re-bless** the roster (the charter changed without a blessing).
     Never dispatch a drifted charter, and never patch the stamp inline to force a
     dispatch.
   - **`stop` with `team-md-invalid`:** STOP and surface the parser errors verbatim. The
     manifest is repaired through the governed `team-manifest.cjs` mutation ops, never by
     hand, before any staffed dispatch.
   - **`degrade` (A8; the stamped role is absent from the live roster, or TEAM.md itself
     is gone):** dispatch ROLELESS, loudly. Set `ROLE_ASSIGNED=false`, drop the
     `<role_assignment>` block from the prompt, and print this receipt line VERBATIM
     (with the plan's role id substituted for `<id>`) in the wave log AND record it in
     the step 6 wave report beside the plan:

     ```
     ROLE DEGRADE: role '<id>' absent from live TEAM.md; dispatched roleless
     ```

     A silent degrade is forbidden: the stamp promised a seat, and the wave record must
     say the seat was gone.
   - **`role`:** set `ROLE_ASSIGNED=true` and inject the `<role_assignment>` block in the
     dispatch prompt below (step 3).

   **Role tier resolution (A7 + A10 + A13):**

   - Agent-bound role (`binding.agent`) with NO explicit `tier`: the model resolves via
     the catalog default, exactly as an unstaffed dispatch of this plan would (the
     `executor_model` from init through the FAST-05 depth tiering above). No new
     resolution path.
   - Role with an explicit `tier` (either binding rung): resolve through the FF-B26 verb,
     the same 1 seam as FAST-05: `ferrox_run query model.resolve-tier --tier "<tier>"`.
     On a ladder miss (A10) the verb returns `modelId: null` plus a `NOT IN LADDER`
     notice: SURFACE the notice verbatim in the wave log, add this receipt line beside
     the plan in the step 6 wave report, and dispatch on the default executor model.
     Never a silently null model id:

     ```
     TIER LADDER MISS: role '<id>' tier '<tier>' not in model.tier_models; dispatched on the default executor model
     ```
   - `FORCE_FRONTIER` still wins over any role tier: a boundary plan can never be routed
     down by a role (the FAST-05 precedence above is unchanged).

   **Dispatch is ALWAYS ferrox-executor (A7).** The role binding is metadata (a tier
   default plus provenance), NEVER a `subagent_type` swap: an agent-bound role and an
   inline-charter role BOTH dispatch `subagent_type="ferrox-executor"`. The injected
   charter is the blessed TEAM.md charter text on both rungs; the A2 check above proved
   the plan stamp byte-identical to it, so the stamp is injected as stamped.

   **TEAM.md mutation stale-stamp sweep (A2/A8).** Whenever the roster mutates (add,
   remove, swap through the governed `team-manifest.cjs` mutation ops, or any re-bless),
   run this sweep BEFORE the next staffed dispatch: every role stamp in
   `.planning/phases/*/*-PLAN.md` whose `team_manifest_hash` no longer matches the live
   manifest is STALE and is NAMED for re-stamp. A documented deterministic procedure, not
   a new module:

   ```bash
   TEAM_LIB=""; for _tl in "${FERROX_TOOLS%/*}/lib/team-manifest.cjs" "$HOME/.claude/ferrox-core/bin/lib/team-manifest.cjs" "./.claude/ferrox-core/bin/lib/team-manifest.cjs" "./ferrox-core/bin/lib/team-manifest.cjs"; do if [ -f "$_tl" ]; then TEAM_LIB="$_tl"; break; fi; done
   if [ -z "$TEAM_LIB" ]; then echo "ERROR: team-manifest.cjs not found; tried: ${FERROX_TOOLS%/*}/lib/team-manifest.cjs, $HOME/.claude/ferrox-core/bin/lib/team-manifest.cjs, ./.claude/ferrox-core/bin/lib/team-manifest.cjs, ./ferrox-core/bin/lib/team-manifest.cjs" >&2; exit 1; fi
   node -e '
   const fs = require("node:fs");
   const path = require("node:path");
   const tm = require(process.argv[1]);
   const parsed = tm.parseTeamManifest(fs.readFileSync(".planning/TEAM.md", "utf8"));
   if (!parsed.ok) { console.error("stale-stamp sweep: TEAM.md does not parse; repair the manifest first"); process.exit(1); }
   const live = tm.computeTeamManifestHash(parsed.manifest);
   const stale = [];
   const root = ".planning/phases";
   for (const entry of fs.existsSync(root) ? fs.readdirSync(root, { withFileTypes: true }) : []) {
     if (!entry.isDirectory()) continue;
     const dir = path.join(root, entry.name);
     for (const f of fs.readdirSync(dir)) {
       if (!f.endsWith("-PLAN.md")) continue;
       // Only the frontmatter block carries a stamp: a hash-shaped line in the
       // plan BODY (prose, examples, quoted receipts) must never flag.
       const fm = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(fs.readFileSync(path.join(dir, f), "utf8"));
       const m = fm === null ? null : /^team_manifest_hash:\s*"?([0-9a-f]{64})"?\s*$/m.exec(fm[1]);
       if (m !== null && m[1] !== live) stale.push(path.join(dir, f));
     }
   }
   if (stale.length === 0) { console.log("stale-stamp sweep: 0 stale role stamps against live TEAM.md " + live.slice(0, 12)); process.exit(0); }
   console.log("stale-stamp sweep: " + stale.length + " stale role stamp(s); re-stamp each against the live TEAM.md (or re-bless the roster):");
   for (const p of stale) console.log("  STALE STAMP: " + p);
   process.exit(1);
   ' "$TEAM_LIB"
   ```

   Exit 1 with named files means those plans re-enter plan-phase for a re-stamp before
   they can dispatch; the sweep never edits a plan itself.

3. **Spawn executor agents:**

   **Emit a plan-start heartbeat (literal line, no tool call) immediately before
   each `Agent()` dispatch (#2410):**

   `[checkpoint] phase {PHASE_NUMBER} wave {N}/{M} plan {plan_id} starting ({P}/{Q} plans done)`

   Pass paths only — executors read files themselves with their fresh context window.
   For 200k models, this keeps orchestrator context lean (~10-15%).
   For 1M+ models (Opus 4.6, Sonnet 4.6), richer context can be passed directly.

   **Worktree mode** (`USE_WORKTREES_FOR_PLAN` is not `false` — evaluated per-plan in step 2.5):

   Before spawning, capture the current HEAD:
   ```bash
   EXPECTED_BASE=$(git rev-parse HEAD)
   DISPATCH_TS=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
   EXPECTED_BRANCH=$(git rev-parse --abbrev-ref HEAD)
   if [ "${USE_WORKTREES_FOR_PLAN:-true}" != "false" ] && [ -z "${WAVE_WORKTREE_MANIFEST:-}" ]; then
     M=$(mktemp "${TMPDIR:-/tmp}/ferrox-worktree-wave-XXXXXX") && mv "$M" "$M.json" && WAVE_WORKTREE_MANIFEST="$M.json" || exit 1  # XXXXXX must be path-final on BSD/macOS (#1520)
     # Persist the dispatch-time orchestrator worktree root so wave-cleanup can pin back to the
     # orchestrator's OWN worktree — NOT `git worktree list`'s first entry (always the main
     # checkout), which pins a non-primary (per-phase lane) orchestrator off its branch (#630).
     # Dispatch runs from the orchestrator's lane, so show-toplevel here is the correct root.
     ORCH_ROOT=$(git rev-parse --show-toplevel)
     ORCH_ROOT="$ORCH_ROOT" MANIFEST="$WAVE_WORKTREE_MANIFEST" node -e 'const fs=require("fs");fs.writeFileSync(process.env.MANIFEST,JSON.stringify({orchestrator_root:process.env.ORCH_ROOT||null,worktrees:[]})+"\n")'
     export WAVE_WORKTREE_MANIFEST
   fi
   ```

   **Sequential dispatch for parallel execution (waves with 2+ agents):**
   Dispatch each `Agent()` call **one at a time with `run_in_background: true`**. Do NOT
   send all Agent calls in a single message: simultaneous `git worktree add` calls race
   on `.git/config.lock`. Agents still run in parallel once their worktrees are created.

   ```text
   # CORRECT: one Agent() per message with run_in_background: true
   # WRONG: multiple Agent() calls in one message -> .git/config.lock contention
   ```

   ```text
   Agent(
     subagent_type="ferrox-executor",
     description="Execute plan {plan_number} of phase {phase_number}",
     # Only include model= when executor_model is an explicit model name.
     # When executor_model is "inherit", omit this parameter entirely so
     # Claude Code inherits the orchestrator model automatically.
     model="{executor_model}",  # omit this line when executor_model == "inherit"
     isolation="worktree",
     prompt="
       <objective>
       Execute plan {plan_number} of phase {phase_number}-{phase_name}.
       Commit each task atomically. Create SUMMARY.md.
       Do NOT update STATE.md or ROADMAP.md — the orchestrator owns those writes after all worktree agents in the wave complete.
       </objective>

       <worktree_branch_check>
       ORCHESTRATOR build-time embed (NOT a sub-agent runtime step): before this dispatch, read `ferrox-core/references/worktree-branch-check.md`, substitute `{EXPECTED_BASE}` with the base SHA captured above ({EXPECTED_BASE}), and replace this note with that fragment's `<worktree_branch_check>` block so the dispatched prompt carries the runnable guard verbatim — do not pass this instruction through in its place.
       Per-commit HEAD/cwd-drift/path-guard: `agents/ferrox-executor.md` steps 0/0a/0b + `references/worktree-path-safety.md` (in <execution_context>).
       </worktree_branch_check>

       <parallel_execution>
       You are running as a PARALLEL executor agent in a git worktree. Worktree path safety (cwd-drift, absolute-path guards) is in `worktree-path-safety.md` (loaded below).
       Run `git commit` normally — hooks run by default. Do NOT pass `--no-verify`
       unless the orchestrator surfaces `workflow.worktree_skip_hooks=true` in this
       prompt; silent bypass violates project CLAUDE.md guidance (#2924).

       IMPORTANT: Do NOT modify STATE.md or ROADMAP.md. execute-plan.md
       auto-detects worktree mode (`.git` is a file, not a directory) and skips
       shared file updates automatically. The orchestrator updates them centrally
       after merge.

       REQUIRED: SUMMARY.md MUST be committed before you return. In worktree mode the
       git_commit_metadata step in execute-plan.md commits SUMMARY.md and REQUIREMENTS.md
       only (STATE.md and ROADMAP.md are excluded automatically). Do NOT skip or defer
       this commit — the orchestrator force-removes the worktree after you return, and
       any uncommitted SUMMARY.md will be permanently lost (#2070).
       REQUIRED ORDER: Write SUMMARY.md → commit → only then any narration. No text between Write and commit (truncation risk; #2070 rescue is not primary defense).

       </parallel_execution>

       <execution_context>
       @~/.claude/ferrox-core/workflows/execute-plan.md
       @~/.claude/ferrox-core/templates/summary.md
       @~/.claude/ferrox-core/references/checkpoints.md
       ${NONCODE_DOMAIN ? '' : '@~/.claude/ferrox-core/references/tdd.md'}
       <!-- v1.13 Wave 0 (B5): NONCODE_DOMAIN is an ORCHESTRATOR build-time fact, true only
            when this plan's `domain` frontmatter (falling back to `.planning/config.json`
            `domain` when the plan omits it) normalizes per gate-select (lowercase, trim,
            spaces/underscores to hyphens, alias to canonical) to `writing`, `long-form`,
            or `research`. Non-code increments get NO tdd.md injection: RED/GREEN test
            discipline is a code instrument and a prose increment has no failing test to
            write. Every other domain gets tdd.md exactly as before. -->
       @~/.claude/ferrox-core/references/worktree-path-safety.md
       ${CONTEXT_WINDOW < 200000 ? '' : '@~/.claude/ferrox-core/references/executor-examples.md'}
       </execution_context>

       <files_to_read>
       Read these files at execution start using the Read tool.
       First resolve repo root so every path is anchored:
       \`PROJECT_ROOT=$(git rev-parse --show-toplevel 2>/dev/null)\`
       - ${PROJECT_ROOT}/{phase_dir}/{plan_file} (Plan)
       - ${PROJECT_ROOT}/.planning/PROJECT.md (Project context — core value, requirements, evolution rules)
       - ${PROJECT_ROOT}/.planning/STATE.md (State)
       - ${PROJECT_ROOT}/.planning/config.json (Config, if exists)
       ${NONCODE_DOMAIN ? `
       - ${PROJECT_ROOT}/LORE.md (Canon store: declared facts bind the draft; the fenced canon-facts YAML is authoritative, if exists)
       - ${PROJECT_ROOT}/SOURCES.md (Sources ledger: every claim traces to a ledger entry, if exists)
       - ${PROJECT_ROOT}/book/SPINE.md (Spine manifest: the single chapter ordering truth, if exists)
       ` : ''}
       ${CONTEXT_WINDOW >= 500000 ? `
       - ${PROJECT_ROOT}/${phase_dir}/*-CONTEXT.md (User decisions from discuss-phase — honors locked choices)
       - ${PROJECT_ROOT}/${phase_dir}/*-RESEARCH.md (Technical research — pitfalls and patterns to follow)
       - ${PROJECT_ROOT}/${prior_wave_summaries} (SUMMARY.md files from earlier waves in this phase — what was already built)
       ` : ''}
       - ${PROJECT_ROOT}/CLAUDE.md (Project instructions, if exists — follow project-specific guidelines and coding conventions)
       - ${PROJECT_ROOT}/.claude/skills/ or ${PROJECT_ROOT}/.agents/skills/ (Project skills, if either exists — list skills, read SKILL.md for each, follow relevant rules during implementation)
       </files_to_read>

       ${NONCODE_DOMAIN ? `
       <chapter_drafting>
       v1.13 Wave 2 (A1) book-domain drafting discipline: ferrox-chapter-drafter is the
       drafting agent for chapter tasks. Read agents/ferrox-chapter-drafter.md and hold
       every drafting task to its contract. The chapter contract below is PLANNER-AUTHORED and
       TRUSTED: the orchestrator copied it verbatim from the plan's frontmatter
       chapter_contract block, never from a draft. Do not invent, drop, or reinterpret its
       fields. The draft frontmatter must ECHO the contract exactly, self-declaring only
       additional_on_stage and optional ages.

       <chapter_contract>
       pov: {chapter_contract.pov}
       scene_date: {chapter_contract.scene_date}
       location: {chapter_contract.location}
       threads: {chapter_contract.threads}
       flashback: {chapter_contract.flashback}
       required_on_stage: {chapter_contract.required_on_stage}
       word_count_target: {chapter_contract.word_count_target}
       beats: {chapter_contract.beats}
       </chapter_contract>

       Research-domain plans carry no chapter contract: skip the block above and execute the
       plan's report-shaped tasks against the SOURCES.md ledger instead.
       </chapter_drafting>
       ` : ''}

       ${ROLE_ASSIGNED ? `
       <role_assignment>
       v1.13 P2 W3 (A7) team-staffed dispatch: ROLE_ASSIGNED is an ORCHESTRATOR build-time
       fact, true only when this plan frontmatter carries all 3 stamp keys (role_id +
       role_charter + team_manifest_hash) AND the step 2.6 preflight verdict was "role".
       The charter below is PLANNER-STAMPED and TRUSTED: the orchestrator copied it
       VERBATIM from the plan's role_charter frontmatter stamp (which the A2 preflight
       proved byte-identical to the blessed .planning/TEAM.md charter), never from any
       agent output. ECHO it, never author it: do not restate, extend, trim, or
       reinterpret the charter. Your SUMMARY.md frontmatter must echo role_id and
       role_charter byte for byte from the plan stamp; the verifier checks the echo and
       FAILS any difference.

       <role_charter>
       role_id: {role_id}
       {role_charter}
       </role_charter>
       </role_assignment>
       ` : ''}

       ${AGENT_SKILLS}

       <mcp_tools>
       If CLAUDE.md or project instructions reference MCP tools (e.g. jCodeMunch, context7,
       or other MCP servers), prefer those tools over Grep/Glob for code navigation when available.
       MCP tools often save significant tokens by providing structured code indexes.
       Check tool availability first — if MCP tools are not accessible, fall back to Grep/Glob.
       </mcp_tools>

       <success_criteria>
       - [ ] All tasks executed
       - [ ] Each task committed individually
       - [ ] SUMMARY.md created in plan directory
       - [ ] No modifications to shared orchestrator artifacts (the orchestrator handles all post-wave shared-file writes)
       </success_criteria>
     "
   )
   ```

   After each `Agent()` returns, parse executor-returned worktree metadata (`<worktree_metadata>`) before harness metadata, then record the `{agent_id, worktree_path, branch, expected_base}` entry with `ferrox_run query worktree.record-agent --manifest "$WAVE_WORKTREE_MANIFEST" --agent-id … --path … --branch … --base …`. The verb validates every field at write time using the same rules the `cleanup-wave` reader enforces (write-strict `--agent-id`), failing loudly with a non-zero exit and recovery hint rather than appending an under-populated entry the reader would later drop silently. On a non-zero exit or any missing field: stop and ask for recovery instead of scanning worktrees.

   > **Worktree recovery policy (#48 + #1292):** See `execute-phase/steps/worktree-recovery-policy.md` — FAIL-CLOSED rule for base/HEAD-namespace mismatches AND isolated-run fail-safe recovery.

   > **ORCHESTRATOR RULE — CODEX RUNTIME**: After calling Agent() above to spawn executor agent(s), stop working on this task immediately. Do not read more files, edit code, or run tests related to this task while the subagent is active. Wait for the subagent to return its result. This prevents duplicate work, conflicting edits, and wasted context. Only resume when the subagent result is available.

   **Sequential mode** (`USE_WORKTREES_FOR_PLAN` is `false` — either project-level `USE_WORKTREES=false`, or per-plan submodule intersection forced it false in step 2.5):

   Omit `isolation="worktree"` from the Agent call. Replace the `<parallel_execution>` block with:

   ```
       <sequential_execution>
       You are running as a SEQUENTIAL executor agent on the main working tree.
       Use normal git commits (with hooks). Do NOT use --no-verify.
       REQUIRED ORDER: Write SUMMARY.md → commit → only then any narration. No text between Write and commit (truncation risk; #2070 rescue is not primary defense).
       </sequential_execution>
   ```

   The sequential mode Agent prompt uses the same structure as worktree mode but with these differences in success_criteria — since there is only one agent writing at a time, there are no shared-file conflicts:

   ```
       <success_criteria>
       - [ ] All tasks executed
       - [ ] Each task committed individually
       - [ ] SUMMARY.md created in plan directory
       - [ ] STATE.md updated with position and decisions
       - [ ] ROADMAP.md updated with plan progress (via `roadmap update-plan-progress`)
       </success_criteria>
   ```

   When worktrees are disabled for a plan (per-plan or project-level), that plan's executor runs on the main working tree. If **any** plan in the current wave dropped to sequential mode, execute the affected plan(s) **one at a time** to avoid concurrent writes to the main working tree — plans in the same wave that retained worktree isolation can still run in parallel alongside the sequential ones, but two non-worktree plans in the same wave must serialize. When the project-level `USE_WORKTREES=false`, all plans in the wave serialize regardless of the `PARALLELIZATION` setting.

4. **Wait for all agents in wave to complete.**

   **Plan-complete heartbeat (#2410):** as each executor returns (or is verified
   via spot-check below), emit one line — `complete` advances `{P}`, `failed`
   and `checkpoint` do not but still warm the stream:

   ```
   [checkpoint] phase {PHASE_NUMBER} wave {N}/{M} plan {plan_id} complete ({P}/{Q} plans done)
   [checkpoint] phase {PHASE_NUMBER} wave {N}/{M} plan {plan_id} failed ({P}/{Q} plans done)
   [checkpoint] phase {PHASE_NUMBER} wave {N}/{M} plan {plan_id} checkpoint ({P}/{Q} plans done)
   ```

   **Ownership consult (AFTER each plan completes — locked decision 4):** as each
   executor returns, consult `coord.ownership-check` to confirm the plan wrote only
   the files it declared in its `files_modified` set. An **undeclared write is
   wave-invalidating** — a plan that touched a file it never declared has escaped
   its lane and the wave's parallelism assumption is void:

   ```bash
   ferrox_run query coord.ownership-check \
     --declared "$(printf '%s,' "${PLAN_DECLARED_FILES[@]}")" \
     --actual   "$(printf '%s,' "${PLAN_ACTUAL_FILES[@]}")" \
     --increment "{plan_id}"
   ```

   If the decision is `wave-invalidating` (an undeclared write was detected — the verb
   returns `ok` when the plan stayed in its lane), treat the wave as invalidated —
   surface it rather than merging silently. `coord.ownership-check`
   is the runtime backing for the one-writer-per-worktree guarantee (COORD-01); see
   [coordination.md](../references/coordination.md). Note this backing is verified by
   the ownership check and guard inspection, **not** by a live parallel worktree run —
   worktrees are DISABLED on this build (honest scope, per coordination.md).

   **Completion signal fallback (Copilot and runtimes where Agent() may not return):**

   If a spawned agent does not return a completion signal but appears to have finished
   its work, do NOT block indefinitely. Instead, verify completion via spot-checks:

   ```bash
   # For each plan in this wave, check if the executor finished:
   SUMMARY_EXISTS=$(test -f "{phase_dir}/{plan_number}-{plan_padded}-SUMMARY.md" && echo "true" || echo "false")
   COMMITS_FOUND=$(git log --oneline --all --grep="{phase_number}-{plan_padded}" --since="1 hour ago" | head -1)
   COMMITS_SINCE_DISPATCH=$(git log "${EXPECTED_BRANCH}" --since="${DISPATCH_TS}" --oneline | head -1)
   ```

   **If SUMMARY.md exists AND commits are found:** The agent completed successfully —
   treat as done and proceed to step 5. Log: `"✓ {Plan ID} completed (verified via spot-check — completion signal not received)"`

   **If SUMMARY.md does NOT exist after a reasonable wait:** The agent may still be
   running or may have failed silently. Check `git log --oneline -5` for recent
   activity. If commits are still appearing, wait longer. If no activity, report
   the plan as failed and route to the failure handler in step 6.

   **Configurable stall surveillance (#3212):** Every `${EXECUTOR_STALL_INTERVAL_MINUTES}`
   minutes while waiting, inspect `git log "${EXPECTED_BRANCH}" --since="${DISPATCH_TS}"`
   for activity. If no completion signal, no SUMMARY.md, and no expected-branch
   commits appear for `${EXECUTOR_STALL_THRESHOLD_MINUTES}` minutes, pause and
   ask for one recovery path: `continue waiting`, `kill and retry`, or
   `kill and switch to inline execution`.

   If the stalled executor ran in an isolated worktree, `kill and switch to inline execution` edits the primary checkout — see worktree recovery policy (`execute-phase/steps/worktree-recovery-policy.md`). Prefer `kill and retry` in a fresh worktree; inline execution requires explicit confirmation, never the default.

   **This fallback applies automatically to all runtimes.** Claude Code's Agent() normally
   returns synchronously, but the fallback ensures resilience if it doesn't.

5. **Post-wave hook validation (parallel mode only):** Hooks run on every executor commit by default (#2924); this post-wave run only fires when `workflow.worktree_skip_hooks=true` opted out of per-commit hooks:
   ```bash
   SKIP_HOOKS=$(ferrox_run query config-get workflow.worktree_skip_hooks 2>/dev/null || echo "false")
   if [ "$SKIP_HOOKS" = "true" ]; then
     # Stash uncommitted changes under a named ref so we always pop (bare `git stash` strands them on hook/script failure). #3542: `refs/stash` is shared across worktrees, so this helper runs ONLY in the orchestrator's main checkout after all wave worktrees have been merged + removed; executors are forbidden from running any `git stash` subcommand (see `<destructive_git_prohibition>` in `agents/ferrox-executor.md`).
     STASHED=false
     if (! git diff --quiet || ! git diff --cached --quiet) && git stash push -u -m "ferrox-post-wave-hook-$$" >/dev/null 2>&1; then STASHED=true; fi
     git hook run pre-commit 2>&1 || echo "⚠ Pre-commit hooks failed — review before continuing"
     [ "$STASHED" = "true" ] && (git stash pop >/dev/null 2>&1 || echo "⚠ Could not pop ferrox-post-wave-hook stash — recover manually")
   fi
   ```
   If hooks fail: report the failure and ask "Fix hook issues now?" or "Continue to next wave?"

5.5. **Worktree cleanup (when `isolation="worktree"` was used):**

   **Standard wave contract:** Each wave's worktrees merge to main via the templated path below before the next wave's worktrees fork. The cleanup loop runs once per wave at the end of the wave lifecycle. Worktrees created in wave N must be fully removed before wave N+1 forks new ones.

   **Cross-wave dependency deviation (supported execution mode):** When the orchestrator legitimately deviates from the standard wave model — for example, a phase with cross-wave plan dependencies that requires custom inter-worktree base-update merges (e.g., `merge: bring 09-01 + 09-02 into 09-03 base`) — the cleanup loop below is NOT automatically re-entered for those custom merges. The deviation path produces correct final history but bypasses this loop, leaving `worktree-agent-*` directories in place. Use the **cleanup-tail snippet** below to remove any residual worktrees after such a deviation.

   When executor agents ran in worktree isolation, their commits land on temporary branches in separate working trees. After the wave completes, merge these changes back and clean up:

   **Manifest source of truth (#3384):** Cleanup consumes the `WAVE_WORKTREE_MANIFEST` created and populated during executor dispatch in step 3. Do not recreate or truncate it here.

   Prefer the bounded helper, which validates branch identity, expected base, deletion
   diffs, merge result, and worktree removal before deleting the temporary branch.
   If the helper reports a blocked cleanup, resolve the reported manifest entry and
   rerun the same command. Do not fall back to broad worktree discovery.

   ```bash
   [ -n "${WAVE_WORKTREE_MANIFEST:-}" ] && [ -f "$WAVE_WORKTREE_MANIFEST" ] || {
     echo "BLOCKED: missing WAVE_WORKTREE_MANIFEST; refusing broad worktree cleanup (#3384)." >&2
     exit 1
   }

   # Guard: pin cleanup back to the orchestrator's OWN worktree and fail on branch drift (#3174, #630).
   # Resolve from the dispatch-time orchestrator root persisted in the manifest — NOT `git worktree
   # list`'s first entry, which is always the main checkout and would pin a non-primary (per-phase
   # lane) orchestrator off its own branch, tripping the #3174 assertion below (#630). Byte-identical
   # for a primary orchestrator (its root IS the first entry); the fallback covers pre-#630 manifests.
   PRIMARY_WT=$(MANIFEST="$WAVE_WORKTREE_MANIFEST" node -e 'const fs=require("fs");try{const j=JSON.parse(fs.readFileSync(process.env.MANIFEST,"utf8"));if(j&&j.orchestrator_root)process.stdout.write(String(j.orchestrator_root))}catch(e){}')
   [ -n "$PRIMARY_WT" ] || PRIMARY_WT=$(git worktree list --porcelain | awk '/^worktree /{print substr($0,10); exit}')
   if [ -z "$PRIMARY_WT" ]; then
     echo "FATAL: could not resolve orchestrator worktree before cleanup" >&2
     exit 1
   fi
   if [ -n "$PRIMARY_WT" ] && [ "$(pwd -P 2>/dev/null)" != "$(cd "$PRIMARY_WT" 2>/dev/null && pwd -P)" ]; then echo "⚠ Orchestrator CWD drifted to $(pwd) — pinning to $PRIMARY_WT before worktree cleanup (#3174)"; cd "$PRIMARY_WT" || { echo "FATAL: cannot cd to primary worktree $PRIMARY_WT" >&2; exit 1; }; fi
   ORCH_BRANCH=$(git rev-parse --abbrev-ref HEAD)
   [ -z "${EXPECTED_BRANCH:-}" ] || [ "$ORCH_BRANCH" = "$EXPECTED_BRANCH" ] || { echo "FATAL: orchestrator on '$ORCH_BRANCH' but expected '$EXPECTED_BRANCH' before worktree cleanup — refusing to merge (#3174-class drift)" >&2; exit 1; }

   # Fail closed: SDK refusal (safety guard #3174/#3384) must surface — do not swallow exit 1.
   ferrox_run query worktree.cleanup-wave --manifest "$WAVE_WORKTREE_MANIFEST" || exit 1
   ```

   **Cleanup-tail snippet (use after any wave whose merges did not flow through the templated path above):**

   If the orchestrator deviated from the standard wave merge path (e.g., custom inter-worktree base-update merges with `merge: bring …` style messages), run this snippet after the custom merges are complete. It reads only `WAVE_WORKTREE_MANIFEST`; do not discover unrelated `worktree-agent-*` worktrees.

   ```bash
   # Cleanup-tail: pin orchestrator CWD to its OWN worktree before cleanup-tail (#3174, #630).
   # Same fix as the templated path: resolve the dispatch-time orchestrator root from the manifest,
   # not `git worktree list`'s first entry (always the main checkout — wrong for a lane orchestrator).
   PRIMARY_WT=$(MANIFEST="$WAVE_WORKTREE_MANIFEST" node -e 'const fs=require("fs");try{const j=JSON.parse(fs.readFileSync(process.env.MANIFEST,"utf8"));if(j&&j.orchestrator_root)process.stdout.write(String(j.orchestrator_root))}catch(e){}')
   [ -n "$PRIMARY_WT" ] || PRIMARY_WT=$(git worktree list --porcelain | awk '/^worktree /{print substr($0,10); exit}')
   if [ -n "$PRIMARY_WT" ] && [ "$(pwd -P 2>/dev/null)" != "$(cd "$PRIMARY_WT" 2>/dev/null && pwd -P)" ]; then echo "⚠ Orchestrator CWD drifted to $(pwd) — pinning to $PRIMARY_WT before cleanup-tail (#3174)"; cd "$PRIMARY_WT" || { echo "FATAL: cannot cd to primary worktree $PRIMARY_WT" >&2; exit 1; }; fi
   # Cleanup-tail: remove residual agent worktrees after a cross-wave-dependency deviation.
   # Uses only the current wave manifest to avoid touching unrelated active agents (#3384).
   WT_PATHS_FILE=$(mktemp "${TMPDIR:-/tmp}/ferrox-worktree-paths-XXXXXX")
   node -e 'const fs=require("fs");const p=process.env.WAVE_WORKTREE_MANIFEST;try{if(!p)throw new Error("WAVE_WORKTREE_MANIFEST is unset");if(!fs.existsSync(p))throw new Error("manifest does not exist");const s=fs.readFileSync(p,"utf8");if(!s.trim())throw new Error("manifest is empty");const j=JSON.parse(s);for(const w of j.worktrees||[])if(w.worktree_path)console.log(w.worktree_path)}catch(e){console.error(`ERROR: cannot read worktree manifest ${p||"(unset)"}: ${e.message}`);process.exit(1)}' > "$WT_PATHS_FILE" || { echo "BLOCKED: cannot read WAVE_WORKTREE_MANIFEST; refusing cleanup (#3384)." >&2; exit 1; }
   while IFS= read -r WT; do
     [ -z "$WT" ] && continue
     WT_BRANCH=$(git -C "$WT" rev-parse --abbrev-ref HEAD 2>/dev/null)
     [ -z "$WT_BRANCH" ] || [ "$WT_BRANCH" = "HEAD" ] && continue
     echo "Cleaning up residual worktree: $WT (branch: $WT_BRANCH)"
     git worktree unlock "$WT" 2>/dev/null || true
     if ! git worktree remove "$WT" --force; then
       WT_NAME=$(basename "$WT")
       if [ -f ".git/worktrees/${WT_NAME}/locked" ]; then
         echo "⚠ Worktree $WT is locked — unlock failed; manual cleanup required:"
         echo "    git worktree unlock \"$WT\" && git worktree remove \"$WT\" --force && git branch -D \"$WT_BRANCH\""
       else
         echo "⚠ Residual worktree at $WT — remove failed; manual cleanup required"
       fi
     else
       git branch -D "$WT_BRANCH" 2>/dev/null || true
     fi
   done < "$WT_PATHS_FILE"
   git worktree prune
   ```

   **When to skip step 5.5:**

   **If no plan in this wave used worktree isolation** (project-level `USE_WORKTREES=false` OR every plan in the wave had `USE_WORKTREES_FOR_PLAN=false` — i.e. `WAVE_WORKTREE_PLANS` from step 2.5 is empty): all agents ran on the main working tree — skip this step entirely.

   **If the orchestrator merged via custom messages (cross-wave-dependency deviation):** the templated cleanup loop above was not triggered for those merges. Run the cleanup-tail snippet above instead. After the snippet completes, proceed to step 5.6.

   **If at least one plan used worktrees but others did not:** still run this cleanup — it iterates over actual `git worktree list` output and only merges back the worktrees that were created, leaving sequential plans' commits on the main tree untouched.

   **If no worktrees found at runtime:** Skip silently — agents may have been spawned without worktree isolation, or the orchestrator already cleaned them up.

   If the user declines to merge a worktree or a worktree over-reached scope, apply the worktree recovery policy (`execute-phase/steps/worktree-recovery-policy.md`) — never default to editing `main`.

5.6. **Post-merge build & test gate:**

   After merging all worktrees in a wave (parallel mode), or after the last plan completes
   (serial mode), run a build and then the project's test suite to catch cross-plan
   integration issues that individual worktree self-checks cannot detect (e.g., conflicting
   type definitions, removed exports, import changes, link errors).

   This addresses the Generator self-evaluation blind spot identified in Anthropic's
   harness engineering research: agents reliably report Self-Check: PASSED even when
   merging their work creates failures.

   Read and execute `ferrox-core/workflows/execute-phase/steps/post-merge-gate.md`.

5.7. **Post-wave shared artifact update (when at least one plan used worktrees, skip if tests failed):**

   When **any** executor agent in this wave ran with `isolation="worktree"`, that agent skipped STATE.md and ROADMAP.md updates to avoid last-merge-wins overwrites. The orchestrator is the single writer for these files. After worktrees are merged back, update shared artifacts once for every completed plan in the wave (worktree-mode plans **and** sequential plans that ran on the main tree but deferred to the orchestrator for tracking writes).

   **Only update tracking when tests passed (TEST_EXIT=0).**
   If tests failed or timed out, skip the tracking update — plans should
   not be marked as complete when integration tests are failing or inconclusive.

   ```bash
   # Guard: only update tracking if post-merge tests passed
   # Timeout (124) is treated as inconclusive — do NOT mark plans complete
   if [ "${TEST_EXIT}" -eq 0 ]; then
     # Update ROADMAP plan progress for each completed plan in this wave
     for plan_id in {completed_plan_ids}; do
       ferrox_run query roadmap.update-plan-progress "${PHASE_NUMBER}" "${plan_id}" "complete"
     done

     # Only commit tracking files if they actually changed
     if ! git diff --quiet .planning/ROADMAP.md .planning/STATE.md 2>/dev/null; then
       ferrox_run query commit "docs(phase-${PHASE_NUMBER}): update tracking after wave ${N}" --files .planning/ROADMAP.md .planning/STATE.md
     fi
   elif [ "${TEST_EXIT}" -eq 124 ]; then
     echo "⚠ Skipping tracking update — test suite timed out. Plans remain in-progress. Run tests manually to confirm."
   else
     echo "⚠ Skipping tracking update — post-merge tests failed (exit ${TEST_EXIT}). Plans remain in-progress until tests pass."
   fi
   ```

   Where `WAVE_PLAN_IDS` is the space-separated list of plan IDs that completed in this wave.

   **If no plan in this wave used worktrees** (project-level `USE_WORKTREES=false` OR `WAVE_WORKTREE_PLANS` is empty): sequential agents already updated STATE.md and ROADMAP.md themselves — skip this step.

5.75. **Execute:wave:post capability dispatch:**

   After worktree merge, post-merge tests, and tracking updates, dispatch capability hooks registered at `execute:wave:post`. The primary hook is the `ui.safety-gate` gate from the UI capability — it verifies that any frontend files changed in this wave conform to the UI-SPEC contract.

   ```bash
   WAVE_POST_HOOKS_JSON=$(ferrox_run loop render-hooks execute:wave:post --raw)
   ```

   Read the `activeHooks` array from `WAVE_POST_HOOKS_JSON` in-context (do NOT pipe through a shell parser).

   **If `activeHooks` is empty or absent:** Skip silently to step 5.8.

   **For each active entry where `kind == "gate"`** (process in array order), run the gate check — for a `predicate` gate (ADR-2008 / #2008) substitute `ferrox_run check predicate --predicate '<hook.check.predicate as JSON>' --phase-number "${PHASE_NUMBER}" --raw` for the `check.query` form:

   ```bash
   GATE_RESULT=$(ferrox_run check ${hook.check.query} "${PHASE_NUMBER}" --raw)
   CHECK_EXIT=$?
   ```

   **Step 1 — did the CHECK COMMAND itself succeed?**

   If the check command failed (non-zero `CHECK_EXIT`, empty output, or unparseable JSON):
   - `onError == "halt"` → treat as a fatal error: stop wave completion, do NOT proceed to step 5.8, and surface: `⚠ Gate check command failed ({hook.capId}): command error. Resolve before continuing.`
   - `onError == "skip"` → log a warning and continue to the next hook. Do NOT read `GATE_RESULT.block`.

   **Step 2 — read `GATE_RESULT.block` (boolean).** This step is only reached when the command succeeded.

   - **Blocking gate (`hook.blocking == true`) AND `GATE_RESULT.block == true`:** HALT — stop wave completion, do NOT proceed to step 5.8, and present:

     ```
     ⚠ Wave {N} blocked by capability gate ({hook.capId}): {GATE_RESULT.message}
     Resolve before continuing to next wave.
     ```

     This halt is **not** bypassed by `onError` — `onError` only covers command errors (step 1 above), not the gate's block decision.

   - **Non-blocking gate (`hook.blocking == false`):** never halts. If `GATE_RESULT.block` is `true` (or non-empty `message`), print `⚠ {hook.capId} advisory (wave {N}): {GATE_RESULT.message}`, then:
     - If `GATE_RESULT.spawn_mapper == true` OR `GATE_RESULT.directive == "auto-remap"`: spawn `ferrox-codebase-mapper` per `execute-phase/steps/codebase-drift-gate.md`; pass `--paths {GATE_RESULT.affected_paths}`. Continue regardless (wave NOT failed by remap failure).
     - Otherwise: continue after advisory.
     - If block `false` and no `message`: continue silently.

   - **Blocking gate (`hook.blocking == true`) AND `GATE_RESULT.block == false`:** continue silently.

   **When all active gates are processed without a blocking halt:** continue to step 5.8.

5.8. **Handle test gate failures (when `WAVE_FAILURE_COUNT > 0`):**

   ```
   ## ⚠ Post-Merge Test Failure (cumulative failures: ${WAVE_FAILURE_COUNT})

   Wave {N} worktrees merged successfully, but {M} tests fail after merge.
   This typically indicates conflicting changes across parallel plans
   (e.g., type definitions, shared imports, API contracts).

   Failed tests:
   {first 10 lines of failure output}

   Options:
   1. Fix now (recommended) — resolve conflicts before next wave
   2. Continue — failures may compound in subsequent waves
   ```

   Note: If `WAVE_FAILURE_COUNT > 1`, strongly recommend "Fix now" — compounding
   failures across multiple waves become exponentially harder to diagnose.

   If "Fix now": diagnose failures (typically import conflicts, missing types,
   or changed function signatures from parallel plans modifying the same module).
   Fix, commit as `fix: resolve post-merge conflicts from wave {N}`, re-run tests.

   **Why this matters:** Worktree isolation means each agent's Self-Check passes
   in isolation. But when merged, add/add conflicts in shared files (models, registries,
   CLI entry points) can silently drop code. The post-merge gate catches this before
   the next wave builds on a broken foundation.

5.9. **Non-code floor gates (`NONCODE_DOMAIN` waves only; v1.13 Wave 3, the ui-phase 9.7 idiom):**

   Skip this step entirely when `NONCODE_DOMAIN` is false. Otherwise the orchestrator runs
   the domain's mechanical floor gate on every artifact this wave landed, BEFORE reporting
   the wave complete. Capture RAW STDOUT per artifact. Do NOT route the handoff through
   gateRunner.runGate: parseGateOutput consumes only the FAIL lines plus the summary and
   drops INDET, WARN, verdict, and hash lines by design; the raw stdout is the only surface
   that carries them.

   **Chapter path (book domain: every plan in this wave that carries a `chapter_contract`).**
   For each chapter draft the wave landed, the ORCHESTRATOR builds the gate bundle to a temp
   path and runs the lore-consistency pack (input contract: `gates/lore-consistency/card.md`):

   ```bash
   BUNDLE=$(mktemp -t lore-bundle-XXXXXX).json
   # Bundle members, trusted side built by the orchestrator, never by the draft:
   #   schema           "ferrox.lore-consistency.bundle/1"
   #   chapter          { filename: "ch-<slug>.md", markdown: <the landed draft, verbatim> }
   #   lore             the full LORE.md content
   #   trusted_contract copied VERBATIM from the plan's chapter_contract frontmatter block
   #                    (pov, scene_date or scene_date_window, location, threads, flashback,
   #                    required_on_stage, word_count_target, beats); never read from a draft
   #   prior_state      { previous_scene_date, chapters, thread_events } from the keeper's
   #                    chapter/thread event ledger and the spine manifest
   #   thresholds       { word_tolerance_pct: 10 } plus era bounds when the canon declares them
   LORE_GATE_OUT=$(node gates/lore-consistency/gate.cjs "${BUNDLE}" 2>&1)
   ```

   Then split the raw stdout 3 ways:

   - `FAIL <LC-id> <category>` lines: declared-fact contract violations. Route to the A2 fix
     lane: re-dispatch ferrox-chapter-drafter in revision mode with the FAIL lines as revision
     context, max 2 passes, then stop honestly and surface the remaining FAILs to the user.
     Never hand a FAIL to the line-editor; style findings only live there.
   - `INDET <LC-id> <reason-code>` lines: the gate refused to guess. Carry them verbatim into
     the continuity-eyes cross-audit below as named judgment items in the book eye's
     `<gate_indet_items>` block; record them in the wave summary as well.
   - `WARN ...` advisory lines (near-miss spelling, unlisted entities): display with the count,
     never block.

   Record the receipt in the wave summary verbatim: the `LORE GATE:` verdict line, the 1-line
   scope disclaimer, and the `canon_facts_hash:` line (amendment A3; a keeper retcon voids
   receipts recorded under a different hash).

   **Keeper ingest is SERIAL and between waves (amendment A5):** after every chapter in the
   wave passes the floor (or its FAILs are resolved), run the lore-keeper ingest ONCE for the
   whole wave, serially, before the next wave dispatches. Parallel chapter waves are legal only
   for timeline-independent chapters the plan names as such.

   **Research path (research or long-form domain: report-shaped artifacts).** For each report
   artifact the wave landed, run the citation-sources pack against the project ledger:

   ```bash
   CIT_GATE_OUT=$(node gates/citation-sources/gate.cjs --ledger "${PROJECT_ROOT}/SOURCES.md" "${report}" 2>&1)
   ```

   Same 3-way split of the raw stdout: `FAIL <CS-id> <category>` lines route to a capped
   executor revision pass (max 2, then stop honestly); `INDET CS-03 <reason>` lines are the
   quote-alteration judgment slice, carry them verbatim to the research judgment eye
   (ferrox-method-reviewer) below in its `<gate_indet_items>` block;
   `WARN CS-06 unused-source <id>` lines are advisory, display and move on. The gate never
   touches the network; live link checking stays a workflow-layer advisory and is NOT run here.

   **Continuity eyes cross-audit (v1.13 Wave 4; the ui-phase 9.7 idiom transposed).**
   The floor gates above are mechanical; the eyes own exactly the judgment slices the gates
   refuse. No rule is owned by 2 tiers: everything a gate scored stays with the gate, and the
   eyes receive only the INDET and WARN lines plus the artifacts. Prose quality is NOT an eye
   here; it stays Crucible-routed by the universal gate-first routing consult (UGE-08) per
   doctrine. The cross-audit owns facts (book) and method (research), never taste.

   The eyes are independent, so fire every eye this wave needs in a SINGLE message and wait;
   wall clock is the slower eye, not the sum. Do no other work while they run. A wave that
   landed both chapter and report artifacts fires 2 parallel dispatches; a single-lane wave
   fires 1.

   **Book eye (chapter artifacts landed this wave):**

   ```
   Agent(
     prompt="Read ~/.claude/agents/ferrox-continuity-checker.md for instructions.

     <objective>Cross-chapter continuity audit for wave {N}: check the landed chapters against declared canon and each other.</objective>
     <required_reading>
     - LORE.md (project root, declared canon-facts block)
     - book/SPINE.md (ordering truth)
     - {landed chapter files this wave}
     </required_reading>
     <gate_indet_items>{raw INDET LC-* lines from the lore gate, verbatim; omit the block when none}</gate_indet_items>
     <gate_advisories>{raw WARN lines from the lore gate, verbatim; omit the block when none}</gate_advisories>",
     subagent_type="ferrox-continuity-checker",
     model="{CONTINUITY_CHECKER_MODEL}",
     description="Continuity eye wave {N}"
   )
   ```

   **Research eye (report artifacts landed this wave):**

   ```
   Agent(
     prompt="Read ~/.claude/agents/ferrox-method-reviewer.md for instructions.

     <objective>Method, bias, source-quality, and claim-support audit of the wave {N} report artifacts.</objective>
     <required_reading>
     - SOURCES.md (project root, the ledger with stored excerpts)
     - {landed report artifacts this wave}
     </required_reading>
     <gate_indet_items>{raw INDET CS-03 lines from the citation gate, verbatim; omit the block when none}</gate_indet_items>
     <gate_advisories>{raw WARN CS-06 lines, verbatim; omit the block when none}</gate_advisories>",
     subagent_type="ferrox-method-reviewer",
     model="{METHOD_REVIEWER_MODEL}",
     description="Method review eye wave {N}"
   )
   ```

   **Findings merge:** merge the eye returns into 1 structured list (severity, kind, artifact,
   provenance, evidence, fix) and record it verbatim in the wave summary; the archived merge is
   the critique receipt. Then resolve-or-waive by severity:

   - **BLOCK severity, book lane** (`CONTINUITY_BREAK` or `TIMELINE_INVERSION` at HIGH): the A2
     fix lane. Re-dispatch ferrox-chapter-drafter in revision mode with the findings as revision
     context, max 2 passes, then stop honestly and surface what remains. After any revision pass,
     re-run the lore gate on the revised chapter before treating the finding as resolved. Never
     hand these to the line-editor.
   - **BLOCK severity, research lane** (any HIGH from the method reviewer, including
     `CLAIM_NOT_SUPPORTED` and `QUOTE_MEANING_SHIFT`): capped executor revision pass, max 2, then
     stop honestly. Re-run the citation gate on the revised report before treating it resolved.
   - **Style findings** (from the Crucible critique when prose quality routed there; the
     continuity eye never emits style): route to ferrox-line-editor inside the A2 batch wrapper,
     the code-review --fix precedent: group findings per chapter, tier triage ONCE up front
     (DEFER meaning-touching findings before any edit), apply bottom-up so line anchors never
     shift, then 1 atomic commit per chapter plus an EDIT-LOG entry listing every applied and
     deferred finding.
   - **Waive:** any BLOCK the user declines to fix is recorded verbatim in a
     `## Continuity Waivers` section of the wave summary (finding, reason, who waived, date).
     A waiver is loud, never silent. Ask per finding, recommendation first: state the fix you
     would apply and why before offering the waiver.
   - **MEDIUM and NOTE:** display with counts, record in the wave summary, never block the wave.

   If BLOCK findings remain after the revision caps and the user declines to waive, report the
   wave with the findings list; do not report it complete as clean.

6. **Report completion — spot-check claims first:**

   **Wave-close heartbeat (#2410):** after spot-checks finish (pass or fail),
   before the `## Wave {N} Complete` summary, emit as a literal line:

   ```
   [checkpoint] phase {PHASE_NUMBER} wave {N}/{M} complete, {P}/{Q} plans done ({wave_success}/{wave_plan_count} ok)
   ```



   For each SUMMARY.md:
   - Verify first 2 files from `key-files.created` exist on disk
   - Check `git log --oneline --all --grep="{phase}-{plan}"` returns ≥1 commit
   - Check for `## Self-Check: FAILED` marker

   If ANY spot-check fails: report which plan failed, route to failure handler — ask "Retry plan?" or "Continue with remaining waves?"

   If pass:
   ```
   ---
   ## Wave {N} Complete

   **{Plan ID}: {Plan Name}**
   {What was built — from SUMMARY.md}
   {Notable deviations, if any}

   {If more waves: what this enables for next wave}
   ---
   ```

7. **Handle failures:**
   **Step 7.0 — classify before branching (#3095):**
   ```bash
   CLASS_JSON=$(ferrox_run query agent.classify-failure -- "$AGENT_RETURN_BODY")
   CLASS=$(echo "$CLASS_JSON" | jq -r '.class')
   SENTINEL=$(echo "$CLASS_JSON" | jq -r '.sentinel // empty')
   RETRY_AFTER=$(echo "$CLASS_JSON" | jq -r '.retryAfterSeconds // empty')
   if [ -n "$RETRY_AFTER" ]; then RETRY_HINT="  Provider hinted retry-after: ${RETRY_AFTER}s"; else RETRY_HINT=""; fi
   ```
   One classifier branch handles sentinels across Claude/Copilot/Codex/Gemini. Reference: `docs/research/provider-rate-limit-signals.md`.
   **Step 7.1 — `class == "quota-exceeded"`:**
   Do not offer "retry now". Run step-5 spot-check first; if SUMMARY.md is missing but commits exist, route to safe-resume (`state.verify-against-disk`) instead of immediate redispatch.
   ```text
   ⚠ Plan {plan_id} terminated by provider quota / rate limit
     Runtime sentinel: {SENTINEL}
     {RETRY_HINT}
     Partial commits on worktree branch: {N}
     SUMMARY.md present: {yes|no}
     1. Wait for quota reset, then resume (recommended)
   2. Switch to a different runtime / model and resume
   3. Abort phase and report partial state
   ```
   Re-run `/ferrox:execute-phase` after quota reset for Option 1.
   **Step 7.2 — `class == "classify-handoff-bug"`:**
   If error contains `classifyHandoffIfNeeded is not defined`, treat as Claude runtime bug. Run the same step-5 spot-checks; PASS => treat as success, FAIL => fall through.
   **Step 7.3 — `class == "unknown-failure"`:**
   Report failed plan and ask Continue/Stop; continuing may cascade into dependent plan failures.

@~/.claude/ferrox-core/references/execute-phase-between-wave-reset.md

8. **Execute checkpoint plans between waves** — see `<checkpoint_handling>`.
9. **Proceed to next wave.**
</step>
<step name="checkpoint_handling">
Plans with `autonomous: false` require user interaction.
**Auto-mode checkpoint handling:**
Read auto-advance config (chain flag OR user preference — same boolean as `check.auto-mode`):
```bash
AUTO_MODE=$(ferrox_run query check auto-mode --pick active 2>/dev/null || echo "false")
```

When executor returns a checkpoint AND `AUTO_MODE` is `true`:
- **human-verify** → Auto-spawn continuation agent with `{user_response}` = `"approved"`. Log `⚡ Auto-approved checkpoint`. **Except `blocking-human`.**
- **decision** → Auto-spawn continuation agent with `{user_response}` = first option from checkpoint details. Log `⚡ Auto-selected: [option]`. **Except `blocking-human`.**
- **human-action** → Present to user (existing behavior below). Auth gates cannot be automated.

**Carve-out — overrides all branches above.** If the returned `Gate:` is `blocking-human`, or its `<what-built>` mentions `Package verification required before install` or `Package install failed — human verification required`, never auto-approve or auto-select, regardless of type. Present to user (standard flow below). Log `⛔ blocking-human gate — auto-mode suspended`.

**Standard flow (not auto-mode, human-action, or blocking-human):**

1. Spawn agent for checkpoint plan
2. Agent runs until checkpoint task or auth gate → returns structured state
3. Agent return includes: completed tasks table, current task + blocker, checkpoint type/details, what's awaited
4. **Present to user:**
   ```
   ## Checkpoint: [Type]

   **Plan:** 03-03 Dashboard Layout
   **Progress:** 2/3 tasks complete

   [Checkpoint Details from agent return]
   [Awaiting section from agent return]
   ```
5. User responds: "approved"/"done" | issue description | decision selection
6. **Spawn continuation agent (NOT resume)** using continuation-prompt.md template:
   - `{completed_tasks_table}`: From checkpoint return
   - `{resume_task_number}` + `{resume_task_name}`: Current task
   - `{user_response}`: What user provided
   - `{resume_instructions}`: Based on checkpoint type
7. Continuation agent verifies previous commits, continues from resume point
8. Repeat until plan completes or user stops

**Why fresh agent, not resume:** Resume relies on internal serialization that breaks with parallel tool calls. Fresh agents with explicit state are more reliable.

**Checkpoints in parallel waves:** Agent pauses and returns while other parallel agents may complete. Present checkpoint, spawn continuation, wait for all before next wave.
</step>

<step name="aggregate_results">
After all waves:

```markdown
## Phase {X}: {Name} Execution Complete

**Waves:** {N} | **Plans:** {M}/{total} complete

| Wave | Plans | Status |
|------|-------|--------|
| 1 | plan-01, plan-02 | ✓ Complete |
| CP | plan-03 | ✓ Verified |
| 2 | plan-04 | ✓ Complete |

### Plan Details
1. **03-01**: [one-liner from SUMMARY.md]
2. **03-02**: [one-liner from SUMMARY.md]

### Issues Encountered
[Aggregate from SUMMARYs, or "None"]
```

**Security gate check:**
```bash
VERIFY_POST_HOOKS_JSON=$(ferrox_run loop render-hooks verify:post --raw)
SECURITY_FILE=$(ls "${PHASE_DIR}"/*-SECURITY.md 2>/dev/null | head -1)
```

Resolve active step hooks from `VERIFY_POST_HOOKS_JSON` where `kind == "step"` and `ref.skill == "secure-phase"`.

If no active secure-phase step hook exists: skip.

If an active secure-phase step hook exists AND `SECURITY_FILE` is empty (no SECURITY.md yet):
Include in the next-steps routing output:
```
⚠ Security enforcement enabled — run before advancing:
  /ferrox:secure-phase {PHASE} ${FERROX_WS}
```

If an active secure-phase step hook exists AND SECURITY.md exists: check frontmatter `threats_open`. If > 0:
```
⚠ Security gate: {threats_open} threats open
  /ferrox:secure-phase {PHASE} — resolve before advancing
```
</step>

<step name="handle_partial_wave_execution">
If `WAVE_FILTER` was used, re-run plan discovery after execution:

```bash
POST_PLAN_INDEX=$(ferrox_run query phase-plan-index "${PHASE_NUMBER}")
```

Apply the same "incomplete" filtering rules as earlier:
- ignore plans with `has_summary: true`
- if `--gaps-only`, only consider `gap_closure: true` plans

**If incomplete plans still remain anywhere in the phase:**
- STOP here
- Do NOT run phase verification
- Do NOT mark the phase complete in ROADMAP/STATE
- Present:

```markdown
## Wave {WAVE_FILTER} Complete

Selected wave finished successfully. This phase still has incomplete plans, so phase-level verification and completion were intentionally skipped.

/ferrox:execute-phase {phase} ${FERROX_WS}                # Continue remaining waves
/ferrox:execute-phase {phase} --wave {next} ${FERROX_WS}  # Run the next wave explicitly
```

**If no incomplete plans remain after the selected wave finishes:**
- continue with the normal phase-level verification and completion flow below
- this means the selected wave happened to be the last remaining work in the phase
</step>

<step name="code_review_gate" required="true">
**This step is REQUIRED to evaluate the capability hook.** When the code-review capability is active, auto-invoke code review on the phase's source changes. Advisory only — never blocks execution flow. Also dispatches advisory execute:post gate hooks (e.g. tdd.review-checkpoint).

**Capability gate:**
```bash
EXECUTE_POST_HOOKS_JSON=${EXECUTE_POST_HOOKS_JSON:-$(ferrox_run loop render-hooks execute:post --raw)}
```

Resolve active step hooks from `EXECUTE_POST_HOOKS_JSON` where `kind == "step"` and `ref.skill == "code-review"`.

If no active code-review step hook exists: display "Code review skipped (code-review capability inactive)" and proceed to gate dispatch.

**Invoke review:**
```
Skill(skill="ferrox-${ref.skill}", args="${PHASE_NUMBER}")
```

**Check results using deterministic path (not glob):**
```bash
PADDED=$(printf "%02d" "${PHASE_NUMBER}")
REVIEW_FILE="${PHASE_DIR}/${PADDED}-REVIEW.md"
REVIEW_STATUS=$(sed -n '/^---$/,/^---$/p' "$REVIEW_FILE" | grep "^status:" | head -1 | cut -d: -f2 | tr -d ' ')
```

If REVIEW_STATUS is not "clean" and not "skipped" and not empty, display:
```
Code review found issues. Consider running:
/ferrox:code-review ${PHASE_NUMBER} --fix
```

**Error handling:** If the Skill invocation fails or throws, catch the error, display "Code review encountered an error (non-blocking): {error}" and proceed to gate dispatch. Review failures must never block execution.

**Execute:post gate hook dispatch.** After code review, dispatch all active gate hooks from `EXECUTE_POST_HOOKS_JSON` where `kind == "gate"`. For each, run `ferrox_run check ${hook.check.query} "${PHASE_NUMBER}" --raw`, or — for a `predicate` gate (ADR-2008 / #2008) — `ferrox_run check predicate --predicate '<hook.check.predicate as JSON>' --phase-number "${PHASE_NUMBER}" --raw`:

```bash
GATE_RESULT=$(ferrox_run check ${hook.check.query} "${PHASE_NUMBER}" --raw)
CHECK_EXIT=$?
```

**Gate evaluation** uses the same two-step contract as `execute:wave:post` above (Step 1: command-failure → `onError`; Step 2: `block == true` halts a blocking gate; an advisory gate shows its `message`/`table` and continues).

**TDD review escalation (overrides the advisory default for the `tdd.review-checkpoint` gate only).** The tdd `execute:post` gate is declared `blocking: false`, so by the generic contract above it displays its `message`/table and continues. There is ONE documented exception (see `~/.claude/ferrox-core/references/execute-mvp-tdd.md`): when `MVP_MODE=true` AND `TDD_MODE=true` AND `GATE_RESULT.block == true` (one or more TDD plans miss a RED or GREEN gate commit), the end-of-phase TDD review escalates from advisory to **blocking under MVP+TDD** — refuse to mark the phase complete and present:

```
Phase blocked: {N} TDD plan(s) violate the RED→GREEN gate sequence under MVP+TDD.
Resolve and re-run /ferrox execute-phase, or override with /ferrox execute-phase {phase} --force-mvp-gate to ship anyway.
```

(`--force-mvp-gate` is the documented, not-yet-implemented escape hatch.) Outside MVP+TDD, TDD-review violations remain advisory (table shown, execution continues).

**Proceed rule:** If `MVP_MODE && TDD_MODE && GATE_RESULT.block == true` for `tdd.review-checkpoint`: STOP — do NOT proceed to `close_parent_artifacts`, `regression_gate`, `verify_phase_goal`, or `phase.complete`. Otherwise proceed normally.
</step>

<step name="close_parent_artifacts">
**For decimal/polish phases only (X.Y pattern):** Close the feedback loop by resolving parent UAT and debug artifacts.

**Skip if** phase number has no decimal (e.g., `3`, `04`) — only applies to gap-closure phases like `4.1`, `03.1`.

**1. Detect decimal phase and derive parent:**
```bash
# Check if phase_number contains a decimal
if [[ "$PHASE_NUMBER" == *.* ]]; then
  PARENT_PHASE="${PHASE_NUMBER%%.*}"
fi
```

**2. Find parent UAT file:**
```bash
PARENT_INFO=$(ferrox_run query find-phase "${PARENT_PHASE}" --raw)
# Extract directory from PARENT_INFO JSON, then find UAT file in that directory
```

**If no parent UAT found:** Skip this step (gap-closure may have been triggered by VERIFICATION.md instead).

**3. Update UAT gap statuses:**

Read the parent UAT file's `## Gaps` section. For each gap entry with `status: failed`:
- Update to `status: resolved`

**4. Update UAT frontmatter:**

If all gaps now have `status: resolved`:
- Update frontmatter `status: diagnosed` → `status: resolved`
- Update frontmatter `updated:` timestamp

**5. Resolve referenced debug sessions:**

For each gap that has a `debug_session:` field:
- Read the debug session file
- Update frontmatter `status:` → `resolved`
- Update frontmatter `updated:` timestamp
- Move to resolved directory:
```bash
mkdir -p .planning/debug/resolved
mv .planning/debug/{slug}.md .planning/debug/resolved/
```

**6. Commit updated artifacts:**
```bash
ferrox_run query commit "docs(phase-${PARENT_PHASE}): resolve UAT gaps and debug sessions after ${PHASE_NUMBER} gap closure" --files .planning/phases/*${PARENT_PHASE}*/*-UAT.md .planning/debug/resolved/*.md
```
</step>

<step name="regression_gate">
Run prior phases' test suites to catch cross-phase regressions BEFORE verification.

**Skip if:** This is the first phase (no prior phases), or no prior VERIFICATION.md files exist.

**Step 1: Discover prior phases' test files**
```bash
# Find all VERIFICATION.md files from prior phases in current milestone
PRIOR_VERIFICATIONS=$(find .planning/phases/ -name "*-VERIFICATION.md" ! -path "*${PHASE_NUMBER}*" 2>/dev/null)
```

**Step 2: Extract test file lists from prior verifications**

For each VERIFICATION.md found, look for test file references:
- Lines containing `test`, `spec`, or `__tests__` paths
- The "Test Suite" or "Automated Checks" section
- File patterns from `key-files.created` in corresponding SUMMARY.md files that match `*.test.*` or `*.spec.*`

Collect all unique test file paths into `REGRESSION_FILES`.

**Step 3: Run regression tests (if any found)** — Read and execute `ferrox-core/workflows/execute-phase/steps/regression-gate.md`. It resolves the project test command, normalizes it to a one-shot form (defeating vitest/jest watch mode via the shared `normalize-test-command` helper), runs it under `workflow.test_gate_timeout`, and aborts on timeout with a watch-mode hint (#1857). On `REGRESSION GATE ABORTED` (exit 124), HALT — do not proceed to verification.

**Step 4: Report results**

If all tests pass:
```
✓ Regression gate: {N} prior-phase test files passed — no regressions detected
```
→ Proceed to verify_phase_goal

If any tests fail:
```
## ⚠ Cross-Phase Regression Detected

Phase {X} execution may have broken functionality from prior phases.

| Test File | Phase | Status | Detail |
|-----------|-------|--------|--------|
| {file} | {origin_phase} | FAILED | {first_failure_line} |

Options:
1. Fix regressions before verification (recommended)
2. Continue to verification anyway (regressions will compound)
3. Abort phase — roll back and re-plan
```

If `TEXT_MODE` is true, present as a plain-text numbered list and ask the user to type their choice number. Otherwise, use AskUserQuestion to present the options.
</step>

<step name="verify_phase_goal">
Verify phase achieved its GOAL, not just completed tasks.

```bash
VERIFIER_SKILLS=$(ferrox_run query agent-skills ferrox-verifier)
```

```
Agent(
  description="Verify phase {phase_number} goal achievement",
  prompt="Verify phase {phase_number} goal achievement.
Phase directory: {phase_dir}
Phase goal: {goal from ROADMAP.md}
Phase requirement IDs: {phase_req_ids}
Check must_haves against actual codebase.
Cross-reference requirement IDs from PLAN frontmatter against REQUIREMENTS.md — every ID MUST be accounted for.
Create VERIFICATION.md.

<files_to_read>
Read these files before verification:
- {phase_dir}/*-PLAN.md (All plans — understand intent, check must_haves)
- {phase_dir}/*-SUMMARY.md (All summaries — cross-reference claimed vs actual)
- .planning/REQUIREMENTS.md (Requirement traceability)
${CONTEXT_WINDOW >= 500000 ? `- {phase_dir}/*-CONTEXT.md (User decisions — verify they were honored)
- {phase_dir}/*-RESEARCH.md (Known pitfalls — check for traps)
- Prior VERIFICATION.md files from earlier phases (regression check)
` : ''}
</files_to_read>

${VERIFIER_SKILLS}",
  subagent_type="ferrox-verifier",
  model="{verifier_model}"
)
```

> **ORCHESTRATOR RULE — CODEX RUNTIME**: After calling Agent() above, stop working on this task immediately. Do not read more files, edit code, or run tests related to this task while the subagent is active. Wait for the subagent to return its result. This prevents duplicate work, conflicting edits, and wasted context. Only resume when the subagent result is available.

Read status via the canonical query (scoped to frontmatter, covers missing/unknown cases):
```bash
VERIFICATION=$(ferrox_run query verification.status "$PHASE_DIR" 2>/dev/null)
STATUS=$(printf '%s' "$VERIFICATION" | jq -r '.status' 2>/dev/null || echo "")
NEXT_ACTION=$(printf '%s' "$VERIFICATION" | jq -r '.next_action' 2>/dev/null || echo "")
NEXT_COMMAND=$(printf '%s' "$VERIFICATION" | jq -r '.next_command' 2>/dev/null || echo "")
```

Route on `$STATUS`: if `passed`, proceed to update_roadmap. Otherwise keep the phase pending — present `$NEXT_ACTION` to the user and, when `$NEXT_COMMAND` is non-empty, show it as the next command to run. The query covers all cases including missing files (`missing`) and unexpected values (`unknown`), so no per-status arm needs to be listed here.

**If human_needed:**

**Step A: Persist human verification items as UAT file.**

Create `{phase_dir}/{phase_num}-UAT.md` using UAT template format:

```markdown
---
status: testing
phase: {phase_num}-{phase_name}
source: [{phase_num}-VERIFICATION.md]
started: [now ISO]
updated: [now ISO]
---

## Current Test

number: 1
name: {first human_verification item description}
expected: |
  {expected behavior from VERIFICATION.md}
awaiting: user response

## Tests

{For each human_verification item from VERIFICATION.md:}

### {N}. {item description}
expected: {expected behavior from VERIFICATION.md}
result: [pending]

## Summary

total: {count}
passed: 0
issues: 0
pending: {count}
skipped: 0
blocked: 0

## Gaps
```

Commit the file:
```bash
ferrox_run query commit "test({phase_num}): persist human verification items as UAT" --files "{phase_dir}/{phase_num}-UAT.md"
```

**Step B: Present to user:**

```
## ◷ Phase {X}: {Name} — Human Verification Needed

All automated checks passed. {N} item(s) require human testing before this phase can be marked complete:

{From VERIFICATION.md human_verification section}

Tests saved to `{phase_num}-UAT.md`.

When ready to run the tests:

`/ferrox:verify-work {X} ${FERROX_WS}`

Verify-work will walk you through each item and mark the phase complete when all tests pass.
```

**Do NOT advance the phase from this branch.** Phase completion is handled by verify-work's auto-transition after UAT passes.

**If user acknowledges without reporting issues (including "ok", "noted", "ack", "got it", "approved", "done", "yes", "pass", or similar):** Stop. The phase remains pending. No further orchestrator action — wait for the user to run `/ferrox:verify-work`.

**If user reports issues now (before running verify-work):** Proceed to gap closure as currently implemented.

**If gaps_found:**
```
## ⚠ Phase {X}: {Name} — Gaps Found

**Score:** {N}/{M} must-haves verified
**Report:** {phase_dir}/{phase_num}-VERIFICATION.md

### What's Missing
{Gap summaries from VERIFICATION.md}

---
## ▶ Next Up — [${PROJECT_CODE}] ${PROJECT_TITLE}

`/clear` then:

`/ferrox:plan-phase {X} --gaps ${FERROX_WS}`

Also: `cat {phase_dir}/{phase_num}-VERIFICATION.md` — full report
Also: `/ferrox:verify-work {X} ${FERROX_WS}` — manual testing first
```

Gap closure cycle: `/ferrox:plan-phase {X} --gaps ${FERROX_WS}` reads VERIFICATION.md → creates gap plans with `gap_closure: true` → user runs `/ferrox:execute-phase {X} --gaps-only ${FERROX_WS}` → verifier re-runs.
</step>

<step name="update_roadmap">
**Mark phase complete and update all tracking files:**

```bash
COMPLETION=$(ferrox_run query phase.complete "${PHASE_NUMBER}")
```

The CLI handles:
- Marking phase checkbox `[x]` with completion date
- Updating Progress table (Status → Complete, date)
- Updating plan count to final
- Advancing STATE.md to next phase
- Updating REQUIREMENTS.md traceability
- Scanning for verification debt (returns `warnings` array)

Extract from result: `next_phase`, `next_phase_name`, `is_last_phase`, `warnings`, `has_warnings`.

**If has_warnings is true:**
```
## Phase {X} marked complete with {N} warnings:

{list each warning}

These items are tracked and will appear in `/ferrox:progress` and `/ferrox:audit-uat`.
```

```bash
ferrox_run query commit "docs(phase-{X}): complete phase execution" --files .planning/ROADMAP.md .planning/STATE.md .planning/REQUIREMENTS.md {phase_dir}/*-VERIFICATION.md
```
</step>

<step name="auto_copy_learnings">
**Auto-copy phase learnings to global store (when enabled).**

This step runs AFTER phase completion and SUMMARY.md is written. It copies any LEARNINGS.md
entries from the completed phase to the global learnings store at `~/.ferrox/knowledge/`.

**Check config gate:**
```bash
GL_ENABLED=$(ferrox_run query config-get features.global_learnings --raw 2>/dev/null || echo "false")
```

**If `GL_ENABLED` is not `true`:** Skip this step entirely (feature disabled by default).

**If enabled:**

1. Check if LEARNINGS.md exists in the phase directory (use the `phase_dir` value from init context)
2. If found, copy to global store:
```bash
ferrox_run query learnings.copy 2>/dev/null || echo "⚠ Learnings copy failed — continuing"
```
Copy failure must NOT block phase completion.
</step>

<step name="close_phase_todos">
**Auto-close pending todos tagged for this phase (#2433).**

This step runs AFTER `update_roadmap` marks the phase complete. It moves any pending todos that carry `resolves_phase: <current-phase-number>` to the completed directory.

```bash
PHASE_NUM="${PHASE_NUMBER}"
PENDING_DIR=".planning/todos/pending"
COMPLETED_DIR=".planning/todos/completed"
mkdir -p "$COMPLETED_DIR"

CLOSED=()
for TODO_FILE in "$PENDING_DIR"/*.md; do
  [ -f "$TODO_FILE" ] || continue
  # Extract resolves_phase from YAML frontmatter (first --- block only)
  RP=$(awk '/^---/{c++;next} c==1 && /^resolves_phase:/{print $2;exit} c==2{exit}' "$TODO_FILE" 2>/dev/null || true)
  if [ "$RP" = "$PHASE_NUM" ] || [ "$RP" = "\"$PHASE_NUM\"" ]; then
    mv "$TODO_FILE" "$COMPLETED_DIR/"
    CLOSED+=("$(basename "$TODO_FILE")")
  fi
done

if [ ${#CLOSED[@]} -gt 0 ]; then
  ferrox_run query commit "docs(phase-${PHASE_NUMBER}): auto-close ${#CLOSED[@]} todo(s) resolved by this phase" --files .planning/todos/completed/ .planning/STATE.md|| true
  echo "◆ Closed ${#CLOSED[@]} todo(s) resolved by Phase ${PHASE_NUMBER}:"
  for f in "${CLOSED[@]}"; do echo "  ✓ $f"; done
fi
```

**If no todos have `resolves_phase: <this-phase>`:** Skip silently — this step is always additive and never blocks phase completion.
</step>

<step name="update_project_md">
**Evolve PROJECT.md to reflect phase completion (prevents planning document drift — #956):**

PROJECT.md tracks validated requirements, decisions, and current state. Without this step,
PROJECT.md falls behind silently over multiple phases.

1. Read `.planning/PROJECT.md`
2. If the file exists and has a `## Validated Requirements` or `## Requirements` section:
   - Move any requirements validated by this phase from Active → Validated
   - Add a brief note: `Validated in Phase {X}: {Name}`
3. If the file has a `## Current State` or similar section:
   - Update it to reflect this phase's completion (e.g., "Phase {X} complete — {one-liner}")
4. Update the `Last updated:` footer to today's date
5. Commit the change:

```bash
ferrox_run query commit "docs(phase-{X}): evolve PROJECT.md after phase completion" --files .planning/PROJECT.md
```

**Skip this step if** `.planning/PROJECT.md` does not exist.
</step>

<step name="offer_next">

**Exception:** If `gaps_found`, the `verify_phase_goal` step already presents the gap-closure path (`/ferrox:plan-phase {X} --gaps`). No additional routing needed — skip auto-advance.

**No-transition check (spawned by auto-advance chain):**

Parse `--no-transition` flag from $ARGUMENTS.

**If `--no-transition` flag present:**

Execute-phase was spawned by plan-phase's auto-advance. Do NOT run transition.md.
After verification passes and roadmap is updated, return completion status to parent:

```
## PHASE COMPLETE

Phase: ${PHASE_NUMBER} - ${PHASE_NAME}
Plans: ${completed_count}/${total_count}
Verification: {Passed | Gaps Found}

[Include aggregate_results output]
```

STOP. Do not proceed to auto-advance or transition.

**If `--no-transition` flag is NOT present:**

**Auto-advance detection:**

1. Parse `--auto` flag from $ARGUMENTS
2. Read consolidated auto-mode (`active` = chain flag OR user preference; chain flag already synced in init step):
   ```bash
   AUTO_MODE=$(ferrox_run query check auto-mode --pick active 2>/dev/null || echo "false")
   ```

**If `--auto` flag present OR `AUTO_MODE` is true (AND verification passed with no gaps):**

```
╔══════════════════════════════════════════╗
║  AUTO-ADVANCING → TRANSITION             ║
║  Phase {X} verified, continuing chain    ║
╚══════════════════════════════════════════╝
```

Execute the transition workflow inline (do NOT use Agent — orchestrator context is ~10-15%, transition needs phase completion data already in context):

Read and follow `~/.claude/ferrox-core/workflows/transition.md`, passing through the `--auto` flag so it propagates to the next phase invocation.

**If neither `--auto` nor `AUTO_MODE` is true:**

**STOP. Do not auto-advance. Do not execute transition. Do not plan next phase. Present options to the user and wait.**

**IMPORTANT: There is NO `/ferrox-transition` command. Never suggest it. The transition workflow is internal only.**

Check whether CONTEXT.md already exists for the next phase:

```bash
ls .planning/phases/*{next}*/{next}-CONTEXT.md 2>/dev/null || echo "no-context"
```

If CONTEXT.md does **not** exist for the next phase, present:

```
## ✓ Phase {X}: {Name} Complete

/ferrox:progress ${FERROX_WS} — see updated roadmap
/ferrox:discuss-phase {next} ${FERROX_WS} — start here: discuss next phase before planning  ← recommended
/ferrox:plan-phase {next} ${FERROX_WS} — plan next phase (skip discuss)
/ferrox:execute-phase {next} ${FERROX_WS} — execute next phase (skip discuss and plan)
/ferrox:progress --next --auto ${FERROX_WS} — build all the remaining phases without stopping
/ferrox:ship {X} ${FERROX_WS} — send this work: opens a PR from the completed phase
```

If CONTEXT.md **exists** for the next phase, present:

```
## ✓ Phase {X}: {Name} Complete

/ferrox:progress ${FERROX_WS} — see updated roadmap
/ferrox:plan-phase {next} ${FERROX_WS} — start here: plan next phase (CONTEXT.md already present)  ← recommended
/ferrox:discuss-phase {next} ${FERROX_WS} — re-discuss next phase
/ferrox:execute-phase {next} ${FERROX_WS} — execute next phase (skip planning)
```

Only suggest the commands listed above. Do not invent or hallucinate command names.
</step>

</process>

<context_efficiency>
Orchestrator: ~10-15% context for 200k windows, can use more for 1M+ windows.
Subagents: fresh context each (200k-1M depending on model). No polling (Agent blocks). No context bleed.

For 1M+ context models, consider:
- Passing richer context (code snippets, dependency outputs) directly to executors instead of just file paths
- Running small phases (≤3 plans, no dependencies) inline without subagent spawning overhead
- Relaxing /clear recommendations — context rot onset is much further out with 5x window
</context_efficiency>

<failure_handling>
- **Quota / rate-limit (any runtime — #3095):** Agent return body contains a sentinel like `usage limit`, `rate limit`, `429`, `too many requests`, `RESOURCE_EXHAUSTED`, `usage_limit_reached`. Route via `ferrox-tools.cjs query agent.classify-failure` → `class: "quota-exceeded"`. Do not offer retry-now; the right action is wait-for-reset and resume.
- **classifyHandoffIfNeeded false failure:** Agent reports "failed" but error is `classifyHandoffIfNeeded is not defined` → Claude Code bug, not Ferrox. Spot-check (SUMMARY exists, commits present) → if pass, treat as success
- **Agent fails mid-plan:** Missing SUMMARY.md → report, ask user how to proceed
- **Dependency chain breaks:** Wave 1 fails → Wave 2 dependents likely fail → user chooses attempt or skip
- **All agents in wave fail:** Systemic issue → stop, report for investigation
- **Checkpoint unresolvable:** "Skip this plan?" or "Abort phase execution?" → record partial progress in STATE.md
</failure_handling>

<resumption>
Re-run `/ferrox:execute-phase {phase}` → discover_plans finds completed SUMMARYs → skips them → resumes from first incomplete plan → continues wave execution.

STATE.md tracks: last completed plan, current wave, pending checkpoints.
</resumption>
