---
name: copilot-pr-followup
description: >-
  Internal routed strategy behind `dev-loop` for GitHub-first Copilot-owned PR
  follow-up: inspect the canonical PR state, request or re-request Copilot when
  appropriate, wait deterministically for new review activity, run narrow Pi
  fix/reply/resolve passes, verify gate evidence, and stop for explicit human
  approval before merge.
compatibility: Internal routed strategy for Copilot PR follow-up. Needs gh auth for PR-followup automation.
allowed-tools: read bash edit write subagent review_loop
user-invocable: false
---

# Copilot PR Follow-up

Canonical internal owner of post-PR mechanics behind public `dev-loop`: discovery,
watch, fix/reply/resolve/re-request, gates, final approval and merge readiness.

## Route ownership

Use this skill whenever the public router lands on any PR-follow-up path that shares the same
post-PR mechanics:
- `copilot_pr_followup`
- `external_pr_followup`
- `reviewer_fixer`
- `wait_watch` uses the separate [Wait / Watch Procedure](../docs/wait-watch-procedure.md);
  load this full follow-up skill only when a fresh envelope selects follow-up.

Route-specific companion docs:
- routed `issue_intake` work is implemented through this skill plus [Copilot Loop Operations](../docs/copilot-loop-operations.md) and [Issue Intake Procedure](../docs/issue-intake-procedure.md)
- routed `final_approval` work is implemented through this skill's **Human approval checkpoint** section; [Final Approval](../final-approval/SKILL.md) is now a thin redirect to that canonical section
- the deterministic state-machine/operator guide lives in [Copilot Loop Operations](../docs/copilot-loop-operations.md)

## Operational cookbook

All commands use the resolved skill scripts directory (see [Skill asset path resolution](#skill-asset-path-resolution) below).

**1. Detect current loop state**
```sh
node <resolved-skill-scripts>/loop/detect-copilot-loop-state.mjs --repo <owner/name> --pr <number>
```
Emits JSON including `{ ok: true, state, allowedTransitions, nextAction, snapshot }`. Follow `nextAction`.

**2. One-step detect → request → emit watch params (preferred handoff contract)**
```sh
node <resolved-skill-scripts>/loop/copilot-pr-handoff.mjs --repo <owner/name> --pr <number>
```
Use this helper output as source of truth for the normal routing seam. Interpret:
- `requestWatchContract.routingState` for request-vs-watch posture
- `requestWatchContract.requestStatus` and top-level `action` / `nextAction`
- `watchArgs` only when `action: "watch"` and `requestWatchContract.watchEntryConfirmed=true`
- `requestWatchContract.stopState` for explicit blocked/stop handling

**3. Preferred async wait-boundary helper**
```sh
node <resolved-skill-scripts>/loop/run-watch-cycle.mjs --repo <owner/name> --pr <number>
```
Persistent async watch/fix loop, not handoff-only behavior: `watch → detect → if threads found, fix + reply + resolve → re-request → watch again → … → pre_approval_gate → merge`. A single returned watch cycle is never completion by itself.

<!-- pi-only -->
**PERSISTENCE MODEL: Subagents do bounded implementation tasks and exit on external wait. The main session drives the loop and re-dispatches when continuation is feasible.** If `cycleDisposition` is `pending` and `terminal` is `false`, the subagent exits on the wait boundary; the main session re-dispatches another watch boundary.
<!-- /pi-only -->

> Under the Claude Code harness, the `dev-loops:dev-loop` coordinator runs this loop as one agent. The helper-owned wait tools (`node <dev-loops-package-root>/cli/index.mjs loop watch-cycle`, `gh run watch`, `node <dev-loops-package-root>/cli/index.mjs gate probe-copilot`) block and return. When `cycleDisposition` is `pending` and `terminal` is `false`, the coordinator runs the next watch cycle itself. The coordinator does not exit on the wait boundary for a parent re-dispatch; it drives the loop until a terminal state or the watch budget expires. A bounded fix may still go to the `fixer` agent (Step 6).

Max watch timeout: **30 minutes** (from `policy-constants.mjs` COPILOT_REVIEW_WAIT_TIMEOUT_MS); expired budget + still `waiting_for_copilot_review` = hard stop. If the user explicitly asks for async handoff-only behavior, say that out loud and stop after the handoff boundary.

**4. Low-level helpers**
```sh
node <resolved-skill-scripts>/github/request-copilot-review.mjs --help
node <resolved-skill-scripts>/github/probe-copilot-review.mjs --help
node <resolved-skill-scripts>/github/list-review-threads.mjs --help
node <resolved-skill-scripts>/github/wait-pr-checks.mjs --help
node <resolved-skill-scripts>/loop/detect-copilot-loop-state.mjs --help
```

For detailed machine guarantees, judgment calls, pre-follow-up planning rules, PR description rules, and timeout defaults, use [Copilot Loop Operations](../docs/copilot-loop-operations.md).

## Required startup reads

Read the canonical entrypoint briefing first: [Entrypoint Strategies](../docs/entrypoint-strategies.md#copilot-pr-follow-up). Then read only the contract docs needed for the current step:

- [Agent Instructions](../../AGENTS.md) (repo constitution)
- [Public Dev Loop Contract](../docs/public-dev-loop-contract.md) (always)
- [Retrospective Checkpoint Contract](../docs/retrospective-checkpoint-contract.md) (when async state/resume applies)
- Active GitHub issue/PR
- Task-relevant source, tests, config, and CI

Route-dependent: see [Copilot Loop Operations](../docs/copilot-loop-operations.md) and [Issue Intake Procedure](../docs/issue-intake-procedure.md) when relevant.
Verify all material claims against source, tests, configuration, and CI.

## Skill asset path resolution

Resolve helper and contract paths from the running skill's installation layout, not the target repository.

Use this rule:
- if the skill is installed as a normalized standalone copy, the required bundled contract docs live under the shared `../docs/` directory next to the installed skill directories. <!-- rule: ASSET-PATH-INSTALLED-NO-ASSUME --> `ASSET-PATH-INSTALLED-NO-ASSUME`: Agents MUST NOT assume helper scripts are bundled unless that installed layout actually contains them.
- if you are working in the `dev-loops` source repository, this skill file lives under `skills/copilot-pr-followup/`, so source-repo helper scripts live two levels up at `../../scripts/`, while required bundled contract docs live one level up at `../docs/`
- when in doubt, resolve helper paths relative to this [skill file](./SKILL.md) first, then verify the target file exists before running it

Required bundled runtime contract docs for installed copies of this skill:
- [Public Dev Loop Contract](../docs/public-dev-loop-contract.md)
- [Retrospective Checkpoint Contract](../docs/retrospective-checkpoint-contract.md)
- [Issue Intake Procedure](../docs/issue-intake-procedure.md)
- [Copilot Loop Operations](../docs/copilot-loop-operations.md)

Read the bundled `../docs/` files. A missing required contract is a packaging/installer bug; do not assume a source checkout is available.
<!-- rule: ASSET-PATH-SOURCE-NO-REPO-LOCAL --> `ASSET-PATH-SOURCE-NO-REPO-LOCAL`: Agents MUST NOT assume `scripts/...` is repo-local to the target codebase they are operating on.

### Stale-installed-CLI: prefer worktree-source verdict/ledger tooling (#1661)

Before running verdict/ledger tooling, resolve its source with this helper. An older installed CLI can lack the gate-evidence CI exclusion and block a `pre_approval_gate` verdict on `WAITING_FOR_CI`.

```sh
node <resolved-skill-scripts>/loop/resolve-verdict-ledger-source.mjs --jq .preferredSource
```

- When `preferredSource` is `worktree`, run the verdict/ledger tooling (`upsert-checkpoint-verdict.mjs`, `write-gate-findings-log.mjs`, `detect-checkpoint-evidence.mjs`, and their gate helpers) from the worktree/source `scripts/` layout instead of the installed layout.
- When `preferredSource` is `installed`, run them from the resolved skill-scripts layout (installed) as usual.
- The helper fails soft to the installed layout when a version cannot be read. The selection changes the tooling source, not gate behavior.

### Source files under review vs. helper-script paths

Helper-script resolution applies to tooling you run. For skill/doc content under review (`skills/<name>/SKILL.md`, `skills/docs/...`, `docs/...`), installed copies can lag the PR and produce findings against text already fixed.

When reviewing skill/doc source:

1. Read from the worktree under review, using the cwd on the briefing prefix's `worktree:` line. Never review an installed copy.
2. Before citing a line, check it against `git show HEAD:<path>` at the reviewed head. If it is absent, the installed-copy citation is stale.
3. Continue to resolve helper scripts you run from the installation layout above.

`GATE-EXEC-SOURCE-READ-WORKTREE` and its briefing-prefix wiring are owned by [Gate Review Sub-Loop Contract](../docs/gate-review-sub-loop-contract.md).

## Authority and safety rules

Source code, tests, CI, and config are authoritative. Generated wiki is navigation aid only. See [Confirmation Rules](../docs/confirmation-rules.md), [Stop Conditions](../docs/stop-conditions.md), and [Merge Preconditions](../docs/merge-preconditions.md) for authorization boundaries.

## Structural quality

Apply [Structural Quality](../docs/structural-quality.md) standards from the `deep` review angle during implementation and follow-up fixes.

## Step 5: PR discovery and interpretation

Treat the PR as the main working artifact once it exists.

Before invoking `resolve-dev-loop-startup.mjs --pr <number>` to continue an externally-created PR (one `create-pr` did not just self-assign), claim ownership by adding `--claim` to that startup call (`loop startup --pr <number> --claim`; it assigns the viewer only when the PR is unassigned, and only on the user's explicit start or continue request for this exact PR). The resolver's single-contributor ownership gate fails closed on a foreign or unclaimed assignee, or a linked issue assigned to another human — see [Public Dev Loop Contract](../docs/public-dev-loop-contract.md#single-contributor-ownership-gate-resolve-dev-loop-startup).

Inspect: PR body/title (must satisfy [PR description contract](../docs/copilot-loop-operations.md)), closing reference (operator-controlled; subagents must NOT modify), author, review summaries, unresolved comments, latest commits, CI results.

At the issue-assignment seam, use `detect-initial-copilot-pr-state.mjs` and keep waiting when `waiting_for_initial_copilot_implementation`.

<!-- rule: COPILOT-FOLLOWUP-REQUEST-HELPER-ONLY -->
`COPILOT-FOLLOWUP-REQUEST-HELPER-ONLY`: Copilot review requests MUST go through `request-copilot-review.mjs` (see [Operational cookbook](#operational-cookbook)); the agent MUST NOT request Copilot by posting literal `/copilot` or `/copilot re-review` PR comments, and MUST NOT rely solely on `gh pr view --json reviewRequests` to confirm a request. After draft→ready or fix push, explicitly decide whether another pass is desired; if yes, ensure green/credibly green posture first.

<!-- rule: COPILOT-FOLLOWUP-REQUEST-BRANCHING -->
`COPILOT-FOLLOWUP-REQUEST-BRANCHING`: The agent MUST branch on the `request-copilot-review.mjs` machine-readable result exactly as follows, and MUST NOT treat an attempted request as equivalent to a confirmed request:
- `requested`: if another Copilot pass is actually desired, immediately re-baseline with `detect-copilot-loop-state.mjs` and follow its `nextAction` (enter persistent wait only through `node <dev-loops-package-root>/cli/index.mjs loop watch-cycle` or `gh run watch`)
- `already-requested`: apply the same detector-first rebasing and wait branching as `requested`
- `suppressed_same_head_clean`: no request was placed. Refresh canonical handoff state and apply the clean-terminal interpretation below. The tool always enforces same-head suppression, so no flag re-requests Copilot on an unchanged head
- `no_changes_since_last_review`: the PR head has not changed since the last Copilot review, so no request was placed. This status alone does not prove clean completion; refresh canonical handoff state and apply the interpretation below. No flag re-requests Copilot on an unchanged head
- `suppressed_post_convergence`: the default converged-once carry under `COPILOT-STATE-CARRIED-CONVERGENCE` and `COPILOT-STATE-CONVERGED-BELOW-CAP` ([Copilot Loop State Graph](../docs/copilot-loop-state-graph.md)), including at the cap and under `--force-rerequest-review`: the latest Copilot review converged on an earlier head, so no fresh round was opened, whatever the delta. An operator suppression marker in this mode also returns this status. Do NOT enter a Copilot wait seam on suppression; refresh canonical handoff state and apply the interpretation below rather than assuming pre-approval permission. An unresolved thread or an outstanding request re-opens the round as normal
- `suppressed_post_convergence_docs_only`: the strict-mode carry (`refinement.requireCopilotConvergenceAtLatestHead: true`), including an operator suppression marker in that mode, under `COPILOT-STATE-CARRIED-CONVERGENCE`, at or below the round cap: no fresh blocking round was forced and the prior converged Copilot review still stands. Do NOT enter a Copilot wait seam on suppression; refresh canonical handoff state and apply the interpretation below rather than assuming pre-approval permission. In strict mode an unresolved thread or any code/test/config/CI or unclassifiable delta re-opens the round as normal
- `unavailable`: report the limitation and stop
- `blocked_by_copilot_comment`: no request was placed. Delete the violating `violationCommentIds` (or confirm they only quote the rule inside a code span/fenced block, which does not arm the guard) and re-run; do NOT treat this as a placed request and do NOT enter a wait seam
- `fixerDispositionWarning` on any status except `suppressed_draft` and `blocked_by_copilot_comment` (they return before the disposition read): the fixer disposition is incomplete. It is advisory (ADR 0155) and blocks nothing; run `verify-fixer-disposition.mjs` if you want it complete.
- non-zero / unexpected failure: stop and report error

Branch on `status`, never on `ok`/exit-code truthiness alone: `ok: true` means the helper ran without error, not that a review was placed. Under `--silent`, the exit code is 0 only for `requested`; every other status (including `blocked_by_copilot_comment`) exits non-zero.

For suppression or `no_changes_since_last_review`, refresh with `node <dev-loops-package-root>/cli/index.mjs loop handoff --repo <owner/name> --pr <number> --watch-status changed` (readback only; never requests another review), then follow [Interpreting Copilot completion versus PR lifecycle completion](../docs/copilot-loop-state-graph.md#interpreting-copilot-completion-versus-pr-lifecycle-completion). Clean sub-loop completion is not a reason to request another round.

### Re-attachment guard (check for existing loop state first)

Before intake normalization or asking for PR direction, read the canonical re-attachment
artifact `tmp/copilot-loop/<owner>/<repo>/pr-<n>/outer-loop-state.json` without mutating it.
Never run `outer-loop.mjs` for this guard: it rewrites `timestamp` and may increment `waitCycles`.
Apply this guard on every same-PR resume<!-- pi-only -->, including between Pi async runs<!-- /pi-only -->:

| `outerAction` | Action |
| --- | --- |
| `continue_wait` | Resume from the checkpoint. Under Claude Code, the dev-loop coordinator runs the next watch cycle. |
| `reenter_copilot_loop` | Run `copilot-pr-handoff.mjs` and follow its next step. |
| `reenter_reviewer_loop` | Enter the reviewer-loop path. |
| `stop` | Report `reason` and ask for direction. |
| `done` or no checkpoint | Continue normal step sequencing. |

<!-- pi-only -->
For `continue_wait` under Pi, the subagent exits; the main session re-dispatches a fresh
`dev-loop` async subagent to resume from the checkpoint.
<!-- /pi-only -->

## Step 6: Async watch behavior

Start every wait seam with a detector refresh: `detect-copilot-loop-state.mjs --repo <owner/name> --pr <number>`.

<!-- rule: COPILOT-FOLLOWUP-WAIT-TOOLS -->
`COPILOT-FOLLOWUP-WAIT-TOOLS`: The agent MUST wait only through allowed deterministic tools: `detect-copilot-loop-state.mjs` (one-shot), `scripts/github/probe-copilot-review.mjs --repo <owner/name> --pr <number> --timeout <seconds>` (the bounded FOREGROUND Copilot-review probe; `--timeout 0` = a single immediate check), `node <dev-loops-package-root>/cli/index.mjs loop watch-cycle` (persistent), `copilot-pr-handoff.mjs --watch-status` (refresh after timeout/idle), `node <dev-loops-package-root>/cli/index.mjs loop watch-ci --repo <owner/name> --pr <number> --timeout 540` (one call waits at most about 170 s per `GATE-EXEC-BOUNDED-WAIT-CAP`; on `outcome: "pending"` run the returned `reissue` command unchanged; provider-agnostic CI: CircleCI / Actions / external commit-status; this CLI verb routes to `scripts/github/probe-ci-status.mjs`, which is equally sanctioned invoked directly with an explicit `--timeout`), `scripts/github/wait-pr-checks.mjs --repo <owner/name> --pr <number> --timeout <seconds>` (same provider-agnostic CI wait, with a direct 0/1/2 process-exit-code contract for shell/scripted callers instead of a JSON `status` field; `--timeout 0` = a single immediate check), `gh run watch <run-id> --repo <owner/name>` (Actions-only fallback when the run id is known), or the harness exit notification for a background command (a command started through the harness background-command mechanism, which notifies the agent when it exits); otherwise exit and resume later from a fresh detector call. Each bounded wait in this list (`probe-copilot-review.mjs`, `wait-pr-checks.mjs`, `loop watch-ci` and `probe-ci-status.mjs`) blocks at most about 170 s per call per `GATE-EXEC-BOUNDED-WAIT-CAP`; on `outcome: "pending"` run the returned `reissue` command unchanged, never the original command. Under the Claude Code harness each Copilot and CI probe wait (`probe-copilot-review.mjs`, `wait-pr-checks.mjs`, `loop watch-ci`, `probe-ci-status.mjs`) MUST run in the FOREGROUND (a bounded inline probe with an explicit `--timeout <seconds>`; `0` = a single immediate check); the one sanctioned non-foreground wait is a command started through the harness background-command mechanism and awaited through its exit notification; any `while`/`until`/`for` loop whose body contains `sleep` (whatever its condition; the check is whole-command, so a loop head plus a `sleep` head anywhere in one command is denied, and such calls must be split) or bare-`&` backgrounding of a probe/wait script is forbidden and mechanically denied — actor-independently and fail-closed, not bypassable by a wrapper (`timeout`/`nohup`/`sh -c`/a node loader flag; a loop inside a backtick substitution is an accepted gap) — by the PreToolUse Bash-gate (`commandContainsDetachedWaitTool` / `decideBashGate`) for the coordinator and every subagent — Claude Code never joins a bare-`&` shell-backgrounded wait (no async wake for it), so it orphans past the stop. This is prevention-only; a `SubagentStop` background-shell reaper safety-net for whatever slips past prevention is tracked as follow-up #2296.

<!-- rule: COPILOT-FOLLOWUP-REREQUEST-AFTER-PUSH -->
`COPILOT-FOLLOWUP-REREQUEST-AFTER-PUSH`:
After ANY push that advances the head of a PR Copilot has already reviewed — a gate fix, a
Copilot-thread fix, a rebase, a docs touch-up — the agent MUST run
`request-copilot-review.mjs` for the new head and branch on its machine-readable result
(`COPILOT-FOLLOWUP-REQUEST-BRANCHING`) BEFORE entering any watch. Copilot does not re-review
a new head on its own. The green-posture precondition
(`COPILOT-FOLLOWUP-REREQUEST-GREEN-GATE`) and the round cap
(`COPILOT-FOLLOWUP-ROUND-CAP`) still decide WHETHER the request is made. Never enter a
watch on a blocked request or suppression. Refresh canonical handoff state and apply
`COPILOT-FOLLOWUP-REQUEST-BRANCHING`'s shared clean-terminal interpretation: genuine
blocked/refusal outcomes stop and report; a proven clean terminal open-PR outcome
ends only the Copilot sub-loop and consults fresh same-head gate coordination.

Practical rules: do not poll manually. `waiting_for_copilot_review` → `run-watch-cycle.mjs` or report-and-resume. `waiting_for_ci` with pending/none CI → `node <dev-loops-package-root>/cli/index.mjs loop watch-ci` or report-and-resume; `node <dev-loops-package-root>/cli/index.mjs loop watch-cycle` also auto-routes a `waiting_for_ci` boundary to this CI watcher. Before considering the bounded CI exception, read [Zero-suite local-validation exception](../docs/copilot-ci-status-contract.md#zero-suite-local-validation-exception), including its unavailable CLI input; never self-certify `none` as green. `ciStatus=failure` → stop/fix, never wait.

Preferred approach:
- route decisions through `copilot-pr-handoff.mjs` output; enter watcher only on `action: "watch"` with `watchEntryConfirmed=true`; prefer `node <dev-loops-package-root>/cli/index.mjs loop watch-cycle` for deterministic handoff → watch
- `changed` → refresh startup, build and validate the new envelope, and load its
  `requiredReads` before entering the selected follow-up (Step 7 when fixing);
  do not stop after one watch cycle
- `timeout`/`idle` → re-run `copilot-pr-handoff.mjs --watch-status <status>` once to refresh state; if still `waiting_for_copilot_review` after 30-minute watch budget exhausted, hard stop with `watch timeout — PR #<number> needs manual attention`
- zero-timeout `idle` probes are for explicit one-shot status/reattach checks only; they are not the normal async wait mechanism
- after a successful fix / reply-resolve / re-request cycle, returning to `waiting_for_copilot_review` is a persistence boundary: resume the watcher instead of reporting completion
<!-- pi-only -->
- if a child async run exits and the refreshed state remains non-terminal (for example `waiting_for_copilot_review`) before merge and without a hard stop, treat that as early exit and the main session re-dispatches the same-PR follow-up path when feasible (the subagent exits on external wait)
<!-- /pi-only -->
- dispatch fix findings to the `fixer` agent; do not run inline fix passes in-watcher
  - emit the work order with `scripts/loop/emit-fixer-work-order.mjs --repo <owner/name> --pr <number> --head-sha <headRefOid> --harness <claude|pi|codex> --phase commit_only --threads-file <list-review-threads.mjs --unresolved-only output>` and dispatch the printed `dispatchPayload` unchanged, on initial, resumed and replacement dispatches alike (ADR 0106). On Claude Code join the fixer with `node <dev-loops-package-root>/cli/index.mjs gate wait-for-units --artifact <hand-back path> --after <emitted planPath> [--timeout <seconds>]` on the work order's `joinRef` (`COORDINATOR-SINGLE-CHILD-JOIN`). Then run `check-pre-push-delta.mjs --threads-file <same file> --repo <owner/name> --pr <number> --baseline <headRefOid> --pr-head <PR head just read from GitHub> --spec-identity <id> --fixer-plan <canonical plan> --site-coverage <handback outputRef>`, even when no commit was made. Handle authenticated `no_commit` or `head_moved` before dispatching a reviewer: the matching sequence closes and routes to the full gate path, with open-thread admission still separate; emit no `full` fixer for these exits. Otherwise run the delta reviewer (on Claude Code join it with `node <dev-loops-package-root>/cli/index.mjs gate wait-for-units --artifact <the delta reviewer's --result path> --after <the input run's input.patchPath>`, `COORDINATOR-SINGLE-CHILD-JOIN`) and its `--result` run (`... --baseline <headRefOid> --pr-head <PR head just read from GitHub> --result <path> --invocation <1-3> --fixer-plan <canonical plan> --site-coverage <handback outputRef>`; `PRE-PUSH-DELTA-TRIGGER`, [pre-push review contract](../docs/pre-pr-review-contract.md#delta-mode)), and only after a clearing record emit the same command with `--phase full` (the emitter refuses `--phase full` without it; after authenticated `no_commit`, post each `rejected` or `deferred` reply directly with `reply-resolve-review-thread.mjs`); new threads, a new head or a new phase require a new emission. A gate act list is emitted per [gate contract Phase 4](../docs/gate-review-sub-loop-contract.md#phase-4--fix) instead (`commit_only`, with `--gate`)
- do not report completion while unresolved Copilot feedback remains
- once a watch/probe settles, do not parse its raw output: re-read via `detect-copilot-loop-state.mjs --repo <owner/name> --pr <number>`, and read the unresolved working set via `capture-review-threads.mjs --repo <owner/name> --pr <number> --unresolved --bodies` (joined bodies; the canonical re-entry read) or `list-review-threads.mjs --repo <owner/name> --pr <number> --unresolved-only` (thread/comment ids for reply-resolve) — inline interpreters are barred by `OPS-NO-INLINE-INTERPRETER` in [Copilot loop operations](../docs/copilot-loop-operations.md)

### Canonical async dispatch wording

Every async dev-loop dispatch task body must include this clause verbatim so fresh-context subagents inherit the gate requirement:

> Before reporting merge-ready or stopping at the human approval checkpoint, you must complete the pre_approval_gate procedure and verify that a visible clean checkpoint verdict comment exists on the PR for the current head SHA. Do not stop or report completion without this evidence.

Key rules:
- helper-owned sleep inside `node <dev-loops-package-root>/cli/index.mjs loop watch-cycle`, `node <dev-loops-package-root>/cli/index.mjs gate probe-copilot`, or `node <dev-loops-package-root>/cli/index.mjs loop watch-initial` is allowed
- agent-authored shell polling is forbidden: do not use `nohup`, detached shell jobs, `tmux`, `screen`, or ad hoc `for i in $(seq ...)`, `while true`, `until ...; do sleep ...; done`, or `sleep`-retry bash loops
- do not wrap repeated `gh pr view`, `gh pr checks`, `gh api`, or `detect-copilot-loop-state.mjs` calls inside shell polling loops, and do not bypass session-based async notifications with detached shell automation
- if the designated async follow-up skill is not appropriate or available, stop and report rather than improvising a shell watcher
- the async-start contract is enforced in code: `outer-loop.mjs` fails closed without a visible async run id when `workflow.asyncStartMode: required` (relaxed automatically under the Claude Code harness — see #830)

### Async delegation guard rules (#524)

All async PR-followup dispatch MUST follow the public skill's [Guard rules](../dev-loop/SKILL.md#guard-rules).

## Step 7: Pi review/fix follow-up loop

This step covers four responsibilities: the draft gate right before `gh pr ready`, the narrower post-review follow-up loop once unresolved feedback exists, the pre-approval gate before calling the PR merge-ready, and the final approval / merge boundary.

### Follow-up loop when unresolved feedback exists

When unresolved feedback exists, use a narrow follow-up loop:

A gate-authored `medium` review thread still inside its gate's round window
(`GATE-EXEC-THREAD-DISPOSITION` in [Gate Review Sub-Loop Contract](../docs/gate-review-sub-loop-contract.md#finding-threads-and-disposition))
is unresolved feedback exactly like an external Copilot comment, and closes through this
same fix → reply-with-resolving-commit → resolve path, not a separate one. A gate-authored
`question` thread is answered (never deferred) through the same loop, and an unanswered
question is likewise unresolved feedback.

1. inspect unresolved comments/threads and failing checks
   - the canonical loop re-entry read for the working set (the trusted comment bodies of the currently-unresolved threads, e.g. after a fix push, a resolve pass, or a crash) is `scripts/github/capture-review-threads.mjs --repo <owner/name> --pr <number> --unresolved --bodies` — it emits only unresolved threads as `{ threadId, path, line, isOutdated, bodies }` with the trusted comment bodies already joined (untrusted comment text is dropped, and an unresolved thread with no trusted comment appears in `skippedUntrusted` with its logins and the remedy: a maintainer restates or resolves it, `GATE-REVIEW-COMMENT-TRUST`), so no capture-then-parse step (and no inline interpreter) is ever needed to read them
   - enumerate unresolved threads (with the thread/comment ids the reply-resolve helpers below need) via `scripts/github/list-review-threads.mjs --repo <owner/name> --pr <number> --unresolved-only` rather than a hand-written `gh api graphql` query
2. before the first local file write in each fixer pass on a Copilot-assigned PR, run `node <resolved-skill-scripts>/loop/pre-write-remote-freshness-guard.mjs --branch <headRefName>` as a required fail-closed guard
   - source `<headRefName>` from authoritative PR state (`headRefName`), not from a local branch guess
   - if the guard exits non-zero (`remote_ahead`), stop writing locally, reconcile to the refreshed remote head, then restart the fixer pass
3. classify findings by the judge's disposition of the cluster (`GATE-EXEC-THREAD-DISPOSITION` in [Gate Review Sub-Loop Contract](../docs/gate-review-sub-loop-contract.md)); severity and round never decide:
   - judge `act`: a fix target at every severity and round; decline it only on reproduction grounds (`GATE-EXEC-JUDGE-AUTHORITY-SPLIT`)
   - judge `defer`: resolved by the closing sweep as deferred; a high is never deferred, a question is never deferred and a nit is never a judge defer on its own; a nit member of a deferred mixed cluster closes with the cluster rationale, with no stamp and no filing
   - judge `reject`: reject-closed by the closing sweep; a medium, low or nit thread closes directly, a question closes once it carries an answer reply, and a rejected high stays open on the round-cap path
   - unjudged or ambiguous: stays open
   - high: blocks gate; fixed unless the judge rejected it
   - question: answer it, promote it to a defect severity when the answer reveals one, or escalate to the author when it is unanswerable. An unanswered question blocks gate-close like an open defect.
4. apply only the accepted narrow fixes
5. run the smallest validation that honestly proves the fix
6. if files changed, run `node <resolved-skill-scripts>/loop/pre-commit-branch-guard.mjs --expected-branch <headRefName>` immediately before every `git add && git commit` sequence as a required fail-closed guard
   - source `<headRefName>` from authoritative PR state (`headRefName`), not from a local branch guess
   - if the guard exits non-zero (`branch_mismatch`), stop and realign to the expected branch before staging or committing
   - this guard reads the CURRENT branch, which is itself cwd-relative; `WORKTREE-DEFAULT-USE` in [worktree-guidance.md](../docs/worktree-guidance.md#default-rule-use-a-worktree-for-mutating-local-work) additionally mandates addressing the tree explicitly (`git -C <absolute-worktree-path> …`) for the `add`/`commit`/`push` themselves
7. if files changed, push the resolving commit before any thread reply claims the fix is present
8. <!-- rule: COPILOT-FOLLOWUP-REPLY-RESOLVE-HELPER --> `COPILOT-FOLLOWUP-REPLY-RESOLVE-HELPER`: When a comment or thread is actually addressed, the agent MUST reply on GitHub with a short resolution note that references the resolving commit SHA or commit URL when applicable, using the deterministic helpers below rather than ad hoc thread mutations:
   - each thread's resolving reply states the specific change (file or behavior) that fixed THAT thread, with the resolving commit; a shared body across threads is permitted only when one shared root cause genuinely fixed them all, and the reply must name that shared cause
   - for one thread, must use the deterministic helper `reply-resolve-review-thread.mjs` from the resolved skill scripts directory with the required `--disposition fixed|deferred|rejected` (a `fixed` reply must contain the full 40-character SHA of the fixing commit, contained in the PR head)
   - for multiple matching unresolved threads, use `reply-resolve-review-threads.mjs --message-map <path>` (a JSON file mapping threadId to `{ "message": <distinct resolution body>, "disposition": fixed|deferred|rejected }`) instead of ad hoc inline `gh api` / `gh api graphql` mutations; `--message` (with a required `--disposition`) alone is only for the shared-root-cause case above
   - when using the single-thread helper, pair `--comment-id` and `--thread-id` from the same fresh PR thread snapshot rather than mixing ids across review rounds
   - use a body file under `tmp/` rather than inline shell text for the single-thread reply body (via `--message` or stdin); the batch helper takes its per-thread bodies from `--message-map <path>` — a JSON file, never stdin — so there is no separate stdin body file to prefer there
   - when the intent is GitHub linkability, keep commit SHAs and issue/PR refs as plain text (for example 3ee82fcb9d4a1f0c6e5b7a8d2c1f4e9a0b3d5c7e and owner/repo#70) and do not wrap them in backticks
   - keep backticks for actual code/path/CLI literals only
   - to reopen a wrongly or prematurely resolved Copilot or gate thread, the orchestrator or the dev-loop coordinator runs `unresolve-review-thread.mjs --repo <owner/name> --pr <n> --thread-id <id>`; only the main agent and the dev-loop coordinator may run it. The Claude Code Bash hook denies every other agent type, including fixer, review and judge. Pi does not restrict non-read-only roles. A raw `unresolveReviewThread` mutation stays denied for every caller. It refuses with `thread_not_resolved`, `thread_not_on_pr`, `pr_closed_or_merged` or `thread_author_not_reviewer`. At the Copilot round cap, a coordinator never declines and resolves a high or medium thread (GATE-EXEC-ROUND-CAP-NO-DECLINE-RESOLVE); it leaves the thread unresolved for the thread-route fixer, because `emit-fixer-work-order.mjs --threads-file` accepts only unresolved threads. After a wrong resolve, run the wrapper before emitting the fixer work order.
   - if either helper was newly added or recently changed, smoke-check it against one real thread before assuming the rest of the loop can rely on it
9. <!-- rule: COPILOT-FOLLOWUP-VERIFY-BEFORE-RESOLVE --> `COPILOT-FOLLOWUP-VERIFY-BEFORE-RESOLVE`: before resolving an addressed review thread, run a post-fix verification checkpoint
   - confirm the GitHub reply actually exists on the intended thread/comment, not only in local notes or helper stdout
   - confirm the pushed current-head diff genuinely addresses the reviewer concern on the flagged lines or pattern; if the concern is only partially addressed, leave the thread open and explain what remains
   - refresh the API-backed thread snapshot via `node <dev-loops-package-root>/cli/index.mjs gate capture-threads` and use that refreshed data — including the unresolved thread count — for follow-up decisions rather than prose assumptions
   - if any verification check fails, do **not** resolve the thread; leave it open, add a short explanation when needed, and re-enter the fix/reply loop
10. <!-- rule: COPILOT-FOLLOWUP-RESOLVE-AFTER-REPLY --> `COPILOT-FOLLOWUP-RESOLVE-AFTER-REPLY`: resolve the addressed review thread only after the reply is attached successfully, the verification checkpoint passes, and the concern is genuinely addressed
    - do not stop at a local fix if GitHub-side reply/resolve is authorized
11. after completing reply/resolve for a pass, verify zero unresolved threads remain via `node <dev-loops-package-root>/cli/index.mjs gate capture-threads` before proceeding
    - if the refreshed snapshot reports unresolved threads, re-enter the reply/resolve loop for the missed threads
    - a zero count does not waive `GATE-EXEC-FIXER-DISPOSITION-BOUNDARY` ([Gate Review Sub-Loop Contract](../docs/gate-review-sub-loop-contract.md#finding-threads-and-disposition)), which is advisory (ADR 0155): run `scripts/github/verify-fixer-disposition.mjs --repo <owner/repo> --pr <n> --head-sha <sha> --fixer-plan <fixer-emit-plan.json>` to complete the fixer's tackled set; an incomplete set warns and blocks no request or gate action
12. <!-- rule: COPILOT-FOLLOWUP-ROUND-CAP --> `COPILOT-FOLLOWUP-ROUND-CAP`: The agent MUST decide whether another Copilot pass is desired, applying the round-cap/signal-gating rules below, only after GitHub-side reply/resolve work is done for the addressed threads and the refreshed thread snapshot proves zero unresolved threads remain
    - resolve the review-round cap from config via `resolveRefinementConfig(config, "maxCopilotRounds")` from `@dev-loops/core/config`; default config ships `maxCopilotRounds: 5`. For a light-dispatched PR, resolve `resolveEffectiveCopilotRoundCap(config, { lightweight: true })` instead — `min(localImplementation.lightMode.maxCopilotRounds ?? 1, maxCopilotRounds)` (default lightweight cap: 1) — see the [Artifact Authority Contract](../docs/artifact-authority-contract.md) lightweight section (issue #1210)
    - for a light-dispatched PR, pass `--lightweight` on every round-cap-consuming helper invocation — `detect-copilot-loop-state.mjs`, `copilot-pr-handoff.mjs`, `detect-pr-gate-coordination-state.mjs`, `request-copilot-review.mjs`, and `upsert-checkpoint-verdict.mjs` — otherwise those tools resolve the full-PR cap and the composed lightweight cap is never enforced
    - **light-dispatched is a gate-dispatch fact, not a startup fact:** a PR is light-dispatched only when `resolveGateDispatchMode` resolves `inline` for it (scope under the light-mode threshold, no `gate:full` label). A PR started via `--lightweight` (PR-body-as-spec, including issue-less PR-first under `localImplementation.issueless`) whose scope is over the threshold is NOT light-dispatched: do not pass `--lightweight` to the round-cap-consuming helpers for it — it takes the full fan-out and the full-PR round cap
    - **Opt out entirely:** `maxCopilotRounds: 0` disables the external Copilot review gate for the repo — the loop runs `draft_gate → pre_approval_gate` with the local harness only, never requesting or waiting on Copilot. Use this when the repo has no Copilot reviewer configured or prefers local-harness-only review.
    - use the completed Copilot review-round count from `detect-copilot-loop-state.mjs` / `copilot-pr-handoff.mjs` as the current PR's review-round count
    - if completed review rounds have reached the resolved round cap above, do **not** re-request Copilot review within that concluded cycle
    - by default (converged-once, ADR 0090), a later head after a converged review needs no new Copilot cycle (a review with findings converges only at the cap or after the Copilot gate passed, `COPILOT-STATE-CONVERGED-BELOW-CAP`; a headerless review that states Copilot reviewed no files counts as a review with findings, ADR 0237): the request tool returns `suppressed_post_convergence` (`COPILOT-FOLLOWUP-REQUEST-BRANCHING`). A later Copilot review, for example the ruleset review when the PR becomes ready, replaces the converged one and decides again (`COPILOT-STATE-CARRIED-CONVERGENCE`)
    - with `refinement.requireCopilotConvergenceAtLatestHead: true` (strict mode), if the loop already converged and then significant post-convergence changes land on a newer head (new/changed product or test logic, not doc/message/comment-only edits), treat that as a NEW cycle and re-request Copilot review when regular rounds are already > 0 (the prior cycle's cap does not suppress this new-cycle request)
    - the inverse — a pure doc/prose or integrate-only-base-move post-convergence head bump with zero unresolved threads must NOT force a fresh blocking Copilot round — is enforced in code at and below the cap by `COPILOT-STATE-CARRIED-CONVERGENCE` ([Copilot Loop State Graph](../docs/copilot-loop-state-graph.md)); at the cap it holds even under `--force-rerequest-review`. An explicit human-only operator withdrawal (issue 1441) records a marker honored under the same checks: see the "Head-advanced sibling case" in [Merge Preconditions](../docs/merge-preconditions.md) for that escape hatch; never invoke it as an automated substitute for a real re-request
    - at the round cap, in `detect-copilot-loop-state.mjs`, `request-copilot-review.mjs` and `merge-pr.mjs`, a body-only Copilot finding (no inline thread) blocks `round_cap_clean_fallback` until a trusted disposition record for the current head clears it (`COPILOT-STATE-BODY-DISPOSITION-RECORD` in [Copilot Loop State Graph](../docs/copilot-loop-state-graph.md)). On a review of the current head only the `operator` form clears it; the actor policy in `COPILOT-STATE-BODY-DISPOSITION-RECORD` names who may post it. After a fix push the finding sits on an earlier head: the fixer posts the `fix` form, naming a fix commit after the reviewed commit, and that clears it. In the default mode the record clears it whatever the delta. With `refinement.requireCopilotConvergenceAtLatestHead: true` it clears only when the fix delta is not significant (docs/comment-only), and a significant code fix at the cap still opens a new Copilot cycle per the rule above. Gate coordination does not need the record: it routes the finding to the judge (`GATE-EXEC-COPILOT-BODY-TO-JUDGE` in [Gate Review Sub-Loop Contract](../docs/gate-review-sub-loop-contract.md))
    - when the round limit is reached **and** the refreshed thread snapshot proves zero unresolved threads **and** current-head CI is green (a real `success`), refresh canonical handoff state and apply the shared clean-terminal interpretation above instead of deadlocking on another Copilot rerequest. Consult fresh same-PR/current-head gate coordination and run `pre_approval_gate` only when permitted; reconcile missing draft evidence first. `crediblyGreen` does NOT qualify here: at the pre-approval/final boundary it fails closed to `BLOCKED_NEEDS_USER_DECISION` (unconfirmed CI, #552), so the fallback waits for CI to settle to a real green
    - when using that fallback, add a short round-exhaustion note to the visible `pre_approval_gate` gate evidence so the PR records why no further Copilot rerequest occurred
    - if the round cap is reached before the PR is thread-clean or before CI is a real green `success`, reply-resolve any remaining intentionally deferred threads with a short `deferred to follow-up` note, then follow `GATE-EXEC-ROUND-CAP-THREAD-ROUTE`: with unresolved threads, fix the feedback, reply-resolve the threads and never re-request Copilot (`wait_for_ci` stays allowed alongside while required CI is pending or none); with zero threads and pending or none CI, `wait_for_ci`; then re-run gate-coordination. Report that the Copilot round limit was reached only when no thread and no CI remedy remains
    - **Signal-gated re-request suppression:** the `detect-copilot-loop-state.mjs` state machine classifies review-thread comments by signal level (High/Mid/Low). High-signal (bugs, security, contract violations) always re-requests; Low-signal (cosmetic nits) never re-requests. When low-signal detection is enabled and thresholds are met, the machine returns a low-signal-converged terminal state without further re-requests. Apply the shared clean-terminal interpretation above and fresh gate coordination rather than inferring pre-approval permission. See [Copilot Loop Operations](../docs/copilot-loop-operations.md) for full signal-level semantics.
    - if that local validation is still known red, continue remediation instead of re-requesting Copilot
    - after a fix push advances the PR head SHA, re-run `detect-copilot-loop-state.mjs` for the new head and apply the [Copilot CI Status Contract](../docs/copilot-ci-status-contract.md). Previous-head CI is stale; only current-head results unblock CI-dependent steps. if GitHub CI/checks for the updated head are known red for a fixable issue, continue remediation instead of re-requesting Copilot. <!-- rule: COPILOT-FOLLOWUP-REREQUEST-GREEN-GATE --> `COPILOT-FOLLOWUP-REREQUEST-GREEN-GATE`: only once the updated head is green or credibly green, explicitly re-request Copilot review for the new head. Always use `request-copilot-review.mjs` — never `gh api POST repos/.../requested_reviewers` directly.
    - branch on the request result per `COPILOT-FOLLOWUP-REQUEST-BRANCHING`; enter a wait only for `requested` or `already-requested`. After the immediate `detect-copilot-loop-state.mjs` re-baseline that `COPILOT-FOLLOWUP-REQUEST-BRANCHING` requires, `waiting_for_copilot_review` uses `node <dev-loops-package-root>/cli/index.mjs loop watch-cycle` and `waiting_for_ci` uses `node <dev-loops-package-root>/cli/index.mjs loop watch-ci`, or stop and resume later. On `unavailable`, stop unless the user explicitly wants passive waiting anyway
13. after a confirmed re-requested Copilot pass, refresh PR thread state again before reporting completion; if fresh Copilot threads exist, return to this follow-up loop rather than stopping at `review requested`
14. after a confirmed re-request returns the PR to `waiting_for_copilot_review`, jump back to Step 6 and keep the same session alive; do not exit on `review requested` alone
15. if scope has broadened, stop and ask before continuing

Do not treat `fix applied locally` as the end of the loop when the workflow also requires GitHub-side reviewer follow-up. If comment/reply authorization is withheld, report explicitly that the code may be fixed while the PR conversation state remains unresolved.

### Mandatory gate-comment command contract

<!-- rule: COPILOT-FOLLOWUP-GATE-COMMENT-CANONICAL -->
`COPILOT-FOLLOWUP-GATE-COMMENT-CANONICAL`: For every `draft_gate` or `pre_approval_gate` verdict, agents MUST run `upsert-checkpoint-verdict.mjs`, never `gh pr comment`, `gh api`, or `gh pr review`. The helper owns the single COMMENT review, finding placement, markers and digest (`GATE-COMMENT-SINGLE-SURFACE`).

For fan-out/fan-in, use the structured results and true, unbudgeted `severityCounts` returned by the SAME single sanctioned call: `node <dev-loops-package-root>/cli/index.mjs gate consolidate-fanin --repo <owner/name> --pr <n> --findings-dir <dir> --head-sha <headSha> --gate <gate> --out <path> --ledger-out <ledger-path> --emit-plan <emit-plan-path> --jq '.severityCounts'`. Its inputs are the reviewers' current-head `tmp/gate-reviews/<repo-slug>/pr-<N>/<gate>-<headSha>/<angle>.json` artifacts (`GATE-EXEC-ARTIFACT-HEAD-STAMP`). Never hand-author or mutate its output with an inline interpreter, invoke consolidation again to extract another shape, or substitute all-zero severity counts.

```sh
node <resolved-skill-scripts>/github/upsert-checkpoint-verdict.mjs \
  --repo <owner/name> \
  --pr <number> \
  --gate <draft_gate|pre_approval_gate> \
  --head-sha <current_head_sha> \
  --verdict <clean|findings_present|blocked> \
  --findings-json <path-to-per-angle-results.json> \
  --findings-ledger <findings-log-path> \
  --next-action "<next action>" --findings-severity-counts '<consolidate-fanin severityCounts>' \
  --execution-mode fanout_fanin
```

Pass `--findings-ledger` on EVERY round: use the durable log path returned by `write-gate-findings-log.mjs` (`tmp/gate-findings/<owner-name>/pr-<N>/<gate>-<headSha>.json`), NOT the flat `consolidate-fanin --ledger-out` file, which lacks the required repo/pr/gate/headSha identity. Without it there is no finding surface or finding threads.

For a `draft_gate` verdict while `gates.draft.maxReviewRounds` is above 0, drop the `--findings-json` line from the command: pass `--findings-ledger` together with a required `--findings-summary "<summary>"` (the parser needs a findings-body flag), because `GATE-EXEC-ROUND-CAP` refuses `--findings-json`. Keep `--findings-json` for `pre_approval_gate` and for `maxReviewRounds` 0. `--findings-json` accepts per-angle results (`[{angle, verdict?, findings:[{severity, summary, file?, line?, disposition?}]}]`) or flat findings (`[{severity, summary, angle?, ...}]`, grouped by angle); unrecognized non-empty input fails closed. Use the sanctioned fan-in `--out`. If a withheld round removed or never wrote it, DO NOT substitute the unbudgeted `--ledger-out` file: that can exceed the render budget. Instead pass `--findings-summary "<summary>"` PLUS the durable `--findings-ledger <findings-log-path>`, never summary alone. [Phase 3 — Consolidation](../docs/gate-review-sub-loop-contract.md#phase-3--consolidation-fan-in-synthesis-and-disposition-ledger) owns provenance-based mandatory-angle proof and refusal when neither proof artifact is supplied.

For an inline round without structured results:

```sh
node <resolved-skill-scripts>/github/upsert-checkpoint-verdict.mjs \
  --repo <owner/name> \
  --pr <number> \
  --gate <draft_gate|pre_approval_gate> \
  --head-sha <current_head_sha> \
  --verdict <clean|findings_present|blocked> \
  --findings-summary "<summary>" \
  --findings-ledger <findings-log-path> \
  --next-action "<next action>" --findings-severity-counts '<true severity counts tallied for this round>' \
  --execution-mode inline_single_agent --inline-reason "<why>"
```

Use the inline round's actually tallied counts, never an all-zero placeholder; see `--help` for when counts are required. Always pass `--execution-mode` explicitly. Inline requires `--execution-mode inline_single_agent --inline-reason "<why>"` with a non-empty reason and emits a warning. The mode defaults to inline, so omitting both flags fails. `detect-checkpoint-evidence.mjs` exposes the recorded mode; `gates.requireFanoutEvidence` governs its admissibility.

`--force --force-reason` on `upsert-checkpoint-verdict.mjs` is a narrow operator-authorized CI override for the helper itself, not the default gate path. Use it only when the helper refuses gate entry solely because the current head is `blocked_needs_user_decision` with `ciStatus="failure"`, and only after the user explicitly authorizes ignoring that current-head CI failure for this one gate-comment upsert. It does **not** bypass stale-head checks, unresolved-thread / unsettled-review refusal, non-draft `draft_gate` refusal, merge conflicts, or other legality checks.

For a `pre_approval_gate` verdict, ALWAYS compute the size budget first and thread it into the upsert via `--size-budget-json`:

```sh
# Exit 0 (pass) and 1 (escalate|block) both write the JSON. Exit 2 is an
# arg/runtime error with no usable JSON; abort on it alone. Capture the status
# in the `if` condition: under `set -e` a bare `$?` capture is never reached.
if node <resolved-skill-scripts>/loop/check-size-budget.mjs --base origin/<base-branch> --head <current_head_sha> > <size-budget-json-path>; then
  check_size_budget_status=0
else
  check_size_budget_status=$?
fi
if [ "$check_size_budget_status" -eq 2 ]; then
  echo "check-size-budget.mjs failed (exit 2); aborting before upsert" >&2
  exit 2
fi
node <resolved-skill-scripts>/github/upsert-checkpoint-verdict.mjs \
  --repo <owner/name> \
  --pr <number> \
  --gate pre_approval_gate \
  --head-sha <current_head_sha> \
  --verdict <clean|findings_present|blocked> \
  ... \
  --size-budget-json <size-budget-json-path>
```

Reuse `check-size-budget.mjs`; never reimplement `computeSizeBudget`/`evaluatePrSizeBudget`. Explicit JSON reuses the computed result. If omitted, the helper auto-derives only for `pre_approval_gate`, failing closed when the base/diff cannot be resolved and naming `--size-budget-json` as the escape hatch. Draft/review do not auto-derive; their absent size evidence has no size-budget merge-gate effect because that gate reads only pre-approval evidence.

### Gate fan-out/fan-in procedure (agent-orchestrated)

Before executing this procedure, read and follow the complete [Gate Review Sub-Loop Contract](../docs/gate-review-sub-loop-contract.md). Its phases, branches and evidence requirements are mandatory; the checklist below is not a substitute for that owner.

Every sanctioned fan-out round passes the emitter's keyed plan to
`consolidate-fanin.mjs` via `--emit-plan <emit-plan-path>`. The later
`write-gate-findings-log.mjs` call derives provenance from the keyed fan-in
ledger and takes no `--emit-plan` or `--provenance`.

Both gates run this same checkpoint review chain, owned end-to-end by [Gate Review Sub-Loop Contract](../docs/gate-review-sub-loop-contract.md) (`GATE-EXEC-BUILD-ONCE-SEED`, `GATE-EXEC-BRIEFING-PREFIX`, `GATE-EXEC-SEPARATE-CHAINS`, `GATE-EXEC-POST-BEFORE-FIX`, `GATE-EXEC-REGATE-MANDATORY`, `GATE-EXEC-ANGLE-CARRY-FORWARD`, `GATE-EXEC-LIGHT-ESCALATION`); this section owns only this skill's dispatch of that chain. It is an **agent-orchestrated skill procedure** — a node script cannot spawn the per-angle reviewers, so a dedicated `gate-coordinator` agent (`GATE-EXEC-GATE-COORDINATOR`) drives the fan-out and uses the pure `@dev-loops/core/loop/gate-fanin` helpers only for consolidation, batching, and ledger mapping.

1. **Context (Phase 1):** run
   `node <dev-loops-package-root>/cli/index.mjs gate resolve-validation --profile targeted --repo <owner/name> --pr <number> --gate <gate> --head-sha <current_head_sha> --suite <selected-suite>`
   ONCE per round before building context (`GATE-EXEC-VALIDATION-RESOLUTION`). Pass each `gateSuites` entry from `resolveTargetedValidation(changedPaths)` in `@dev-loops/core/loop/validation-classify` as an explicit `--suite`; its exact `commands` remain worker checks. If the resolver returns `profile: full-repository` for a mixed or unknown surface, request that profile through the same authority. A targeted request without an explicit `--suite` is incomplete, so a targeted result with an empty `gateSuites` requests the full-repository profile. Build/read the artifact through `scripts/github/write-gate-context.mjs`, passing `--validation-results <path>` and, for a `gate:full` PR, `--full-label`. Consume `tmp/gate-context/<repo-slug>/pr-<N>/<gate>-<headSha>.json`: its resolved angles, full diff at `scope.diffPath`, and `adjacentCode` are the build-once reviewer seed; do not re-derive them per reviewer (`GATE-EXEC-BUILD-ONCE-SEED`). Reviewers consume the recorded validation instead of rerunning its suites. Let the CLI resolve the PR body and every closing issue/body; pass `--pr-body`/`--issue-body`/`--acceptance-criteria` only to override live values. Failed GitHub reads fail closed with no artifact.
2. **Carry-forward (Phase 1.2):** Skip this step ONLY on a gate's genuine first round (no prior findings-log at any head). Every re-gate (a prior findings-log exists at an earlier head) MUST run it — a non-clean prior round is never a reason to skip the resolver and re-fan everything; eligibility is decided per angle by the delta against each angle's review surface (`clean` OR `findings_present`). Before dispatch, run `node <resolved-skill-scripts>/github/resolve-angle-carry-forward.mjs --repo <owner/name> --pr <number> --gate <gate> --prev-head <prior_head_sha> --head-sha <current_head_sha> --spec-authority <identity-path>` from the current-head worktree. Use FULL 40-character SHAs; abbreviated keys cannot locate the prior log. `--prev-head` MUST be the most recently recorded head for this gate, which the dev-loop coordinator retains from the immediately preceding round in run state and passes to the gate coordinator, never guessed or discovered by scanning for a preferable older log. The resolver records its plan as the keyed `<gate>-<headSha>.carry-forward-plan.json` artifact at the current head; `GATE-EXEC-CARRY-FORWARD-PLAN-REQUIRED` makes the fan-out emitter refuse to spawn a reviewer on a re-gate head without it, so skipping this step fails closed rather than silently re-fanning.

   Follow `GATE-EXEC-ANGLE-CARRY-FORWARD` in the mandatory [owner](../docs/gate-review-sub-loop-contract.md#angle-carry-forward-fail-closed): `clean` and `findings_present` are eligible, subject to every surface, attribution and mandatory-angle guard. Carried open findings stay open and blocking as before; preserve their prior reviewer identity, `carriedVerdict` and `carriedFromHead`, never a fabricated fresh review. On success `{ carried, mustRerun }`, subtract, never substitute: dispatch every current-head resolved angle minus the plan's `carried` angles. `mustRerun` is informational, not the dispatch set; newly resolved angles absent from both lists still run. A non-zero exit is one of two shapes, distinguished by the plan artifact the resolver leaves at the current head: an ELIGIBILITY refusal (a readable prior log whose verdict is not carry-eligible) records a `{ ok: false, fallback: true }` marker, so rebuild+emit fans out every resolved angle (full re-dispatch); an OPERATIONAL or prior-log INTEGRITY failure (parse/usage error, no/mismatched/unreadable/corrupt prior log, wrong worktree) records NO marker, and the emitter then REFUSES the re-gate (`GATE-EXEC-CARRY-FORWARD-PLAN-REQUIRED`) — do not try to fan out around it, resolve the underlying failure (fix the `--prev-head`, the worktree, or the corrupt ledger) and re-run the resolver. Never treat exit 1 as "nothing to re-run" or search older logs to evade refusal.
3. **First-wave release:** follow `GATE-EXEC-FIRST-WAVE-RELEASE`. There is no primer and no lead reviewer: release the first emitted wave immediately after emission, bounded only by the emitted `maxConcurrent`. Cache priming is an optional adapter optimization and never a gate precondition.
4. **Fan-out (Phase 2):** read and follow the owner's [Phase 2](../docs/gate-review-sub-loop-contract.md#phase-2--fan-out-independent-reviewers-seeded-with-the-neutral-bundle), including `GATE-EXEC-FANOUT-DISPATCH-EMIT` and `GATE-EXEC-BRIEFING-PREFIX`. Rebuild the context after carry-forward with `--carried-angles <json>`; the rebuild discovers the gate's earlier findings-logs itself for the `prior-dispositions` read. Then run `node <resolved-skill-scripts>/github/emit-fanout-dispatch.mjs --repo <owner/name> --pr <n> --gate <gate> --head-sha <sha> --pending --carry-forward-plan <json> [--operator-focus-file <path>]` using the resolver’s complete carry plan (write the `--operator-focus-file` JSON only when the operator supplied round context for the reviewers, `GATE-EXEC-OPERATOR-FOCUS`). This includes all-carried rounds: consume the keyed zero-unit plan in fan-in and ledger writing, without dispatching a reviewer. For full fallback (`carried: []`), rebuild without `--carried-angles` and emit without `--pending`. Dispatch one collectable fresh-context `review` agent per emitted unit whose task is that unit's compact `dispatchPrompt`, unchanged; the reviewer pulls its work order with `pull-work-order.mjs` and reads the referenced evidence itself. Obey the emitted `maxConcurrent`, not the unsplit context's wave plan. A unit whose angles share one non-`full` scope already names its `briefingVariants[scope]` file as a unit required read; never inline a variant or other evidence into the task. The reviewer runs its fresh-context guard once per unit, passing the emitted unit's `scope` verbatim as `--scope` — exactly as its prompt states, never composed from the unit name. Record actual reviewer identities and each emitted `group` for fan-in. Each reviewer writes one current-head artifact per angle, not one per group. Do not re-derive prompts, groups or personas in the conductor.
   Preserve the emitted `group` even on a one-angle split tail; its angle-shaped scope does not make it an ungrouped resolved unit (ADR0072).
   <!-- rule: COPILOT-FOLLOWUP-ADVERSARIAL-BRIEFING -->
   `COPILOT-FOLLOWUP-ADVERSARIAL-BRIEFING`: Each reviewer MUST be briefed to review like an external code reviewer hunting real bugs: read the diff in full from the round's required reads (the required `diff` read is the filtered diff, with lockfiles, generated trees, and configured `gates.reviewDiff.excludeGlobs` paths excluded; `scope.diffPath` holds the unfiltered `.diff` as an optional widening read; `git diff` when null) rather than re-deriving it, and query the bundled adjacent code (callers, callees, imports; the context artifact's optional `.adjacentCode`) on demand as a navigation aid, never as a required full read, then review adversarially for concrete defects (edge cases, input validation, numeric coercion incl. NaN/Infinity/floats/negatives, null/undefined, boundary conditions, mismatched caller/callee contracts, dedup/identity bugs) with `file:line` + the failing scenario — not process nits like "no test exists". Reviewers MAY widen scope (open adjacent repo files beyond the bundle) only when their angle genuinely needs more, recording in the optional `contextWidened` field only the widening that moved their judgment. This angle-specific text is what `scripts/github/emit-fanout-dispatch.mjs` writes as each dispatch unit's angle-suffix and feeds into the composer core (issue #1852/#2166) — the SANCTIONED way this briefing is actually assembled into one reviewer prompt, right after the same step's `resolve-angle-carry-forward.mjs`/`verify-fresh-review-context.mjs` calls and before spawning the reviewer, never a hand-assembled per-group preamble and never a per-unit conductor call to the composer's own CLI (which refuses every direct fan-out invocation). The LAYOUT of this briefing — invariant block first, this adversarial angle prompt last, so every reviewer's prompt shares one byte-identical cache-aligned prefix (the pointer line itself, when a harness seeds via a file pointer rather than inline bytes) — the composer, and the `--prefix-hash`/`--prefix-file` sentinel recording, are owned by `GATE-EXEC-BRIEFING-PREFIX` — not restated here.
   Each reviewer also reads a known-findings block that lists every currently open or resolved
   finding thread from a trusted author (`GATE-REVIEW-COMMENT-TRUST`), so the reviewer does not re-raise what a thread already
   covers. The block is delivered by reference: save
   `node scripts/github/capture-review-threads.mjs --repo <owner/name> --pr <number>` output
   (the full-bodies read, not `list-review-threads.mjs`'s 200-char listing excerpt, never an
   ad-hoc GraphQL call) to a file and pass it as `--known-findings <path>` to every context
   build of the round. The builder writes the digest-keyed round-bound `<gate>-<headSha>.known-findings-<digest12>.json`
   and hash-binds it as a required read in every work order, outside the byte-identical prefix
   `GATE-EXEC-BRIEFING-PREFIX` hashes. The conductor never appends anything to the
   compact `dispatchPrompt`. The block's content, dedupe contract, and prefix-hash non-interference
   are owned by `GATE-EXEC-FINDING-THREADS` in
   [Gate Review Sub-Loop Contract](../docs/gate-review-sub-loop-contract.md#finding-threads-and-disposition).
5. **Fan-in (Phase 3):** read and follow the owner's [Phase 3](../docs/gate-review-sub-loop-contract.md#phase-3--consolidation-fan-in-synthesis-and-disposition-ledger) and [disposition-ledger contract](../docs/gate-review-sub-loop-contract.md#disposition-ledger-and-durable-logging). Consolidate once:
   `node <dev-loops-package-root>/cli/index.mjs gate consolidate-fanin --repo <owner/name> --pr <n> --findings-dir <dir> --head-sha <current_head_sha> --gate <gate> --expected-dispatch-units <n> --out <findings-json-path> --ledger-out <ledger-path> --emit-plan <emit-plan-path> --jq '.severityCounts'`.
   Use the actual emitted-and-dispatched unit count for `<n>`; omit that flag when zero. Capture the returned true severity totals for the verdict; do not invoke consolidation again to extract them. When Phase 1.2 returned a plan, pass both `--carried-angles <json>` and `--carry-forward-plan <json>`; omit both on the first round. Any non-zero result stops the pass, regardless of existing output files.

   Before the durable write, follow the owner's [Phase 3.5](../docs/gate-review-sub-loop-contract.md#phase-35--judge-relevance-disposition-1525): emit the judge work order with `dev-loops-run scripts/loop/emit-judge-work-order.mjs` (prior-round verdicts as `--prior-verdict`, an optional `--round <n>` override of the derived gate round, current spec/head/content identity, and the round's `--tmp-root` when the context bundle was relocated) and dispatch the judge with its compact `dispatchPrompt` only, then consume its relevance and spec-authority verdicts. Write `--ledger-out` directly through `write-gate-findings-log.mjs --findings-file <ledger-path> --judge-verdict <judge-verdict-path> --execution-mode fanout_fanin`, before the visible verdict. If the context bundle was relocated with `--tmp-root`, pass that same root as `--context-tmp-root` on this ledger write. The writer derives mode and provenance from the keyed emit plan and fan-in ledger; pass no hand-built provenance. On `gate:full`, also pass `--full-label` to the ledger writer. Thread the round's spec-authority identity through both writers as required by the owner's Spec-context seam. Only if `gates.postFindingsComments` is explicitly enabled, also run `node <resolved-skill-scripts>/github/post-gate-findings.mjs --repo <owner/name> --pr <number> --gate <gate> --head-sha <current_head_sha> --findings-file <ledger-path>`; that command accepts no `--provenance`.

   Run `node <dev-loops-package-root>/cli/index.mjs gate judge-pass --repo <owner/name> --pr <number> --gate <gate> --head-sha <current_head_sha> --findings-file <ledger-path> --judge-verdict <judge-verdict-path> --judge-plan <judge-plan-path> --out <act-list-path> --ledger-out <enriched-ledger-path> --spec-file <spec-path> --content-digest <content-digest> --spec-authority-verdict <spec-authority-verdict-path>`, adding the owner's required re-entry flags. Pass only its `act` list to the fixer (`GATE-EXEC-JUDGE-AUTHORITY-SPLIT`), never the unfiltered ledger. A failed bridge requires a current-head judge rerun; it never authorizes severity-only fallback or skipped spec authority. Keep the enriched ledger for verdict/disposition evidence.
6. **Verdict (Phase 4):** post through the [Gate comment command](#mandatory-gate-comment-command-contract) with `--execution-mode fanout_fanin` and the same durable log as `--findings-ledger <findings-log-path>` (`GATE-EXEC-FINDING-THREADS`). For `draft_gate` while `gates.draft.maxReviewRounds` is above 0, pass `--findings-ledger` with a required `--findings-summary "<summary>"` and no `--findings-json`. Otherwise check whether fan-in's `--out` exists: if present, use its same-round `--findings-json <path>`; a withheld round deletes `--out`, so use `--findings-summary "<summary>"` PLUS `--findings-ledger`, never summary alone. Follow the command contract's accepted shapes and coverage-proof requirements. Do NOT run `close-gate-findings.mjs` until after step 7's fixer triage (#1585).
7. **Retry / fixer triage (Phase 5):** on EVERY round, including a clean verdict, apply the owner's Phase 4 and `GATE-EXEC-THREAD-DISPOSITION` to all findings. The judge controls relevance; fixer work receives only the `act` list and retains reproduction-based rejection. Within that list, triage high/medium/low defects and answer locatable question threads (answer, promote to a defect, or escalate); body-filed findings retain the owner's non-locatable disposition rules. Defects may be fixed cheaply in the same commit when already touching that code. A low the judge disposed `act` is a fix target declinable only on reproduction grounds (`GATE-EXEC-JUDGE-AUTHORITY-SPLIT`), never re-deferred on its severity label, except `GATE-EXEC-LOW-FIX-UNTIL-CAP`. Only a judge `defer` defers a finding, whatever its severity or round, except `GATE-EXEC-LOW-FIX-UNTIL-CAP`; the medium fix window is an input to the judge. A judge `act` overrides the medium fix window: an act item blocks `clean` until a fix commit is re-gated (ADR 0089), except `GATE-EXEC-LOW-NIT-CONVERGENCE`. Nits require no severity-axis fixer cycle; a judge `act` on a nit is the exception and reaches the fixer through the severity-blind act filter, except `GATE-EXEC-LOW-FIX-UNTIL-CAP`. Drive high and act findings through Step 7's fix → reply-with-resolving-commit → resolve loop.

   After triage, at EVERY gate close (clean or not), run
   `node <resolved-skill-scripts>/github/close-gate-findings.mjs --ledger <findings-log-path> --allowed-refs <governing-issue>`
   against the same ledger. Resolve `<governing-issue>` deterministically from Phase 1's `closingIssuesReferences` / `Closes #N`; pass all closing issue numbers as CSV for an umbrella PR, never a hardcoded literal. Omit the flag only when the PR closes no issue. This permits bare references to governing issues only; unrelated issue references remain fail-closed.

   The sweep only dispositions threads; it posts no verdict and never fix-closes. It resolves only the threads the judge disposed `defer`, leaving act, unjudged and question threads unresolved — except a thread whose markers are all judge `act` with `remedyKind: evidence_only`, which it closes with an evidence-only reply (`evidenceOnlyClosed`), and an answered `question` thread the judge disposed `reject`, which ADR 0088 has the sweep reject-close, citing the judge's rejection rationale; an unanswered question, or one the judge did not reject, still stays unresolved. It also reject-closes a judge-rejected medium, low or nit defect thread per `GATE-EXEC-THREAD-DISPOSITION` (ADR 0144); a judge-rejected high stays unresolved. A judge-deferred thread always gets the `disposition=deferred` stamp and a filing entry, except a nit member of a judge-deferred mixed cluster, which closes with the cluster rationale in a `Closed at gate close` reply with no stamp and no filing; the ADR 0088 question reject-close never files and never stamps `deferred`. Its reported `unresolvedGateThreadCount` must be zero for downstream gate-close assertions.

   Then re-enter the chain at Phase 1 for the fixed head — [Phase 1.2](../docs/gate-review-sub-loop-contract.md#angle-carry-forward-fail-closed) decides what re-runs, including eligible findings-present angles whose open findings and provenance carry unchanged. Context-builder and fan-in always re-run. Repeat until the consolidated verdict is `clean` for the current head SHA AND 0 unresolved gate-authored threads remain (`GATE-EXEC-REGATE-MANDATORY`, `GATE-EXEC-THREAD-DISPOSITION`).

   Exception: when a `draft_gate` round at or past the cap round (`gates.draft.maxReviewRounds`) has a judge act list that is all `low`/`nit` and the `commit_only` pre-push delta result for the fixer commit is `locally_clear`, do not re-enter Phase 1. Post with `upsert-checkpoint-verdict.mjs --converged-json` (built from the judge act list, the fixer commit and the delta result file) plus `--findings-ledger`. `GATE-EXEC-LOW-NIT-CONVERGENCE` owns the clauses and refusals; any refusal keeps the full round. Below the cap, route the low/nit act list to the fixer and run the next full round.

### Draft gate contract (before marking PR ready for review)

The canonical checkpoint verdict comment contract is [Gate Review Comment Contract](../docs/gate-review-comment-contract.md).

- **Gate name:** Draft gate
- **Trigger / boundary:** right before running `gh pr ready` (draft → ready for review)
- **Skip rule:** before entering the draft gate, run `detect-pr-gate-coordination-state.mjs` and check `draftGateAlreadySatisfied`. If `true`, skip the draft gate entirely — the draft→ready transition was already recorded. `draft_gate` is a one-time gate; do not re-post on new heads once clean draft-gate evidence exists for the transition record. (While the PR is still draft, advancing the head SHA does require a new draft-gate comment for the new head.) This skip rule applies only to the draft boundary.
- **Execution directive:** run the [Gate fan-out/fan-in procedure](#gate-fan-outfan-in-procedure-agent-orchestrated) (the agent-orchestrated chain defined in [Gate Review Sub-Loop Contract](../docs/gate-review-sub-loop-contract.md)) with the draft gate inspection angles resolved from config.
- **Review angles:** resolved at runtime from config via `resolveGateAngles(config, "draft")` from `@dev-loops/core/config`. Default config enables all configured draft gate angle families; consumer repos may opt out individual angles by setting `enabled: false` on that angle's entry. Do **not** apply angles from the other gate; each gate owns its own angle list from config.
- **CI prerequisite:** resolve the draft gate config first (`resolveGateConfig(config, "draft")`). When `requireCi=true` (default), wait for green current-head CI before entering `draft_gate`. When `requireCi=false`, the draft gate may proceed without green CI. This draft-only override does **not** relax `pre_approval_gate` — that gate has its own separate `gates.preApproval.requireCi` knob (default `true`), which when set `false` opts the pre-approval boundary out of the CI precondition independently.
- **Pass criteria:** all configured draft gate angles pass; every judge act item is addressed (on a round with an unjudged finding, every finding at a `blockCleanOnFindingSeverities` severity too); validation passes; no unrelated files are included.
- **Next step after passing:** mark the PR ready for review via `scripts/github/ready-for-review.mjs` — never a raw `gh pr ready` call or the GitHub UI's "Ready for review" button, both of which bypass its gate-authored-thread guard (`RAW-GH-PR-READY-BYPASS` in [Anti-patterns](../docs/anti-patterns.md)).
- **Board status sync (built-in, after ready-for-review):** `ready-for-review.mjs` performs the In-Progress board move as a deterministic tail (#1069); run no separate `sync-item-status` step. The move is best-effort and NON-FATAL and never blocks marking the PR ready.
- **Non-substitution rule:** a clean `draft_gate` comment only authorizes the draft → ready-for-review transition for that head SHA; cross-gate non-substitution is owned by `GATE-COMMENT-NON-SUBSTITUTION` in [Gate Review Comment Contract](../docs/gate-review-comment-contract.md).
- **Required PR comment:** post a visible checkpoint verdict comment using the mandatory [Gate comment command](#mandatory-gate-comment-command-contract). Comment field content and validation-reporting format are owned by `GATE-COMMENT-VALIDATION-REPORTING`; the draft-boundary comment requirement is owned by `GATE-COMMENT-DRAFT-REQUIREMENTS`; posting-failure fail-closed behavior is owned by `GATE-COMMENT-FAIL-CLOSED` — all in [Gate Review Comment Contract](../docs/gate-review-comment-contract.md).

### Pre-approval gate contract

The canonical checkpoint verdict comment contract is [Gate Review Comment Contract](../docs/gate-review-comment-contract.md).

- **Gate name:** Pre-approval gate
- **Trigger / boundary:** right before calling a PR/branch review-complete, approval-ready, merge-ready, or ready for final handoff
- **Execution directive:** run the [Gate fan-out/fan-in procedure](#gate-fan-outfan-in-procedure-agent-orchestrated) (the agent-orchestrated chain defined in [Gate Review Sub-Loop Contract](../docs/gate-review-sub-loop-contract.md)) with the pre-approval gate inspection angles resolved from config. The `acceptance-criteria` angle is mandatory for this gate (see `.devloops` `gates.preApproval.angles` — the `acceptance-criteria` entry sets `mandatory: true`) and always survives dynamic resolution. Retry rule: in subsequent cycles, [Phase 1.2](../docs/gate-review-sub-loop-contract.md#angle-carry-forward-fail-closed) decides what re-runs.
- **Review angles:** resolved at runtime from config via `resolveGateAngles(config, "preApproval")` from `@dev-loops/core/config`. Default config enables all configured pre-approval gate angle families; consumer repos may opt out individual angles by setting `enabled: false` on that angle's entry.
- **Persona mapping:** the fan-out emitter resolves each assigned angle's persona and focus prompt and carries them in the unit's work order (`angleInstructions`, ADR 0086) — that carried work order is the fan-out reviewer's role source. A reviewer running standalone (outside a fan-out unit) or defensively re-validating a carried role never calls `resolveReviewerRole` inline; the sanctioned standalone/defensive role source is `node <dev-loops-package-root>/cli/index.mjs gate resolve-role --gate <draft_gate|pre_approval_gate|review|spike> --angle <angle>` (`--gate <operation>`, where `<operation>` is the review operation being run; `pre_approval_gate` is this gate's own case). Exit 0: use the returned persona, and use `prompt` when present, otherwise review the angle by name. On a nonzero exit: inside a fan-out unit (defensively re-validating a carried role), emit the blocked result via `emit-reviewer-blocked.mjs` as usual; running standalone (no findings directory or fan-out budget counters), instead stop that angle's pass and report it as blocked in the review verdict output.
<!-- pi-only -->
- **Model tier (Pi and Codex):** use the active harness recorded in the gate context, then resolve each reviewer's model via `resolveRoleModel(config, { role: angle, harness: context.harness, kind: "angle" })` from `@dev-loops/core/config`. `kind: "angle"` forces the review tier even when the angle name collides with a routine role. Pass a model at dispatch **only when non-null**; Codex currently inherits, while Pi uses its configured model when present.
<!-- /pi-only -->
- **Pass criteria:** the sub-loop completes with verdict `clean`; all configured angles pass, following the sequential-fallback rule owned by `GATE-EXEC-FANOUT-SEQUENTIAL-FALLBACK` in [Gate Review Sub-Loop Contract](../docs/gate-review-sub-loop-contract.md).
- **Acceptance criteria verification:** follow the canonical procedure in [Acceptance Criteria Verification](../docs/acceptance-criteria-verification.md) before posting the `pre_approval_gate` comment. `upsert-checkpoint-verdict.mjs` ticks the reviewer-verified items from the findings ledger's `verifiedItems` after every refusal check, directly before it posts the verdict (step 5 of that procedure), so the merged PR shows checked AC.
- **Next step after passing:** continue the Step 7 flow and then proceed to the human approval checkpoint below.
- **Non-substitution rule:** a clean `pre_approval_gate` comment governs final-approval readiness for that head SHA and is separate from `draft_gate` evidence; cross-gate non-substitution is owned by `GATE-COMMENT-NON-SUBSTITUTION` in [Gate Review Comment Contract](../docs/gate-review-comment-contract.md).
- **Required PR comment:** post a visible checkpoint verdict comment using the mandatory [Gate comment command](#mandatory-gate-comment-command-contract). Comment field content and validation-reporting format are owned by `GATE-COMMENT-VALIDATION-REPORTING`; the pre-approval-boundary comment requirement is owned by `GATE-COMMENT-PREAPPROVAL-REQUIREMENTS`; posting-failure fail-closed behavior is owned by `GATE-COMMENT-FAIL-CLOSED` — all in [Gate Review Comment Contract](../docs/gate-review-comment-contract.md).
- <!-- rule: GATE-SKIP-NOT-RECOVERABLE-BY-CONVERGENCE --> `GATE-SKIP-NOT-RECOVERABLE-BY-CONVERGENCE`: Skipping the gate MUST NOT be treated as recoverable by asserting convergence.

### Conflict-resolution gate

Before any merge-ready or final-approval claim, run `detect-pr-gate-coordination-state.mjs` for the current PR. If it reports `gateBoundary=conflict_resolution` or `mergeStateStatus` is conflicted, stop the normal gate path immediately and use this recovery flow. Exception: when `baseFreshness.status` equals `base_stale_integrate_first` (the reason starts with that token), follow `GATE-EXEC-BASE-REFRESH` in [Gate Review Sub-Loop Contract](../docs/gate-review-sub-loop-contract.md) instead of steps 1 to 9 (integrate through `resolve-pr-conflicts.mjs`, no authorization step).

1. fetch fresh `origin/main`, confirm the current PR head SHA, and summarize the conflict scope from `mergeStateStatus` plus any reported `conflictFiles`
2. ask for explicit authorization before any merge commit or other branch-state-changing reconciliation command
3. after authorization, reconcile locally on the PR branch; default to a merge commit (`git merge origin/main`) per the behind-branch integration policy in [Local Implementation Skill](../local-implementation/SKILL.md#branch--review--merge-policy), unless the operator explicitly chooses another conflict-resolution command
4. auto-resolve simple conflicts when the correct fix is mechanical and clearly in scope; report complex conflicts explicitly and fix them manually only for in-scope files
5. rerun the smallest honest local validation for the touched conflict slice
6. rerun `detect-pr-gate-coordination-state.mjs` for the new head
7. because the head changed, rerun `pre_approval_gate` for the new head before any approval-ready or merge-ready claim
8. wait for current-head CI again before retrying merge evaluation
9. if the chosen reconciliation rewrote branch history (rebase only — merge commits push as a normal fast-forward), ask for explicit authorization before `git push --force-with-lease` (`--force-with-lease` only, never bare `--force`), then continue the loop on the updated head

`mergeStateStatus: CLEAN` alone is not enough to resume approval or merge claims. Every [merge-ready precondition](../docs/merge-preconditions.md#required-before-merge) still applies.

### Merge-ready preconditions

See [Merge Preconditions](../docs/merge-preconditions.md). Verify: zero unresolved threads (via `node <dev-loops-package-root>/cli/index.mjs gate capture-threads`), visible clean `draft_gate` + current-head `pre_approval_gate`, green CI. Fresh-context review follows [Gate Review Sub-Loop Contract](../docs/gate-review-sub-loop-contract.md).

### Human approval checkpoint

After merge-ready preconditions pass, verify [Merge Preconditions](../docs/merge-preconditions.md) authoritatively before reporting merge-ready, and cross-check threads via `node <dev-loops-package-root>/cli/index.mjs gate capture-threads` (not prose assertion). Stop at the human approval checkpoint by default, and stop at `waiting_for_merge_authorization` after approval unless merge is explicitly authorized. When authorized, merge through the sanctioned wrapper `node <resolved-skill-scripts>/github/merge-pr.mjs --repo <owner/name> --pr <number> --human-approved-by <login>`. It runs the full pre-merge precondition set fail-closed before merging; a raw `gh pr merge` is forbidden.

When `approval.enabled` is set, don't just park silently at this stop: run `node <dev-loops-package-root>/cli/index.mjs gate offer-human-handoff --repo <owner/name> --pr <number>` to surface candidate reviewers/assignees, then **offer** them to the operator. Only on operator confirmation, route the PR with `--assign <login>` / `--request-review <login>`. This is OFFER-only — never auto-assign. See the `approval` section in [Merge Preconditions](../docs/merge-preconditions.md); it pairs with `autonomy.humanMergeOnly`.

### Mechanical pre-merge gate evidence check

The sanctioned merge wrapper `merge-pr.mjs` (above) runs this check internally,
fail-closed, before it merges. The wrapper reuses `detect-checkpoint-evidence.mjs` (always-on: it reads both verdict
surfaces — the PR review stream, primary per `GATE-COMMENT-SINGLE-SURFACE`, and visible
PR issue comments for legacy/fallback verdicts — and fails closed unless both required
gate verdicts are visible: a clean `draft_gate` and a clean current-head
`pre_approval_gate`). You may also run `detect-checkpoint-evidence.mjs --repo <owner/name>
--pr <number>` standalone for a read-only pre-merge check. Resolved threads, green CI,
clean Copilot rereview, or local notes never substitute for the wrapper's fail-closed
verdict. If a final approval or merge boundary sees a raw `gh pr merge`
(`RAW-GH-PR-MERGE-BYPASS`), treat that as a workflow violation and stop.

### Stale runner-coordination lock held by a completed run

The pre-merge check fails closed on `.pi/runner-coordination/<owner>/<name>/pr-<n>.json`:
a competing new run receives `ownership_lost`, or `stale_runner` after max age.
The auto-loop releases its own claim best-effort at terminal stops (clean-converged,
blocked, done, including human approval); release never blocks stopping or clears
an active competitor's claim. The headless driver also releases claims still owned
by its run when the process exits.

`copilot-pr-handoff` uses `supersedeStale: true` to take over only confirmed-dead
(recorded exit signal) or max-age-expired claims. A genuinely live owner still blocks.
Before standing down or deciding dispatch, verify actual execution with the harness's
`subagent status`: LIVE means an actively updating `EXECUTING` workflow child.
A fresh claim heartbeat alone is insufficient; a completed/control run may have left it.

A takeover driven by the `copilot-pr-handoff` pre-flight (`supersedeStale: true`) reports which
evidence authorized it as `recovery: { evidence: "exit_signal" | "stale_max_age", displacedRunId,
maxAgeMs }` on the `runnerOwnership` result. The explicit `takeover` subcommand below carries no
`recovery` field: it takes over on your instruction, and the CLI refuses a live non-stale owner. A result that
displaced nobody carries no `recovery` field either, so a
handback records a recovery only when that field is present — a plain fresh claim is never
reported as a recovery.

An async owner that will not reach a terminal stop must not wait for a process boundary to
free its claim. After verifying with native evidence that its required children are joined,
run the owner-only handoff before returning its handback and record its status there:

```sh
node <resolved-skill-scripts>/loop/pr-runner-coordination.mjs handoff \
  --repo <owner/name> --pr <number> --run-id <the id used at claim>
```

`handoff` appends the exit signal and clears the claim in one locked write, so the successor's
pre-flight finds no claim to recover: it takes the `no_owner_record` path, claims fresh and returns
`claimed_new` with a `previousRun` naming the handed-off owner and no `recovery` field, without
waiting out the stale window. A `recovery` field appears only when the successor actually displaces
a claim. `ownership_lost` or
`run_id_required` exits 1 with no state write.

If a stale claim still blocks the merge because the completing run could not release it (crash, killed process, or a pre-#1109 run), the sanctioned recovery for a lock held by a COMPLETED run is an explicit takeover by the merge run:

```sh
node <resolved-skill-scripts>/loop/pr-runner-coordination.mjs takeover \
  --repo <owner/name> --pr <number> --run-id <the merge run's id>
```

`takeover` seizes ownership for the given run id and records the displaced run under `previousRun`. Its refusal policy lives in `RUNNER-HANDOFF-TEARDOWN` ([Copilot loop operations](../docs/copilot-loop-operations.md#runner-handoff-teardown)). Only take over when the prior owner is genuinely completed/dead. A genuinely active (non-stale) run must still be allowed to block — do not take over to race a live run.

### Mandatory post-merge retrospective checkpoint write

After merge (or an operator-recorded retrospective discharge), write the durable checkpoint before
exiting. Under `RETRO-FRESH-CONTEXT-MANDATORY` in [Retrospective Checkpoint Contract](../docs/retrospective-checkpoint-contract.md),
the retrospective MUST be an independent fresh-context pass over the cycle's full
agent/subagent tool-call record, dispatched like a gate reviewer, never self-authored inline.
Both `complete` and `skipped` MUST carry this cycle's `--repo`, `--pr` and full
`--merge-commit` oid (obtain it with `node <resolved-skill-scripts>/github/view-pr.mjs --repo <owner/name> --pr <n> --json mergeCommit --jq .pr.mergeCommit.oid`).
The next loop checks that identity against base-branch ancestry; absent identity is
unverifiable/stale. `complete` also MUST carry fresh-context provenance; the CLI rejects
`inline` and identity-less complete/skipped records:

```sh
node <resolved-skill-scripts>/loop/checkpoint-contract.mjs --state complete --notes "<one-line retrospective summary>" \
  --retro-context fresh --record-source <path to the seeded agent/subagent tool-call record> \
  --repo <owner/name> --pr <number> --merge-commit <full merge commit oid>
```

To record a discharge without a retrospective pass:

```sh
node <resolved-skill-scripts>/loop/checkpoint-contract.mjs --state skipped --reason "Retrospective obligation for PR <number> discharged without a pass: <factual reason>" \
  --repo <owner/name> --pr <number> --merge-commit <full merge commit oid>
```

Loop startup reports an undischarged retrospective as `pendingRetrospectives`, and the orchestrator dispatches each one in parallel with the unit. `merge-pr` refuses (`retrospective_checkpoint`) until `.pi/dev-loop-retrospective-checkpoint.json` is updated to `complete` or `skipped` carrying that cycle's identity.

### Post-merge board sync (best-effort)

After the retrospective checkpoint write, run the post-merge board sync and archive as standard steps of the post-merge hook (see [Merge Preconditions](../docs/merge-preconditions.md) "Post-merge"):

```sh
node <dev-loops-package-root>/cli/index.mjs queue sync-status --repo <owner/name> --pr <number> --item <linked-issue> --logical-column done || true
node <resolved-skill-scripts>/projects/archive-done-items.mjs --repo <owner/name> || true
```

Run from the main checkout before worktree removal: `queue sync-status` resolves
`.devloops` from cwd and has no `--repo-root`. `queue.statusColumns` maps `done` to
the configured column; omit `--item` for a PR queue item (empty also falls back to `--pr`).
Board/archive settings are `tracker.board` and `queue.archiveOlderThanDays` (default 7d),
using local `gh` auth, no CI/cron/PAT. Both steps are best-effort and NON-FATAL; retain
both `|| true` guards. Neither failure blocks merge or retrospective.

`node <dev-loops-package-root>/cli/index.mjs queue reconcile` (idempotent, run best-effort at loop startup) is the fallback when the sync above is skipped: it re-derives every item's column from live GitHub state.

The post-merge hook also fast-forwards the main checkout's local `main` to `origin/main` (#1596) so read-only gate scripts run current code; see [Merge Preconditions](../docs/merge-preconditions.md) "Post-merge" for the canonical step. Best-effort and non-blocking (`--ff-only` refuses a diverged main without rewriting history).

## Validation policy

Follow [Validation Policy](../docs/validation-policy.md). Default to the narrowest deterministic targeted check; local full-repository runs go only through `node <dev-loops-package-root>/cli/index.mjs gate resolve-validation`. For repo-local examples: `bun run test:dev-loop` for skill scripts, contract tests for templates, `git diff --check` for docs. When CI runs exist, use `gh run watch` or `detect-copilot-loop-state.mjs` instead of `sleep`-based polling. Distinguish: locally validated, full current-head CI or sanctioned full evidence, awaiting CI, and incomplete evidence.

## Confirmation checkpoints

See [Confirmation Rules](../docs/confirmation-rules.md). Stop and ask before GitHub mutations (edits, assignments, labels, comments, reviews, thread resolution, commits, pushes, merges, workflows) unless explicitly authorized.

## Stop conditions

Follow [Stop Conditions](../docs/stop-conditions.md). Genuine stops: `blocked` state, `done`, `approval_ready` without merge auth, ambiguous state, scope drift. Non-stops: `waiting` watcher states, quiet observations.

## Anti-patterns

Follow [Anti-patterns](../docs/anti-patterns.md) and this skill's request, wait,
reply/resolve, gate-comment and merge boundaries. A conflicted PR never authorizes a
blind `gh pr merge`, `gh pr update-branch` or unapproved rebase.

## Output expectations

Report the inspected issue/PR, current state, next recommended action and any required
authorization concisely.
