---
description: Ship a branch to its deploy target — detect or create PR, fix CI, review, merge. Returns structured result for callers.
argument-hint: "[source_branch | \"staging\" | \"milestone/{slug}\"] [--target TARGET] [--issue ISSUE_NUMBER] [--repo REPO] [--max-ci-iterations N] [--max-review-iterations N] [--dry-run]"
allowed-tools: Bash, Read, Grep, Glob, Skill
---
<!-- SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios -->
<!-- SPDX-License-Identifier: AGPL-3.0-or-later -->

# /deploy-pr — PR Ship Orchestrator

> **Skill names**: `{FORGE_SKILL_PREFIX}` is `forgedock:` (plugin install) or empty (`install.sh`), resolved once per run by `commands/work-on.md` § Skill Name Resolution. If the skill is not found under either name, STOP and report "skill not found" — never run the phase inline.

**Input**: $ARGUMENTS

**NEVER use plan mode (EnterPlanMode)** — it breaks execution context.
**NEVER use the Agent tool** — deploy-pr dispatches sub-skills via `Skill(...)` only. The Agent tool bypasses the allowed-tools constraint and produces opaque output that cannot be structured into the deploy result.

**Agent model policy**: `model: "{DEFAULT_MODEL}"` — resolved from forge.yaml `agents.default_model`, else "sonnet" (standard tier). Fallback: `model: "opus"` if rate-limited. User can override with `--model <name>`.

<!-- FORGE:SPEC_LOADED — deploy-pr.md loaded and active. Agent is bound by this spec. -->

---

## What This Command Does

`/deploy-pr` is a **sub-skill** designed to be invoked by callers like `/autopilot` that need to ship a branch without consuming their own context window. It handles the full PR shipping lifecycle:

1. Detect or create the PR for the source→target pair
2. Run the CI gate — fix failures via `/fix-ci` (loop up to max iterations)
3. Run the review gate — via `/review-pr` (fix + re-review loop up to max iterations)
4. Merge the PR after both gates pass
5. Return a structured result to the caller

**Never force-merges.** If CI or review fail after maximum iterations, the command stops and reports the blocking state without merging.

---

## Forbidden Tools Self-Check

**Before executing any phase**, verify you are NOT using any of these tools:

| Tool | Status | Reason |
|------|--------|--------|
| `Agent` | **FORBIDDEN** | Bypasses allowed-tools; produces opaque output that cannot feed the structured result |
| `EnterPlanMode` | **FORBIDDEN** | Breaks execution context; phases must be executed, not planned |

---

## Phase 0: Config Resolution & Argument Parsing

### 0A: Read forge.yaml

Resolve all config variables before any logic runs. This prevents unresolved `{PLACEHOLDER}` values in bash blocks — a known failure mode on deploy-info.md (issues #318, #1392).

```bash
CONFIG_FILE="${FORGE_CONFIG:-forge.yaml}"

GH_REPO=$(yq '.project.owner + "/" + .project.repo' "$CONFIG_FILE" 2>/dev/null)
GH_FLAG="-R $GH_REPO"
STAGING_BRANCH=$(yq '.branches.staging // "staging"' "$CONFIG_FILE" 2>/dev/null || echo "staging")
DEFAULT_BRANCH=$(yq '.branches.default // "main"' "$CONFIG_FILE" 2>/dev/null || echo "main")
REPO_PATH=$(yq '.paths.root' "$CONFIG_FILE" 2>/dev/null || echo "$(git rev-parse --show-toplevel)")
```

### 0B: Parse Arguments

```
$ARGUMENTS format examples:
  staging
  milestone/my-feature
  feat/my-branch --target staging
  staging --issue 1234 --repo owner/repo --max-ci-iterations 2 --max-review-iterations 3
  staging --dry-run
```

Parse:
- `SOURCE` — first positional arg, or `staging` if omitted
- `--target TARGET` — explicit PR target override (skips routing table)
- `--issue ISSUE_NUMBER` — parent issue to reference in PR body (optional)
- `--repo REPO` — override GH_REPO (optional — forge.yaml takes precedence if absent)
- `--max-ci-iterations N` — max CI fix attempts, default 3
- `--max-review-iterations N` — max review + fix cycles, default 3
- `--dry-run` — run all phases but do NOT merge; print what would happen

```bash
SOURCE="${1:-staging}"
TARGET=""          # resolved in Phase 1 if not passed via --target
ISSUE_NUMBER=""
MAX_CI_ITER=3
MAX_REVIEW_ITER=3
DRY_RUN=false

# Parse optional flags
shift 2>/dev/null || true
while [[ $# -gt 0 ]]; do
  case "${1}" in
    --target)      TARGET="${2}";           shift 2 ;;
    --issue)       ISSUE_NUMBER="${2}";     shift 2 ;;
    --repo)        GH_REPO="${2}"; GH_FLAG="-R $GH_REPO"; shift 2 ;;
    --max-ci-iterations)     MAX_CI_ITER="${2}";     shift 2 ;;
    --max-review-iterations) MAX_REVIEW_ITER="${2}"; shift 2 ;;
    --dry-run)     DRY_RUN=true;          shift ;;
    *) shift ;;
  esac
done
```

---

## Phase 1: Branch Routing

Determine the PR target from the source branch. If `--target` was passed explicitly, skip the routing table and use it directly.

### Routing Table

| Source Branch Pattern | Target | PR Title Prefix |
|----------------------|--------|-----------------|
| `staging` | `main` (DEFAULT_BRANCH) | `Deploy` |
| `milestone/*` | `staging` (STAGING_BRANCH) | `Ship` |
| Any other branch | `staging` (STAGING_BRANCH) | `Merge` |

```bash
if [ -n "$TARGET" ]; then
  # Explicit override
  PR_TARGET="$TARGET"
  case "$SOURCE" in
    staging)        TITLE_PREFIX="Deploy" ;;
    milestone/*)    TITLE_PREFIX="Ship" ;;
    *)              TITLE_PREFIX="Merge" ;;
  esac
else
  case "$SOURCE" in
    staging)
      PR_TARGET="$DEFAULT_BRANCH"
      TITLE_PREFIX="Deploy"
      ;;
    milestone/*)
      PR_TARGET="$STAGING_BRANCH"
      TITLE_PREFIX="Ship"
      ;;
    *)
      PR_TARGET="$STAGING_BRANCH"
      TITLE_PREFIX="Merge"
      ;;
  esac
fi

echo "Source: $SOURCE → Target: $PR_TARGET (prefix: $TITLE_PREFIX)"
```

**Routing guard — staging→main**: When `SOURCE=staging` and `PR_TARGET=main`, the review gate (Phase 4) MUST route to `Skill("{FORGE_SKILL_PREFIX}review-pr-staging", ...)` rather than the standard `review-pr`. This ensures the staging deploy review (comprehensive, multi-agent) runs instead of the single-PR review.

**Routing guard — milestone→staging**: When `SOURCE` matches `milestone/*`, this is a feature lane ship. `/review-pr` handles these normally (they target staging, not main).

---

## Phase 2: PR Detection / Creation

### 2A: Detect Existing PR

Always check for an open PR before creating one. Never close-and-recreate — always update in place. <!-- Ref: issue #1328 -->

```bash
cd "$REPO_PATH"
git fetch origin "$SOURCE" "$PR_TARGET" 2>/dev/null || true

EXISTING_PR=$(gh pr list $GH_FLAG \
  --head "$SOURCE" \
  --base "$PR_TARGET" \
  --state open \
  --json number,url,title,headRefOid \
  --jq '.[0] // empty' 2>/dev/null)

if [ -n "$EXISTING_PR" ]; then
  PR_NUMBER=$(echo "$EXISTING_PR" | jq -r '.number')
  PR_URL=$(echo "$EXISTING_PR" | jq -r '.url')
  echo "Found existing open PR #${PR_NUMBER}: ${PR_URL}"
  PR_CREATED=false
else
  echo "No existing PR found — creating new PR"
  PR_NUMBER=""
  PR_CREATED=true
fi
```

### 2A.5: Version Sync Pre-flight

Applies ONLY when `SOURCE=$STAGING_BRANCH` and `PR_TARGET=$DEFAULT_BRANCH` (a staging deploy). Skip for every other lane. Publishing bumps the version on the default branch only, so the deploy PR fails the Deploy Version Guard until staging carries that version. The publish workflow normally syncs it; this pre-flight is the safety net when that sync failed. <!-- Added: forge#3695 -->

Rule (same as the publish workflow): sync only when the default branch `package.json` version is strictly ahead of the source branch's. If the source is already at or above it, skip. The sync is a version-only commit (`package.json` and `.claude-plugin/plugin.json`), never a merge of the default branch.

```bash
CONFIG_FILE="${FORGE_CONFIG:-forge.yaml}"
STAGING_BRANCH=$(yq '.branches.staging // "staging"' "$CONFIG_FILE" 2>/dev/null || echo "staging")
DEFAULT_BRANCH=$(yq '.branches.default // "main"' "$CONFIG_FILE" 2>/dev/null || echo "main")
REPO_PATH=$(yq '.paths.root' "$CONFIG_FILE" 2>/dev/null || echo "$(git rev-parse --show-toplevel)")

if [ "$SOURCE" = "$STAGING_BRANCH" ] && [ "$PR_TARGET" = "$DEFAULT_BRANCH" ]; then
  cd "$REPO_PATH"
  git fetch origin "$SOURCE" "$DEFAULT_BRANCH" || { echo "version sync: fetch failed — continuing (version guard will report)"; }
  MAIN_VERSION=$(git show "origin/$DEFAULT_BRANCH:package.json" | node -e "process.stdout.write(JSON.parse(require('fs').readFileSync(0, 'utf8')).version)")
  SRC_VERSION=$(git show "origin/$SOURCE:package.json" | node -e "process.stdout.write(JSON.parse(require('fs').readFileSync(0, 'utf8')).version)")

  # Numeric semver compare in node (never a string compare: 1.10.0 > 1.9.0).
  if MAIN_VERSION="$MAIN_VERSION" SRC_VERSION="$SRC_VERSION" node -e "
    const p = (v) => v.split('.').map(Number);
    const [m, s] = [p(process.env.MAIN_VERSION), p(process.env.SRC_VERSION)];
    for (let i = 0; i < 3; i++) { if (m[i] !== s[i]) process.exit(m[i] > s[i] ? 0 : 1); }
    process.exit(1);
  "; then
    echo "$DEFAULT_BRANCH is at $MAIN_VERSION, ahead of $SOURCE ($SRC_VERSION) — version sync needed"
    if [ "${DRY_RUN:-false}" = "true" ]; then
      echo "[dry-run] would sync version $MAIN_VERSION to $SOURCE"
    else
      SYNC_DIR=$(mktemp -d)
      git worktree add --detach "$SYNC_DIR" "origin/$SOURCE"
      (
        cd "$SYNC_DIR" || exit 1
        VERSION="$MAIN_VERSION" node -e "
          const fs = require('fs');
          for (const f of ['package.json', '.claude-plugin/plugin.json']) {
            const j = JSON.parse(fs.readFileSync(f, 'utf8'));
            j.version = process.env.VERSION;
            fs.writeFileSync(f, JSON.stringify(j, null, 2) + '\\n');
          }
        "
        git add package.json .claude-plugin/plugin.json
        git commit -m "chore: sync version $MAIN_VERSION to $SOURCE"
        if ! git push origin "HEAD:$SOURCE"; then
          # Push rejected (protected branch or race): fall back to a sync PR.
          SYNC_BRANCH="chore/sync-main-into-staging-$MAIN_VERSION"
          git push -f origin "HEAD:refs/heads/$SYNC_BRANCH" \
            && SYNC_PR=$(gh pr create $GH_FLAG --base "$SOURCE" --head "$SYNC_BRANCH" \
                 --title "chore: sync version $MAIN_VERSION to $SOURCE" \
                 --body "Version-only sync so the deploy PR passes the Deploy Version Guard. Generated by deploy-pr 2A.5.") \
            && echo "Opened sync PR $SYNC_PR — wait for CI green and merge (never bypass gating), then re-run"
        fi
      )
      git worktree remove --force "$SYNC_DIR" 2>/dev/null || true
      git fetch origin "$SOURCE" 2>/dev/null || true   # re-fetch before 2B/2C
    fi
  else
    echo "$SOURCE ($SRC_VERSION) is at or above $DEFAULT_BRANCH ($MAIN_VERSION) — no version sync needed"
  fi
fi
```

If a sync PR was opened instead of a direct push, wait for it to pass CI and merge through the normal gates before continuing to 2B; do not create or update the deploy PR against a stale source version. Phase 2B onward and the `PR_NUMBER` handoff are unchanged.

### 2B: Gather Commit Summary (for new PR body)

Skip if PR already exists.

```bash
if [ "$PR_CREATED" = "true" ]; then
  # Commits on source that are not yet on target
  COMMIT_LOG=$(git log --oneline "origin/${PR_TARGET}..origin/${SOURCE}" --format="%h %s" 2>/dev/null | head -30)
  COMMIT_COUNT=$(git rev-list --count "origin/${PR_TARGET}..origin/${SOURCE}" 2>/dev/null || echo "0")

  if [ "$COMMIT_COUNT" -eq 0 ]; then
    echo "DEPLOY_RESULT: status=NOTHING_TO_DEPLOY source=$SOURCE target=$PR_TARGET"
    echo "{ \"pr\": null, \"source\": \"$SOURCE\", \"target\": \"$PR_TARGET\", \"status\": \"nothing_to_deploy\", \"ci_fixes\": 0, \"review_findings\": 0 }"
    exit 0
  fi

  # Extract issue references from commit messages
  ISSUE_REFS=$(echo "$COMMIT_LOG" | grep -oE '#[0-9]+' | sort -u | head -20 | tr '\n' ' ')

  # Build issue ref block
  if [ -n "$ISSUE_NUMBER" ]; then
    CLOSES_LINE="Closes #${ISSUE_NUMBER}"
  else
    CLOSES_LINE="<!-- No parent issue specified -->"
  fi

  PR_BODY="## Summary

${TITLE_PREFIX}: \`${SOURCE}\` → \`${PR_TARGET}\`

**Commits**: ${COMMIT_COUNT}

## Changes

\`\`\`
${COMMIT_LOG}
\`\`\`

## Issue References

${ISSUE_REFS:-None}

---
${CLOSES_LINE}
**Source**: \`${SOURCE}\`
**Target**: \`${PR_TARGET}\`"

  # #4727: a staging -> default deploy PR links the release lane's post-deploy rollup (deterministic; empty = no link, never blocks)
  if [ "$SOURCE" = "$STAGING_BRANCH" ] && [ "$PR_TARGET" = "$DEFAULT_BRANCH" ]; then
    _l="$(readlink -f "$HOME/.claude/commands/work-on.md" 2>/dev/null || true)"; _l="${_l%/commands/work-on.md}"
    ROLLUP_LINK=""
    for _c in '${CLAUDE_PLUGIN_ROOT}' "${FORGE_ROOT:-}" "${FORGEDOCK_HOME:-}" "${FORGE_HOME:-}" "$_l"; do
      case "$_c" in /*) [ -z "$ROLLUP_LINK" ] && [ -f "$_c/scripts/postdeploy-rollup-link.sh" ] && ROLLUP_LINK=$(bash "$_c/scripts/postdeploy-rollup-link.sh" --repo "$GH_REPO" 2>/dev/null || true) ;; esac
    done
    [ -n "$ROLLUP_LINK" ] && PR_BODY="${PR_BODY}

${ROLLUP_LINK}"
  fi
fi
```

### 2C: Create PR (if needed)

```bash
if [ "$PR_CREATED" = "true" ] && [ "$DRY_RUN" = "false" ]; then
  # Determine PR title
  PR_TITLE="${TITLE_PREFIX}: ${SOURCE} → ${PR_TARGET} (${COMMIT_COUNT} commits)"

  # Route to correct review spec — staging→main PRs use review-pr-staging conventions
  if [ "$SOURCE" = "$STAGING_BRANCH" ] && [ "$PR_TARGET" = "$DEFAULT_BRANCH" ]; then
    PR_TITLE="${TITLE_PREFIX}: Deploy staging → main (${COMMIT_COUNT} commits)"
  fi

  PR_URL=$(gh pr create $GH_FLAG \
    --head "$SOURCE" \
    --base "$PR_TARGET" \
    --title "$PR_TITLE" \
    --body "$PR_BODY" 2>&1)

  if echo "$PR_URL" | grep -qE '^https://'; then
    PR_NUMBER=$(echo "$PR_URL" | grep -oE '/pull/[0-9]+' | grep -oE '[0-9]+' | tail -1)
    echo "Created PR #${PR_NUMBER}: ${PR_URL}"
  else
    echo "ERROR: PR creation failed:"
    echo "$PR_URL"
    echo "{ \"pr\": null, \"source\": \"$SOURCE\", \"target\": \"$PR_TARGET\", \"status\": \"pr_creation_failed\", \"ci_fixes\": 0, \"review_findings\": 0 }"
    exit 1
  fi

elif [ "$DRY_RUN" = "true" ] && [ "$PR_CREATED" = "true" ]; then
  echo "[DRY-RUN] Would create PR: ${TITLE_PREFIX}: ${SOURCE} → ${PR_TARGET} (${COMMIT_COUNT} commits)"
  echo "[DRY-RUN] PR body would include ${COMMIT_COUNT} commits and issue refs: ${ISSUE_REFS}"
  PR_NUMBER="DRY_RUN"
fi
```

**State after Phase 2**: `PR_NUMBER` is set (either detected or created).

---

## Phase 3: CI Gate

Invoke `/fix-ci` to handle CI failures. Loop until green or max iterations reached.

**Graceful degradation**: If `/fix-ci` is not available (not yet installed — issue #1675 is its companion), skip this phase with a warning. The review gate in Phase 4 will still run, and a failing CI will block the merge at the review stage.

```bash
CI_FIXES=0
CI_GATE_PASSED=false
CI_ITER=0

# Check if fix-ci is available
FIX_CI_AVAILABLE=$(ls ~/.claude/commands/fix-ci.md 2>/dev/null && echo "true" || echo "false")

if [ "$FIX_CI_AVAILABLE" = "false" ]; then
  echo "WARNING: /fix-ci not available — skipping CI gate. Install fix-ci (issue #1675) for automated CI fixing."
  echo "CI fix loop: SKIPPED (fix-ci unavailable) — the Phase 5 CI gate still blocks a red merge"
  CI_GATE_PASSED=true  # the fix loop is skipped, not the gate: Phase 5 runs wait-ci-green.sh before merging
else
  # Check current CI status
  # Fail closed: valid fields only (`status`/`conclusion` do not exist on gh pr checks --json; the
  # old query errored and defaulted to 0 = "no failures"). An unreadable result counts as failing.
  # forgedock/verify (the lean engine's report-only gate summary) is not a code failure: ignored, as wait-ci-green.sh does.
  # forge/deploy-gate and "Check for FORGE gate markers" (the staging review's marker status and its workflow job) are not fixable by /fix-ci: ignored here, still waited on in Phase 5.
  # A still-running check is not passed (#5277): the reads below count fail, cancel and pending. When nothing has failed yet and
  # checks are only unfinished, this phase reports PENDING and leaves the wait to Phase 5 (wait-ci-green.sh); never PASSED.
  CI_PENDING=false
  ci_only_pending() {
    gh pr checks "$PR_NUMBER" $GH_FLAG --json name,bucket \
      --jq '[.[] | select(.name != "forgedock/verify" and .name != "forge/deploy-gate" and .name != "Check for FORGE gate markers") | select(.bucket == "fail" or .bucket == "cancel")] | length' 2>/dev/null | grep -qx 0
  }
  CURRENT_CI_STATUS=$(gh pr checks "$PR_NUMBER" $GH_FLAG --json name,bucket \
    --jq '[.[] | select(.name != "forgedock/verify" and .name != "forge/deploy-gate" and .name != "Check for FORGE gate markers") | select(.bucket == "fail" or .bucket == "cancel" or .bucket == "pending")] | length' 2>/dev/null || echo "1")

  if [ "$CURRENT_CI_STATUS" -eq 0 ]; then
    echo "CI gate: PASSED (no failing checks)"
    CI_GATE_PASSED=true
  elif ci_only_pending; then
    echo "CI gate: PENDING ($CURRENT_CI_STATUS check(s) unfinished, none failed) — deferred to Phase 5 (wait-ci-green.sh)"
    CI_PENDING=true
    CI_GATE_PASSED=true
  else
    echo "CI has $CURRENT_CI_STATUS failing checks — invoking /fix-ci (max $MAX_CI_ITER iterations)"

    while [ "$CI_ITER" -lt "$MAX_CI_ITER" ] && [ "$CI_GATE_PASSED" = "false" ]; do
      CI_ITER=$((CI_ITER + 1))
      echo "=== CI Gate Iteration $CI_ITER / $MAX_CI_ITER ==="

      if [ "$DRY_RUN" = "false" ]; then
        Skill("{FORGE_SKILL_PREFIX}fix-ci", args="$PR_NUMBER $GH_FLAG")
      else
        echo "[DRY-RUN] Would invoke: Skill(fix-ci, $PR_NUMBER $GH_FLAG)"
      fi

      CI_FIXES=$((CI_FIXES + 1))

      # Re-check CI status after fix attempt (same fail-closed query as above)
      FAILING_AFTER=$(gh pr checks "$PR_NUMBER" $GH_FLAG --json name,bucket \
        --jq '[.[] | select(.name != "forgedock/verify" and .name != "forge/deploy-gate" and .name != "Check for FORGE gate markers") | select(.bucket == "fail" or .bucket == "cancel" or .bucket == "pending")] | length' 2>/dev/null || echo "1")

      if [ "$FAILING_AFTER" -eq 0 ]; then
        echo "CI gate: PASSED after $CI_ITER iteration(s)"
        CI_GATE_PASSED=true
      elif ci_only_pending; then
        echo "CI gate: PENDING after $CI_ITER iteration(s) ($FAILING_AFTER check(s) unfinished, none failed) — deferred to Phase 5 (wait-ci-green.sh)"
        CI_PENDING=true
        CI_GATE_PASSED=true
      else
        echo "CI still has $FAILING_AFTER failing checks after iteration $CI_ITER"
      fi
    done

    if [ "$CI_GATE_PASSED" = "false" ]; then
      echo "CI gate: FAILED — still failing after $MAX_CI_ITER fix iteration(s). NOT merging."
      echo "{ \"pr\": $PR_NUMBER, \"source\": \"$SOURCE\", \"target\": \"$PR_TARGET\", \"status\": \"ci_failed\", \"ci_fixes\": $CI_FIXES, \"review_findings\": 0 }"
      exit 1
    fi
  fi
fi

# Emit gate state marker for auditability <!-- Ref: issue #1582 — gate passes must be auditable -->
if [ "$DRY_RUN" = "false" ] && [ -n "$PR_NUMBER" ] && [ "$PR_NUMBER" != "DRY_RUN" ]; then
  gh pr comment "$PR_NUMBER" $GH_FLAG --body "<!-- FORGE:GATE_PASS phase=ci iterations=${CI_ITER} fixes=${CI_FIXES} pending=${CI_PENDING:-false} -->" 2>/dev/null || true
fi
```

---

## Phase 4: Review Gate

Invoke `/review-pr` for the PR. Route staging→main PRs to the staging review spec.

**On rejection**: Callers (e.g., /autopilot) are expected to push a fix commit to the source branch before this command is re-invoked. The re-review loop here handles only the re-review after a fix is already pushed — it does NOT fix code itself.

```bash
REVIEW_FINDINGS=0
REVIEW_GATE_PASSED=false
REVIEW_ITER=0

while [ "$REVIEW_ITER" -lt "$MAX_REVIEW_ITER" ] && [ "$REVIEW_GATE_PASSED" = "false" ]; do
  REVIEW_ITER=$((REVIEW_ITER + 1))
  echo "=== Review Gate Iteration $REVIEW_ITER / $MAX_REVIEW_ITER ==="

  if [ "$DRY_RUN" = "false" ]; then
    # Route: staging→main uses review-pr-staging; all other uses standard review-pr
    if [ "$SOURCE" = "$STAGING_BRANCH" ] && [ "$PR_TARGET" = "$DEFAULT_BRANCH" ]; then
      REVIEW_RESULT=$(Skill("{FORGE_SKILL_PREFIX}review-pr-staging", args="$PR_NUMBER $GH_FLAG"))
    else
      REVIEW_RESULT=$(Skill("{FORGE_SKILL_PREFIX}review-pr", args="$PR_NUMBER $GH_FLAG"))
    fi
  else
    echo "[DRY-RUN] Would invoke review-pr for PR #$PR_NUMBER"
    REVIEW_RESULT="DRY_RUN_APPROVED"
  fi

  # Extract verdict from review result
  # Review-pr posts <!-- FORGE:REVIEW --> comment on the PR — read it
  if [ "$DRY_RUN" = "false" ]; then
    REVIEW_VERDICT=$(gh api "repos/${GH_REPO}/issues/${PR_NUMBER}/comments" \
      --jq '[.[] | select(.body | contains("FORGE:REVIEW"))] | last | .body' 2>/dev/null \
      | grep -oE 'APPROVED|CHANGES REQUESTED' | head -1 || echo "")
    FINDINGS_THIS_ROUND=$(gh api "repos/${GH_REPO}/issues/${PR_NUMBER}/comments" \
      --jq '[.[] | select(.body | contains("FORGE:REVIEW"))] | last | .body' 2>/dev/null \
      | grep -oE '[0-9]+ finding' | grep -oE '[0-9]+' | head -1 || echo "0")
    REVIEW_FINDINGS=$((REVIEW_FINDINGS + ${FINDINGS_THIS_ROUND:-0}))
  else
    REVIEW_VERDICT="APPROVED"
  fi

  if [ "$REVIEW_VERDICT" = "APPROVED" ]; then
    echo "Review gate: APPROVED after $REVIEW_ITER iteration(s)"
    REVIEW_GATE_PASSED=true
  elif [ "$REVIEW_VERDICT" = "CHANGES REQUESTED" ]; then
    echo "Review gate: CHANGES REQUESTED (iteration $REVIEW_ITER / $MAX_REVIEW_ITER)"
    if [ "$REVIEW_ITER" -lt "$MAX_REVIEW_ITER" ]; then
      echo "Waiting for caller to push a fix commit, then re-reviewing..."
      echo "NOTE: /deploy-pr does not fix code itself. Push fix commits to $SOURCE and re-invoke, or allow the max-review-iterations loop to exhaust."
      # In an autonomous context (e.g., /autopilot), the caller pushes the fix.
      # In manual context, the operator pushes the fix and re-invokes /deploy-pr.
      # This loop's next iteration will re-read the latest PR state.
    fi
  else
    # Fail-closed: unknown verdict must block merge, not grant it.
    # If FORGE:REVIEW comment is missing, malformed, or unparseable for any reason
    # (race condition, context compaction, skill error, comment format mismatch),
    # treat it as a failed review — REVIEW_GATE_PASSED remains false.
    echo "ERROR: Could not determine review verdict from FORGE:REVIEW comment. Blocking merge — review verdict is required. (#1714)"
  fi
done

if [ "$REVIEW_GATE_PASSED" = "false" ]; then
  echo "Review gate: FAILED — changes requested after $MAX_REVIEW_ITER review iteration(s). NOT merging."
  echo "{ \"pr\": $PR_NUMBER, \"source\": \"$SOURCE\", \"target\": \"$PR_TARGET\", \"status\": \"review_failed\", \"ci_fixes\": $CI_FIXES, \"review_findings\": $REVIEW_FINDINGS }"
  exit 1
fi

# Emit review gate state marker for auditability
if [ "$DRY_RUN" = "false" ] && [ -n "$PR_NUMBER" ] && [ "$PR_NUMBER" != "DRY_RUN" ]; then
  gh pr comment "$PR_NUMBER" $GH_FLAG --body "<!-- FORGE:GATE_PASS phase=review iterations=${REVIEW_ITER} findings=${REVIEW_FINDINGS} -->" 2>/dev/null || true
fi
```

---

## Phase 5: Merge

Both CI and review gates have passed. Merge the PR.

**Never force-merges.** If merge fails, report and stop.

```bash
if [ "$DRY_RUN" = "true" ]; then
  echo "[DRY-RUN] Would merge PR #$PR_NUMBER (${SOURCE} → ${PR_TARGET})"
  MERGE_STATUS="dry_run"
else
  # CI gate (MANDATORY before any autonomous merge): wait for every check, merge only if all are
  # green, and merge exactly the commit the gate checked.
  _l="$(readlink -f "$HOME/.claude/commands/work-on.md" 2>/dev/null || true)"; _l="${_l%/commands/work-on.md}"
  CI_GATE_SCRIPT=""
  for _c in '${CLAUDE_PLUGIN_ROOT}' "${FORGE_ROOT:-}" "${FORGEDOCK_HOME:-}" "${FORGE_HOME:-}" "$_l"; do
    case "$_c" in /*) [ -z "$CI_GATE_SCRIPT" ] && [ -f "$_c/scripts/wait-ci-green.sh" ] && CI_GATE_SCRIPT="$_c/scripts/wait-ci-green.sh" ;; esac
  done
  if [ -n "$CI_GATE_SCRIPT" ]; then CI_GATE_OUT=$(bash "$CI_GATE_SCRIPT" "$PR_NUMBER" $GH_FLAG); CI_GATE_RC=$?
  else CI_GATE_OUT="CI_GATE: ERROR — scripts/wait-ci-green.sh not resolvable (fail closed)"; CI_GATE_RC=2; fi
  echo "$CI_GATE_OUT"
  GATED_HEAD=$(printf '%s\n' "$CI_GATE_OUT" | sed -n 's/^CI_GATE_HEAD: //p' | head -1)
  # rc 3 = CI still running: re-run this block (up to 3 more times) before treating it as a failure.
  if [ "$CI_GATE_RC" -ne 0 ]; then
    MERGE_OUTPUT="not merged: CI gate rc=${CI_GATE_RC}"; MERGE_EXIT=1
  else
    echo "Merging PR #$PR_NUMBER..."
    MERGE_OUTPUT=$(gh pr merge "$PR_NUMBER" $GH_FLAG --merge --match-head-commit "$GATED_HEAD" 2>&1)
    MERGE_EXIT=$?
  fi

  if [ "$MERGE_EXIT" -eq 0 ]; then
    echo "Merged PR #$PR_NUMBER successfully"
    MERGE_STATUS="merged"
  else
    echo "ERROR: Merge failed:"
    echo "$MERGE_OUTPUT"
    echo "{ \"pr\": $PR_NUMBER, \"source\": \"$SOURCE\", \"target\": \"$PR_TARGET\", \"status\": \"merge_failed\", \"ci_fixes\": $CI_FIXES, \"review_findings\": $REVIEW_FINDINGS }"
    exit 1
  fi
fi
```

---

## Phase 6: Report Structured Result

Return a machine-readable result for callers. This structured block is the primary output consumed by `/autopilot` and other callers.

```bash
echo ""
echo "=== /deploy-pr Complete ==="
echo ""
echo "DEPLOY_RESULT: pr=$PR_NUMBER source=$SOURCE target=$PR_TARGET status=$MERGE_STATUS ci_fixes=$CI_FIXES review_findings=$REVIEW_FINDINGS"
echo ""

# Machine-readable JSON result (consumed by callers)
cat <<JSON
{
  "pr": ${PR_NUMBER:-null},
  "source": "${SOURCE}",
  "target": "${PR_TARGET}",
  "status": "${MERGE_STATUS}",
  "ci_fixes": ${CI_FIXES},
  "review_findings": ${REVIEW_FINDINGS},
  "ci_gate": "$([ $CI_GATE_PASSED = true ] && echo passed || echo failed)",
  "review_gate": "$([ $REVIEW_GATE_PASSED = true ] && echo passed || echo failed)",
  "iterations": {
    "ci": ${CI_ITER},
    "review": ${REVIEW_ITER}
  }
}
JSON
```

---

## Error Reference

| Exit Condition | Status Field | Action |
|---------------|-------------|--------|
| No commits to deploy | `nothing_to_deploy` | No PR created — exit 0 |
| PR creation failed | `pr_creation_failed` | Check gh auth and branch existence |
| CI failed after max iterations | `ci_failed` | Check failing CI job logs; fix manually |
| Review failed after max iterations | `review_failed` | Address review findings; re-invoke |
| Merge failed | `merge_failed` | Check merge conflicts; may need manual resolution |

**`needs-human` pattern**: When any exit condition produces a non-zero exit, callers (like `/autopilot`) should add a `needs-human` label to the parent issue and stop autonomous iteration for this branch.
