Business operating system for Claude Code — 57 skills, 21 agents, smart daemon. Unified inbox (WhatsApp/Email/Slack/Telegram), autonomous PR merge, full-AWS monitoring, revenue (Stripe+RevenueCat), e-commerce (Shopify), marketing (Klaviyo/Meta/GA4), voice (Bland/ElevenLabs), APM (Datadog/NewRelic/OTEL), YOLO mode.
Shell agent-teamsai-agentai-automationanthropicautonomous-agentawsbusiness-operationsclaudeclaude-codeclaude-code-plugindevopsecommerceinbox-zeroklaviyomarketingmcpmorning-briefingpr-automationshopifyterminal
feat(ops-release): sweep open PRs before cutting a release (#992)
Aurora Capital55efa17429cc
diff --git a/claude-ops/CHANGELOG.md b/claude-ops/CHANGELOG.mdindex d6d6f0cc..e10c33b3 100644--- a/claude-ops/CHANGELOG.md+++ b/claude-ops/CHANGELOG.md@@ -2,6 +2,30 @@## Unreleased+### Added+- `ops-release` now sweeps open pull requests before it cuts anything. Twice in+ one day a release went out while reviewed, good external PRs sat open, and+ both had to be merged by hand and the release re-cut. The new stage runs+ before the version bump, so the changelog and tag cover everything that+ landed. For every open PR against `main` — drafts and fork PRs included — it+ classifies the PR, approves workflow runs that GitHub is holding at+ `action_required`, dispatches one background review agent per PR (all of them+ together, so independent PRs are reviewed in parallel), and merges only what+ the agent blessed and the required checks report green. `skipped`, `neutral`+ and `cancelled` are not failures; `failure`, `timed_out`, `action_required`+ and `error` are. Anything the agent would not clearly bless, anything still+ red, still draft, or in conflict is reported and left open, and the release+ proceeds without it. The stage is on by default, `--no-sweep` skips it, and+ `--sweep-only` runs the sweep and stops. `--dry-run` never sweeps, since a+ sweep merges for real.++### Fixed+- A pull request from a fork looked permanently blocked. GitHub holds a fork's+ workflow runs at `action_required` until a maintainer approves them, so the+ required checks never started and `mergeable_state` stayed `blocked` forever.+ The sweep approves those held runs, which is what unblocked both stalled+ external contributions.+## [3.10.19] - 2026-09-16### Addeddiff --git a/claude-ops/bin/ops-release b/claude-ops/bin/ops-releaseindex d9e1c348..82681dbf 100755--- a/claude-ops/bin/ops-release+++ b/claude-ops/bin/ops-release@@ -18,8 +18,15 @@# 6. GitHub wiki counts/version synced + a Release-Notes entry# pushed after merge (--no-wiki)#+# Before any of that it runs the PR sweep (--no-sweep to skip): every open PR+# against main — drafts and fork PRs included — is classified, has its held fork+# workflow runs approved, is reviewed by a background agent that may undraft it+# and fix its checks, and is merged only when the agent blessed it AND every+# required check is green. Anything else is reported and left open, and the+# release is cut without it. See scripts/lib/release-pr-sweep.sh.+## Flow:-# fetch → isolated worktree off origin/main → bump version files → AI changelog+# sweep open PRs → fetch → isolated worktree off origin/main → bump version files → AI changelog# → ops-sync-docs → commit → push → PR to main → (optional) wait for CI + squash-merge# → (optional) tag vX.Y.Z → (optional) wiki sync#@@ -27,6 +34,7 @@# ops-release [--type patch|minor|major] [--version X.Y.Z]# [--notes "markdown body for the changelog"]# [--no-ai] [--no-docs] [--no-wiki]+# [--no-sweep] [--sweep-only]# [--no-merge] [--no-tag] [--dry-run] [-h|--help]## Defaults: --type patch, doc-count sync, auto squash-merge, tag, and wiki@@ -39,6 +47,8 @@# ops-release --notes "..." # hand-written fallback when Unreleased is empty# ops-release --no-ai --no-wiki # commit-subject changelog, no wiki push# ops-release --no-merge # open the PR, leave it for review+# ops-release --no-sweep # cut the release without sweeping open PRs+# ops-release --sweep-only # sweep open PRs and stop; cut nothing# ops-release --dry-run # show what would change (incl. AI changelog), touch nothing## After a release lands, refresh the local install:@@ -57,6 +67,10 @@ PLUGIN_NAME="ops" # name in marketplace.json .GH_REPO="Lifecycle-Innovations-Limited/claude-ops"# shellcheck source=../scripts/lib/release-changelog.sh. "$PLUGIN_DIR/scripts/lib/release-changelog.sh"+# shellcheck source=../scripts/lib/release-pr-sweep.sh+. "$PLUGIN_DIR/scripts/lib/release-pr-sweep.sh"+# shellcheck source=../scripts/lib/claude-invoke.sh+. "$PLUGIN_DIR/scripts/lib/claude-invoke.sh" 2>/dev/null || true# package.json may live under claude-ops/ (current layout) or at the repo root.# Record its path RELATIVE to the repo root so we can reapply it inside a worktree.@@ -66,9 +80,11 @@ for cand in "claude-ops/package.json" "package.json"; dodonebump_type="patch"; explicit_ver=""; notes=""; do_merge=1; do_tag=1; dry_run=0-do_ai=1; do_docs=1; do_wiki=1+do_ai=1; do_docs=1; do_wiki=1; do_sweep=1; sweep_only=0while [ $# -gt 0 ]; docase "$1" in+ --no-sweep) do_sweep=0; shift ;;+ --sweep-only) sweep_only=1; shift ;;--type) bump_type="$2"; shift 2 ;;--version) explicit_ver="$2"; shift 2 ;;--notes) notes="$2"; shift 2 ;;@@ -78,7 +94,7 @@ while [ $# -gt 0 ]; do--no-docs) do_docs=0; shift ;;--no-wiki) do_wiki=0; shift ;;--dry-run) dry_run=1; shift ;;- -h|--help) sed -n '2,43p' "$0"; exit 0 ;;+ -h|--help) sed -n '2,52p' "$0"; exit 0 ;;*) echo "ops-release: unknown arg '$1'" >&2; exit 2 ;;esacdone@@ -241,6 +257,22 @@ wait_for_release_ci() {return 1}+# ----- pre-release PR sweep -----+# Land everything that can land BEFORE the bump, so the changelog and the tag+# cover it. A PR that cannot be made good and green is reported and left open;+# the release goes ahead without it. Merging something bad is far worse than+# skipping it, so anything short of a clear yes is a skip.+if [ "$do_sweep" -eq 1 ] && [ "$dry_run" -eq 0 ]; then+ echo "ops-release: sweeping open pull requests (--no-sweep to skip)…"+ release_pr_sweep "$GH_REPO" || echo "ops-release: sweep did not run — continuing" >&2+elif [ "$do_sweep" -eq 1 ]; then+ echo "ops-release: --dry-run: skipping the PR sweep (it merges for real)"+fi+if [ "$sweep_only" -eq 1 ]; then+ echo "ops-release: --sweep-only: stopping before the version bump"+ exit 0+fi+# ----- version base -----# Bump from what is PUBLISHED, never from whatever this checkout happens to# hold. Running from a stale branch or a feature worktree would otherwise takediff --git a/claude-ops/scripts/lib/release-pr-sweep.sh b/claude-ops/scripts/lib/release-pr-sweep.shnew file mode 100644index 00000000..c374cad0--- /dev/null+++ b/claude-ops/scripts/lib/release-pr-sweep.sh@@ -0,0 +1,413 @@+#!/usr/bin/env bash+# release-pr-sweep.sh — pre-release pull-request sweep for ops-release.+#+# Sourced by bin/ops-release. Runs BEFORE the version bump so that everything+# that can land is already on main when the changelog and tag are cut.+#+# For every OPEN pull request targeting main (drafts and fork PRs included):+#+# 1. Classify — state, draft flag, mergeable, mergeable_state, and the+# check runs for the head sha.+# 2. Unblock — a PR from a fork has its workflow runs held at+# `action_required` until a maintainer approves them. Until+# that happens the required checks never start and+# mergeable_state sits at "blocked" forever. Approve the runs+# so CI can actually report.+# 3. Review — one background agent per PR: read the diff, judge whether it+# is good, undraft it when ready, and fix failing checks.+# Independent PRs get independent agents, dispatched together.+# 4. Merge — only PRs that are BOTH judged good AND fully green on the+# required checks. Anything else is reported and left open;+# the release proceeds without it.+#+# Merge criteria (all must hold):+# - open, targets main, not a draft (after the agent's chance to undraft)+# - no merge conflict (mergeable_state != dirty, mergeable != false)+# - the agent verdict is literally GOOD+# - every required check is present and completed for the head sha+# - no check run concluded failure | timed_out | action_required | error+# (skipped, neutral and cancelled are NOT failures)+#+# Deliberate no-ops — the sweep reports and moves on, never forces:+# - the REST rate budget is low (bail before touching anything)+# - a PR that does not target main+# - a PR the agent did not clearly bless (anything other than GOOD)+# - a PR that stays red, stays draft, or has conflicts+# - a PR whose head sha moved while the sweep was running+#+# GitHub is read over REST (`gh api repos/...`) only. Never `gh pr checks` or+# `gh pr view` (GraphQL), never a poll loop with a short fixed sleep.++# Failure conclusions. Everything else that has completed counts as non-failing.+SWEEP_FAIL_CONCLUSIONS="${SWEEP_FAIL_CONCLUSIONS:-failure timed_out action_required error}"++# Checks that must exist and be finished before a PR may merge.+SWEEP_REQUIRED_CHECKS_DEFAULT='["lint-and-check (ubuntu-latest)","lint-and-check (ubuntu-24.04)","pii-gate","test-suite (ubuntu-latest)","test-suite (ubuntu-24.04)","CodeQL"]'++# REST core calls we refuse to start a sweep below.+SWEEP_RATE_FLOOR="${SWEEP_RATE_FLOOR:-300}"++# Wall clock a single review agent gets.+SWEEP_AGENT_TIMEOUT="${SWEEP_AGENT_TIMEOUT:-900}"++# Upper bound on PRs swept in one run, so a stale backlog cannot burn the budget.+SWEEP_MAX_PRS="${SWEEP_MAX_PRS:-20}"++sweep_log() { echo "ops-release: sweep: $*"; }+sweep_warn() { echo "ops-release: sweep: $*" >&2; }++# Run a command under a wall-clock bound. `timeout` is GNU-only, so fall back to+# python3, which ops-release already requires.+sweep_bounded() {+ local seconds="$1"; shift+ if command -v timeout >/dev/null 2>&1; then+ timeout "$seconds" "$@"+ elif command -v python3 >/dev/null 2>&1; then+ python3 - "$seconds" "$@" <<'PY'+import subprocess, sys+try:+ result = subprocess.run(sys.argv[2:], timeout=float(sys.argv[1]), check=False)+except subprocess.TimeoutExpired:+ raise SystemExit(124)+raise SystemExit(result.returncode)+PY+ else+ "$@"+ fi+}++# --- GitHub reads -------------------------------------------------------------++# Remaining REST core budget. Prints a number; 0 when it cannot be read.+sweep_rate_remaining() {+ gh api /rate_limit --jq '.resources.core.remaining' 2>/dev/null || echo 0+}++# Refuse to start when the budget is thin. A half-finished sweep that dies on a+# 403 mid-merge is worse than one that never ran.+sweep_rate_ok() {+ local remaining+ remaining="$(sweep_rate_remaining)"+ [[ "$remaining" =~ ^[0-9]+$ ]] || remaining=0+ if [ "$remaining" -lt "$SWEEP_RATE_FLOOR" ]; then+ sweep_warn "REST budget is $remaining (floor $SWEEP_RATE_FLOOR) — skipping the sweep"+ return 1+ fi+ sweep_log "REST budget $remaining"+ return 0+}++# Open PRs against main, newest last. Emits a compact JSON array.+sweep_open_prs() {+ local repo="$1"+ gh api "repos/$repo/pulls?state=open&base=main&per_page=100" 2>/dev/null \+ | jq -c '[ .[] | {+ number,+ title,+ draft: (.draft // false),+ head_sha: .head.sha,+ head_label: (.head.label // ""),+ base_ref: (.base.ref // ""),+ fork: ((.head.repo.full_name // "") != (.base.repo.full_name // ""))+ } ]' 2>/dev/null+}++# Single PR, re-read for the fields the list endpoint does not compute.+sweep_pr_detail() {+ local repo="$1" num="$2"+ gh api "repos/$repo/pulls/$num" 2>/dev/null \+ | jq -c '{+ number,+ draft: (.draft // false),+ state,+ head_sha: .head.sha,+ base_ref: (.base.ref // ""),+ mergeable: .mergeable,+ mergeable_state: (.mergeable_state // "unknown")+ }' 2>/dev/null+}++# Check runs for a head sha, normalized to {name, status, conclusion}.+sweep_check_runs() {+ local repo="$1" sha="$2"+ gh api "repos/$repo/commits/$sha/check-runs?per_page=100" 2>/dev/null \+ | jq -c '[ .check_runs[]? | {+ name,+ status,+ conclusion: (.conclusion // "")+ } ]' 2>/dev/null+}++# green | pending | failed, for a normalized check-runs array plus the required list.+# skipped / neutral / cancelled are explicitly NOT failures.+sweep_check_verdict() {+ local runs="$1" required="${2:-$SWEEP_REQUIRED_CHECKS_DEFAULT}"+ jq -r --argjson required "$required" --arg fails "$SWEEP_FAIL_CONCLUSIONS" '+ ($fails | split(" ")) as $bad+ | if any(.[]; .conclusion as $c | $bad | index($c)) then "failed"+ elif (($required - [.[] | select(.status == "completed") | .name]) | length) > 0 then "pending"+ elif any(.[]; .status != "completed") then "pending"+ else "green" end' <<<"$runs" 2>/dev/null || echo "pending"+}++# Names of the checks that are actually failing, for the report.+sweep_failing_names() {+ jq -r --arg fails "$SWEEP_FAIL_CONCLUSIONS" '+ ($fails | split(" ")) as $bad+ | [ .[] | select(.conclusion as $c | $bad | index($c)) | .name ] | join(", ")' <<<"$1" 2>/dev/null+}++# --- Fork CI unblock ----------------------------------------------------------++# A fork PR's workflow runs sit at status=action_required until a maintainer+# approves them, so the required checks never start and mergeable_state stays+# "blocked" forever. This is the defect that stalled two good external PRs.+# Approve every held run for the head sha. Prints how many it approved.+sweep_approve_held_runs() {+ local repo="$1" sha="$2" ids id approved=0+ ids="$(gh api "repos/$repo/actions/runs?head_sha=$sha&per_page=100" 2>/dev/null \+ | jq -r '.workflow_runs[]? | select(.status == "action_required") | .id' 2>/dev/null)" || ids=""+ for id in $ids; do+ if gh api --method POST "repos/$repo/actions/runs/$id/approve" >/dev/null 2>&1; then+ approved=$((approved + 1))+ else+ sweep_warn "could not approve held run $id"+ fi+ done+ printf '%s\n' "$approved"+}++# --- Review agent -------------------------------------------------------------++sweep_agent_prompt() {+ local repo="$1" num="$2" title="$3" draft="$4" verdict="$5" failing="$6"+ cat <<PROMPT+You are reviewing pull request #$num ("$title") on the PUBLIC repository $repo,+ahead of a release that will merge it if, and only if, it is good and green.++Current state: draft=$draft, checks=$verdict${failing:+, failing checks: $failing}++Do this with the gh CLI. Read GitHub over REST ('gh api repos/...') only: the+GraphQL-backed pr-checks and pr-view subcommands are banned here, as is any+tight poll loop around gh.++1. Read the full diff ('gh pr diff $num --repo $repo') and judge whether the+ change is correct, in keeping with the repository's conventions, and safe to+ land unattended.+2. If it is good but still a draft, mark it ready: 'gh pr ready $num --repo $repo'.+3. If required checks are failing, read the failing logs, fix the cause in the+ PR's own branch, and push. Never weaken, delete or skip a check to get green.+ Never merge it yourself, never force-push over someone else's history, and+ never reach for an administrator merge override.+4. The repository is PUBLIC: do not add personal names, email addresses or home+ directory paths to any file.++Then end your reply with exactly one line, on its own:++ SWEEP_VERDICT: GOOD - the change is correct and should be merged+ SWEEP_VERDICT: SKIP - anything else: unsure, risky, out of scope, or you+ could not make it green++If your judgement is not clearly positive, say SKIP. A sweep that merges+something bad is far worse than a sweep that skips it.+PROMPT+}++# Run one review agent. Writes its transcript to $3. Always returns 0 — a dead+# agent is a SKIP, not a failed release.+sweep_run_agent() {+ local repo="$1" pr_json="$2" out="$3"+ local num title draft verdict failing prompt+ num="$(jq -r '.number' <<<"$pr_json")"+ title="$(jq -r '.title // ""' <<<"$pr_json")"+ draft="$(jq -r '.draft' <<<"$pr_json")"+ verdict="$(jq -r '.verdict // "unknown"' <<<"$pr_json")"+ failing="$(jq -r '.failing // ""' <<<"$pr_json")"+ prompt="$(sweep_agent_prompt "$repo" "$num" "$title" "$draft" "$verdict" "$failing")"++ if [ -n "${SWEEP_AGENT_CMD:-}" ]; then+ # Deliberately unquoted: the override is a command line, not one word.+ # shellcheck disable=SC2086+ printf '%s' "$prompt" | sweep_bounded "$SWEEP_AGENT_TIMEOUT" $SWEEP_AGENT_CMD >"$out" 2>/dev/null || true+ return 0+ fi+ if command -v claude_invoke >/dev/null 2>&1; then+ printf '%s' "$prompt" | claude_invoke --no-session-persistence -p >"$out" 2>/dev/null || true+ elif command -v claude >/dev/null 2>&1; then+ printf '%s' "$prompt" | sweep_bounded "$SWEEP_AGENT_TIMEOUT" claude -p >"$out" 2>/dev/null || true+ else+ : >"$out"+ fi+ return 0+}++# GOOD only when the agent said so in the exact agreed form. Silence, a crash,+# an empty transcript or anything ambiguous reads as SKIP.+sweep_agent_verdict() {+ local out="$1"+ [ -s "$out" ] || { echo "SKIP"; return 0; }+ if grep -qE '^[[:space:]]*SWEEP_VERDICT:[[:space:]]*GOOD[[:space:]]*$' "$out"; then+ echo "GOOD"+ else+ echo "SKIP"+ fi+}++# --- Main ---------------------------------------------------------------------++# release_pr_sweep <repo>+# Never returns non-zero for a PR it declined to merge: the release goes ahead+# without it. Returns 1 only when the sweep itself could not run.+release_pr_sweep() {+ local repo="$1"+ local prs count i pr num title draft head_sha base_ref fork detail+ local runs verdict failing approved merged=0 skipped=0+ local workdir pr_file line agent_says detail+ local d_state d_draft d_sha d_mergeable d_mstate+ local agent_jobs=() report=()++ command -v jq >/dev/null 2>&1 || { sweep_warn "jq required"; return 1; }+ sweep_rate_ok || return 1++ prs="$(sweep_open_prs "$repo")" || prs=""+ if ! jq -e 'type == "array"' <<<"${prs:-null}" >/dev/null 2>&1; then+ sweep_warn "could not list open pull requests — skipping the sweep"+ return 1+ fi+ count="$(jq 'length' <<<"$prs")"+ if [ "$count" -eq 0 ]; then+ sweep_log "no open pull requests against main — nothing to sweep"+ return 0+ fi+ if [ "$count" -gt "$SWEEP_MAX_PRS" ]; then+ sweep_warn "$count open PRs exceeds SWEEP_MAX_PRS=$SWEEP_MAX_PRS — sweeping the first $SWEEP_MAX_PRS"+ count="$SWEEP_MAX_PRS"+ fi+ sweep_log "$count open pull request(s) against main"++ workdir="$(mktemp -d)"+ # shellcheck disable=SC2064+ trap "rm -rf '$workdir'" RETURN++ # Pass 1 — classify and unblock fork CI, then dispatch every agent together so+ # independent PRs are reviewed in parallel.+ for ((i = 0; i < count; i++)); do+ pr="$(jq -c ".[$i]" <<<"$prs")"+ num="$(jq -r '.number' <<<"$pr")"+ title="$(jq -r '.title' <<<"$pr")"+ draft="$(jq -r '.draft' <<<"$pr")"+ head_sha="$(jq -r '.head_sha' <<<"$pr")"+ base_ref="$(jq -r '.base_ref' <<<"$pr")"+ fork="$(jq -r '.fork' <<<"$pr")"++ if [ "$base_ref" != "main" ]; then+ report+=("#$num skipped: targets $base_ref, not main")+ skipped=$((skipped + 1))+ continue+ fi++ runs="$(sweep_check_runs "$repo" "$head_sha")"+ [ -n "$runs" ] || runs='[]'+ verdict="$(sweep_check_verdict "$runs")"++ # The action_required defect: held fork runs mean the required checks never+ # even start. Approve them, then re-read so the agent sees the truth.+ local held=0+ if jq -e 'any(.[]; .conclusion == "action_required" or .status == "action_required")' <<<"$runs" >/dev/null 2>&1; then+ held=1+ fi+ if [ "$fork" = "true" ]; then held=1; fi+ if [ "$held" -eq 1 ]; then+ approved="$(sweep_approve_held_runs "$repo" "$head_sha")"+ if [ "${approved:-0}" -gt 0 ]; then+ sweep_log "#$num: approved $approved held workflow run(s) (fork CI was waiting on a maintainer)"+ runs="$(sweep_check_runs "$repo" "$head_sha")"+ [ -n "$runs" ] || runs='[]'+ verdict="$(sweep_check_verdict "$runs")"+ fi+ fi++ failing="$(sweep_failing_names "$runs")"+ sweep_log "#$num draft=$draft fork=$fork checks=$verdict${failing:+ failing=$failing}"++ printf '%s' "$(jq -c -n --argjson pr "$pr" --arg v "$verdict" --arg f "$failing" \+ '$pr + {verdict: $v, failing: $f}')" >"$workdir/$num.pr.json"+ sweep_run_agent "$repo" "$(cat "$workdir/$num.pr.json")" "$workdir/$num.agent.txt" &+ agent_jobs+=("$!")+ done++ # Independent PRs, independent agents, all in flight at once.+ # (Guarded: bash 3.2 treats an empty array as unbound under `set -u`.)+ if [ "${#agent_jobs[@]}" -gt 0 ]; then+ for i in "${agent_jobs[@]}"; do wait "$i" 2>/dev/null || true; done+ fi++ # Pass 2 — re-read every PR after the agents have had their say, then merge+ # only what is both good and green.+ for pr_file in "$workdir"/*.pr.json; do+ [ -f "$pr_file" ] || continue+ pr="$(cat "$pr_file")"+ num="$(jq -r '.number' <<<"$pr")"+ head_sha="$(jq -r '.head_sha' <<<"$pr")"+ local agent_says+ agent_says="$(sweep_agent_verdict "$workdir/$num.agent.txt")"++ if [ "$agent_says" != "GOOD" ]; then+ report+=("#$num left open: the review agent did not bless it (verdict $agent_says)")+ skipped=$((skipped + 1))+ continue+ fi++ detail="$(sweep_pr_detail "$repo" "$num")"+ if ! jq -e '.number' <<<"${detail:-null}" >/dev/null 2>&1; then+ report+=("#$num left open: could not re-read the PR after review")+ skipped=$((skipped + 1))+ continue+ fi+ local d_state d_draft d_sha d_mergeable d_mstate+ d_state="$(jq -r '.state' <<<"$detail")"+ d_draft="$(jq -r '.draft' <<<"$detail")"+ d_sha="$(jq -r '.head_sha' <<<"$detail")"+ d_mergeable="$(jq -r '.mergeable' <<<"$detail")"+ d_mstate="$(jq -r '.mergeable_state' <<<"$detail")"++ if [ "$d_state" != "open" ]; then+ report+=("#$num skipped: no longer open ($d_state)")+ skipped=$((skipped + 1)); continue+ fi+ if [ "$d_draft" = "true" ]; then+ report+=("#$num left open: still a draft after review")+ skipped=$((skipped + 1)); continue+ fi+ if [ "$d_mergeable" = "false" ] || [ "$d_mstate" = "dirty" ]; then+ report+=("#$num left open: merge conflict with main")+ skipped=$((skipped + 1)); continue+ fi++ runs="$(sweep_check_runs "$repo" "$d_sha")"+ [ -n "$runs" ] || runs='[]'+ verdict="$(sweep_check_verdict "$runs")"+ if [ "$verdict" != "green" ]; then+ failing="$(sweep_failing_names "$runs")"+ report+=("#$num left open: checks are $verdict${failing:+ ($failing)}")+ skipped=$((skipped + 1)); continue+ fi++ # Bind the merge to the sha we actually judged. Never --admin, never force.+ if gh pr merge "$num" --repo "$repo" --squash --delete-branch \+ --match-head-commit "$d_sha" >/dev/null 2>&1; then+ sweep_log "#$num merged (good + green on $d_sha)"+ report+=("#$num merged")+ merged=$((merged + 1))+ else+ report+=("#$num left open: merge was refused (protection, or the head moved)")+ skipped=$((skipped + 1))+ fi+ done++ sweep_log "merged $merged, left open $skipped"+ if [ "${#report[@]}" -gt 0 ]; then+ for line in "${report[@]}"; do sweep_log " $line"; done+ fi+ return 0+}diff --git a/claude-ops/tests/mocks/gh b/claude-ops/tests/mocks/ghindex 2abfa176..c60b50ed 100755--- a/claude-ops/tests/mocks/gh+++ b/claude-ops/tests/mocks/gh@@ -45,6 +45,51 @@ case "$sub" infi}+ # ---- ops-release PR sweep fixtures -------------------------------------+ # Only active when MOCK_GH_SWEEP_DIR points at a fixture directory, so no+ # existing suite changes behaviour. Files served, all optional:+ # pulls.json GET repos/*/pulls?state=open&base=main+ # pr-<n>.json GET repos/*/pulls/<n>+ # checkruns-<sha>.json GET repos/*/commits/<sha>/check-runs+ # checkruns-<sha>.after.json same, served once <sha> has had a run approved+ # runs-<sha>.json GET repos/*/actions/runs?head_sha=<sha>+ # Approving a run writes approved-<sha> and appends to approvals.log.+ if [ -n "${MOCK_GH_SWEEP_DIR:-}" ]; then+ _bare="${path%%\?*}"+ case "$_bare" in+ */actions/runs/*/approve)+ _rest="${_bare#*/actions/runs/}"; _rid="${_rest%%/*}"+ echo "approve $_rid" >> "$MOCK_GH_SWEEP_DIR/approvals.log"+ _sha="$(cat "$MOCK_GH_SWEEP_DIR/run-$_rid.sha" 2>/dev/null || true)"+ [ -n "$_sha" ] && : > "$MOCK_GH_SWEEP_DIR/approved-$_sha"+ exit "${MOCK_GH_SWEEP_APPROVE_RC:-0}"+ ;;+ */actions/runs)+ _sha="${path##*head_sha=}"; _sha="${_sha%%&*}"+ emit "$(cat "$MOCK_GH_SWEEP_DIR/runs-$_sha.json" 2>/dev/null || echo '{"workflow_runs":[]}')"+ exit 0+ ;;+ */check-runs)+ _sha="${_bare%/check-runs}"; _sha="${_sha##*/}"+ _f="$MOCK_GH_SWEEP_DIR/checkruns-$_sha.json"+ if [ -f "$MOCK_GH_SWEEP_DIR/approved-$_sha" ] && [ -f "$MOCK_GH_SWEEP_DIR/checkruns-$_sha.after.json" ]; then+ _f="$MOCK_GH_SWEEP_DIR/checkruns-$_sha.after.json"+ fi+ emit "$(cat "$_f" 2>/dev/null || echo '{"check_runs":[]}')"+ exit 0+ ;;+ */pulls)+ emit "$(cat "$MOCK_GH_SWEEP_DIR/pulls.json" 2>/dev/null || echo '[]')"+ exit 0+ ;;+ */pulls/[0-9]*)+ _n="${_bare##*/}"+ emit "$(cat "$MOCK_GH_SWEEP_DIR/pr-$_n.json" 2>/dev/null || echo '{}')"+ exit 0+ ;;+ esac+ fi+case "$path" inrate_limit|/rate_limit)# MOCK_GH_RATE_DROP_AFTER lets a test keep the bucket healthy for the@@ -109,6 +154,19 @@ case "$sub" inecho "${MOCK_GH_PR_VIEW_JSON:-$_default}"exit 0;;+ merge)+ # Sweep tests: record the merge (number + argv) and honour a forced rc.+ if [ -n "${MOCK_GH_SWEEP_DIR:-}" ]; then+ echo "merge $*" >> "$MOCK_GH_SWEEP_DIR/merges.log"+ fi+ exit "${MOCK_GH_PR_MERGE_RC:-0}"+ ;;+ ready)+ if [ -n "${MOCK_GH_SWEEP_DIR:-}" ]; then+ echo "ready $*" >> "$MOCK_GH_SWEEP_DIR/ready.log"+ fi+ exit 0+ ;;esac;;secret)diff --git a/claude-ops/tests/run-all.sh b/claude-ops/tests/run-all.shindex bb5ed0d5..70a5c85e 100755--- a/claude-ops/tests/run-all.sh+++ b/claude-ops/tests/run-all.sh@@ -91,6 +91,7 @@ run_suite "$TESTS_DIR/test-ops-dns-provision.sh"run_suite "$TESTS_DIR/test-ops-marketing-dash-brand-isolation.sh"run_suite "$TESTS_DIR/test-ops-dash-portfolio-counts.sh"run_suite "$TESTS_DIR/test-ops-release-changelog-heading.sh"+run_suite "$TESTS_DIR/test-ops-release-pr-sweep.sh"run_suite "$TESTS_DIR/../templates/statusline/tests/run-tests.sh"run_suite "$TESTS_DIR/test-registry-schema-skills.sh"run_suite "$TESTS_DIR/test-ops-external-registry-classification.sh"diff --git a/claude-ops/tests/test-ops-release-pr-sweep.sh b/claude-ops/tests/test-ops-release-pr-sweep.shnew file mode 100755index 00000000..848a4f24--- /dev/null+++ b/claude-ops/tests/test-ops-release-pr-sweep.sh@@ -0,0 +1,281 @@+#!/usr/bin/env bash+# test-ops-release-pr-sweep.sh — the pre-release pull-request sweep.+#+# Covers the behaviour the sweep exists for:+# - a fork PR whose workflow runs sit at action_required gets them approved+# (the defect that stalled two good external PRs behind checks that never ran)+# - a good, green PR is merged+# - a red PR is left open and reported+# - a good draft is undrafted and then merged+# - skipped / neutral / cancelled are NOT failures+# - a PR the agent did not bless is left open+# - a thin REST budget aborts the sweep instead of half-running it+# - --no-sweep skips the whole stage+#+# `gh` is the repo's own mock, driven by fixture files in MOCK_GH_SWEEP_DIR.+set -uo pipefail++PLUGIN_ROOT="$(cd "$(dirname "$0")/.." && pwd)"+RELEASE="$PLUGIN_ROOT/bin/ops-release"+LIB="$PLUGIN_ROOT/scripts/lib/release-pr-sweep.sh"+MOCKS="$PLUGIN_ROOT/tests/mocks"++pass=0+fail=0+ok() { echo " PASS: $1"; pass=$((pass+1)); }+err() { echo " FAIL: $1"; fail=$((fail+1)); }++echo "Checking: ops-release pre-release PR sweep"+echo ""++# ---- static checks -----------------------------------------------------------++[ -f "$LIB" ] && ok "scripts/lib/release-pr-sweep.sh exists" \+ || { err "scripts/lib/release-pr-sweep.sh missing"; echo "Results: $pass passed, $fail failed"; exit 1; }++bash -n "$LIB" && ok "the sweep library parses" || err "the sweep library has a syntax error"+bash -n "$RELEASE" && ok "bin/ops-release still parses" || err "bin/ops-release has a syntax error"++grep -q -- '--no-sweep)' "$RELEASE" && ok "ops-release accepts --no-sweep" || err "--no-sweep is not parsed"+grep -q -- '--sweep-only)' "$RELEASE" && ok "ops-release accepts --sweep-only" || err "--sweep-only is not parsed"++# The sweep has to land PRs BEFORE the bump, or the changelog and tag miss them.+sweep_line="$(grep -n 'release_pr_sweep "\$GH_REPO"' "$RELEASE" | head -1 | cut -d: -f1)"+bump_line="$(grep -n '^# ----- version base -----' "$RELEASE" | head -1 | cut -d: -f1)"+if [ -n "$sweep_line" ] && [ -n "$bump_line" ] && [ "$sweep_line" -lt "$bump_line" ]; then+ ok "the sweep runs before the version bump"+else+ err "the sweep does not run before the version bump"+fi++# The repo is public and there is a pii-gate CI job. The pattern is assembled at+# runtime so this check cannot match its own source line.+home_pat="/U""sers/|/ho""me/[a-z]"+if grep -qE "$home_pat" "$LIB"; then+ err "a home-directory path leaked into the sweep sources"+else+ ok "no home-directory paths in the sweep sources"+fi++# Never poll GitHub over GraphQL, and never merge past the protections.+# Comment lines are stripped first: the rules are also written down in prose.+CODE="$(grep -vE '^[[:space:]]*#' "$LIB")"+if printf '%s' "$CODE" | grep -qE 'gh pr (checks|view)'; then+ err "the sweep uses GraphQL (gh pr checks / gh pr view)"+else+ ok "the sweep reads GitHub over REST only"+fi+if printf '%s' "$CODE" | grep -q -- '--admin'; then+ err "the sweep can merge with --admin"+else+ ok "the sweep never merges with --admin"+fi++# shellcheck source=../scripts/lib/release-pr-sweep.sh+. "$LIB"++# ---- check verdict -----------------------------------------------------------++SWEEP_REQUIRED_CHECKS_DEFAULT='["build","test"]'++v() { sweep_check_verdict "$1"; }++got="$(v '[{"name":"build","status":"completed","conclusion":"success"},{"name":"test","status":"completed","conclusion":"success"}]')"+[ "$got" = green ] && ok "all successful -> green" || err "all successful gave '$got', wanted green"++got="$(v '[{"name":"build","status":"completed","conclusion":"skipped"},{"name":"test","status":"completed","conclusion":"neutral"}]')"+[ "$got" = green ] && ok "skipped + neutral are not failures" || err "skipped/neutral gave '$got', wanted green"++got="$(v '[{"name":"build","status":"completed","conclusion":"cancelled"},{"name":"test","status":"completed","conclusion":"success"}]')"+[ "$got" = green ] && ok "cancelled is not a failure" || err "cancelled gave '$got', wanted green"++for bad in failure timed_out action_required error; do+ got="$(v "[{\"name\":\"build\",\"status\":\"completed\",\"conclusion\":\"$bad\"},{\"name\":\"test\",\"status\":\"completed\",\"conclusion\":\"success\"}]")"+ [ "$got" = failed ] && ok "$bad is a failure" || err "$bad gave '$got', wanted failed"+done++got="$(v '[{"name":"build","status":"completed","conclusion":"success"}]')"+[ "$got" = pending ] && ok "a missing required check is pending, not green" || err "missing required gave '$got', wanted pending"++got="$(v '[{"name":"build","status":"in_progress","conclusion":""},{"name":"test","status":"completed","conclusion":"success"}]')"+[ "$got" = pending ] && ok "an unfinished check is pending" || err "in_progress gave '$got', wanted pending"++# ---- agent verdict -----------------------------------------------------------++tmp_out="$(mktemp)"+printf 'looks fine\nSWEEP_VERDICT: GOOD\n' >"$tmp_out"+[ "$(sweep_agent_verdict "$tmp_out")" = GOOD ] && ok "an explicit GOOD reads as GOOD" || err "GOOD was not recognised"+printf 'this is good, merge it\n' >"$tmp_out"+[ "$(sweep_agent_verdict "$tmp_out")" = SKIP ] && ok "prose praise without the verdict line is a SKIP" || err "prose was taken as approval"+: >"$tmp_out"+[ "$(sweep_agent_verdict "$tmp_out")" = SKIP ] && ok "a dead agent (empty transcript) is a SKIP" || err "an empty transcript was taken as approval"+rm -f "$tmp_out"++# ---- end-to-end sweep --------------------------------------------------------++FIX="$(mktemp -d)"+export MOCK_GH_SWEEP_DIR="$FIX"+export PATH="$MOCKS:$PATH"++# A fake review agent: verdict per PR from SWEEP_FAKE_<n>, defaulting to SKIP.+AGENT="$FIX/fake-agent"+cat >"$AGENT" <<'AGENTEOF'+#!/usr/bin/env bash+body="$(cat)"+num="$(printf '%s' "$body" | sed -n 's/.*pull request #\([0-9][0-9]*\).*/\1/p' | head -1)"+eval "verdict=\${SWEEP_FAKE_$num:-SKIP}"+if [ "$verdict" = "GOOD_UNDRAFT" ]; then+ gh pr ready "$num" --repo "$SWEEP_TEST_REPO" >/dev/null 2>&1+ verdict=GOOD+fi+echo "reviewed #$num"+echo "SWEEP_VERDICT: $verdict"+AGENTEOF+chmod +x "$AGENT"+export SWEEP_AGENT_CMD="$AGENT"+export SWEEP_TEST_REPO="octo-org/example"++reset_fixtures() {+ rm -f "$FIX"/*.json "$FIX"/*.log "$FIX"/approved-* "$FIX"/run-*.sha 2>/dev/null || true+ unset SWEEP_FAKE_1 SWEEP_FAKE_2 SWEEP_FAKE_3 SWEEP_FAKE_4 2>/dev/null || true+}++# 1. A fork PR held at action_required: the sweep approves the runs, the checks+# then report green, and it merges.+reset_fixtures+cat >"$FIX/pulls.json" <<'EOF'+[{"number":1,"title":"external fix","draft":false,+ "head":{"sha":"sha1","label":"contributor:patch","repo":{"full_name":"contributor/example"}},+ "base":{"ref":"main","repo":{"full_name":"octo-org/example"}}}]+EOF+cat >"$FIX/checkruns-sha1.json" <<'EOF'+{"check_runs":[{"name":"build","status":"completed","conclusion":"action_required"}]}+EOF+cat >"$FIX/checkruns-sha1.after.json" <<'EOF'+{"check_runs":[{"name":"build","status":"completed","conclusion":"success"},+ {"name":"test","status":"completed","conclusion":"success"}]}+EOF+cat >"$FIX/runs-sha1.json" <<'EOF'+{"workflow_runs":[{"id":99,"status":"action_required","head_sha":"sha1"}]}+EOF+printf 'sha1' >"$FIX/run-99.sha"+cat >"$FIX/pr-1.json" <<'EOF'+{"number":1,"draft":false,"state":"open","head":{"sha":"sha1"},+ "base":{"ref":"main"},"mergeable":true,"mergeable_state":"clean"}+EOF+export SWEEP_FAKE_1=GOOD; release_pr_sweep "$SWEEP_TEST_REPO" >"$FIX/out1.txt" 2>&1++grep -q 'approve 99' "$FIX/approvals.log" 2>/dev/null \+ && ok "a fork PR's action_required run is approved" \+ || err "the held fork workflow run was never approved"+grep -q 'merge 1 ' "$FIX/merges.log" 2>/dev/null \+ && ok "a good, green PR is merged once its fork CI is unblocked" \+ || err "the good green PR was not merged"++# 2. A red PR is left open and reported; the release proceeds without it.+reset_fixtures+cat >"$FIX/pulls.json" <<'EOF'+[{"number":2,"title":"broken","draft":false,+ "head":{"sha":"sha2","label":"octo-org:broken","repo":{"full_name":"octo-org/example"}},+ "base":{"ref":"main","repo":{"full_name":"octo-org/example"}}}]+EOF+cat >"$FIX/checkruns-sha2.json" <<'EOF'+{"check_runs":[{"name":"build","status":"completed","conclusion":"failure"},+ {"name":"test","status":"completed","conclusion":"success"}]}+EOF+cat >"$FIX/pr-2.json" <<'EOF'+{"number":2,"draft":false,"state":"open","head":{"sha":"sha2"},+ "base":{"ref":"main"},"mergeable":true,"mergeable_state":"unstable"}+EOF+export SWEEP_FAKE_2=GOOD; release_pr_sweep "$SWEEP_TEST_REPO" >"$FIX/out2.txt" 2>&1+rc=$?+[ "$rc" -eq 0 ] && ok "a red PR does not fail the release" || err "a red PR aborted the release (rc=$rc)"+grep -q 'merge 2 ' "$FIX/merges.log" 2>/dev/null \+ && err "a red PR was merged" \+ || ok "a red PR is left open"+grep -qi '#2 left open' "$FIX/out2.txt" \+ && ok "the red PR is reported" \+ || err "the red PR was skipped silently"++# 3. A good draft is undrafted by the agent, then merged.+reset_fixtures+cat >"$FIX/pulls.json" <<'EOF'+[{"number":3,"title":"draft work","draft":true,+ "head":{"sha":"sha3","label":"octo-org:draft","repo":{"full_name":"octo-org/example"}},+ "base":{"ref":"main","repo":{"full_name":"octo-org/example"}}}]+EOF+cat >"$FIX/checkruns-sha3.json" <<'EOF'+{"check_runs":[{"name":"build","status":"completed","conclusion":"success"},+ {"name":"test","status":"completed","conclusion":"skipped"}]}+EOF+# The re-read after review sees the undrafted PR — the point of re-reading.+cat >"$FIX/pr-3.json" <<'EOF'+{"number":3,"draft":false,"state":"open","head":{"sha":"sha3"},+ "base":{"ref":"main"},"mergeable":true,"mergeable_state":"clean"}+EOF+export SWEEP_FAKE_3=GOOD_UNDRAFT; release_pr_sweep "$SWEEP_TEST_REPO" >"$FIX/out3.txt" 2>&1+grep -q 'ready 3 ' "$FIX/ready.log" 2>/dev/null \+ && ok "a good draft is marked ready for review" \+ || err "the good draft was never undrafted"+grep -q 'merge 3 ' "$FIX/merges.log" 2>/dev/null \+ && ok "an undrafted, green PR is merged" \+ || err "the undrafted green PR was not merged"++# 4. Green, but the agent would not bless it: left open.+reset_fixtures+cat >"$FIX/pulls.json" <<'EOF'+[{"number":4,"title":"risky","draft":false,+ "head":{"sha":"sha4","label":"octo-org:risky","repo":{"full_name":"octo-org/example"}},+ "base":{"ref":"main","repo":{"full_name":"octo-org/example"}}}]+EOF+cat >"$FIX/checkruns-sha4.json" <<'EOF'+{"check_runs":[{"name":"build","status":"completed","conclusion":"success"},+ {"name":"test","status":"completed","conclusion":"success"}]}+EOF+cat >"$FIX/pr-4.json" <<'EOF'+{"number":4,"draft":false,"state":"open","head":{"sha":"sha4"},+ "base":{"ref":"main"},"mergeable":true,"mergeable_state":"clean"}+EOF+export SWEEP_FAKE_4=SKIP; release_pr_sweep "$SWEEP_TEST_REPO" >"$FIX/out4.txt" 2>&1+grep -q 'merge 4 ' "$FIX/merges.log" 2>/dev/null \+ && err "a green PR was merged although the agent did not bless it" \+ || ok "a green PR the agent did not bless is left open"++# 5. A thin REST budget aborts the sweep before it touches anything.+reset_fixtures+cat >"$FIX/pulls.json" <<'EOF'+[{"number":1,"title":"x","draft":false,+ "head":{"sha":"sha1","repo":{"full_name":"octo-org/example"}},+ "base":{"ref":"main","repo":{"full_name":"octo-org/example"}}}]+EOF+MOCK_GH_RATE_CORE=5 release_pr_sweep "$SWEEP_TEST_REPO" >"$FIX/out5.txt" 2>&1+rc=$?+[ "$rc" -ne 0 ] && ok "a thin REST budget aborts the sweep" || err "the sweep ran on a thin REST budget"+[ ! -f "$FIX/merges.log" ] && ok "nothing is merged on a thin REST budget" || err "the sweep merged on a thin REST budget"++# 6. --no-sweep skips the whole stage.+BLOCK="$(awk '/^# ----- pre-release PR sweep -----$/{f=1} f{print} /^# ----- version base -----$/{if(f)exit}' "$RELEASE" \+ | sed '$d')"+if [ -z "$BLOCK" ]; then+ err "the sweep stage block was not found in bin/ops-release"+else+ ok "the sweep stage block is present in bin/ops-release"+ ran="$FIX/stage-ran"+ release_pr_sweep() { : >"$ran"; }+ rm -f "$ran"+ ( do_sweep=0 dry_run=0 sweep_only=0 GH_REPO="$SWEEP_TEST_REPO"; eval "$BLOCK" ) >/dev/null 2>&1+ [ ! -f "$ran" ] && ok "--no-sweep skips the sweep stage" || err "--no-sweep still ran the sweep"+ rm -f "$ran"+ ( do_sweep=1 dry_run=0 sweep_only=0 GH_REPO="$SWEEP_TEST_REPO"; eval "$BLOCK" ) >/dev/null 2>&1+ [ -f "$ran" ] && ok "the sweep is on by default" || err "the sweep did not run by default"+ rm -f "$ran"+ ( do_sweep=1 dry_run=1 sweep_only=0 GH_REPO="$SWEEP_TEST_REPO"; eval "$BLOCK" ) >/dev/null 2>&1+ [ ! -f "$ran" ] && ok "--dry-run never merges anything" || err "--dry-run ran the real sweep"+fi++rm -rf "$FIX"++echo ""+echo "---"+echo "Results: $pass passed, $fail failed"+[ "$fail" -eq 0 ]