PR Autofix
Autonomous PR monitor and fixer. This file carries the whole protocol,
including the Ready-to-Merge definition below. Two bundled dependencies are
required beyond it, both from the github skill: Phase 0 runs its transport
preflight, and MCP mode reads its routing reference. Everything else needed
to run this skill is here.
Migrated from the pr-autofix command under ADR-064, which makes skills the single
user-invocable surface. The command file is gone, so its path is named here in
plain text rather than as a citation to something a reader could open.
Triggers
| Trigger phrase |
Operation |
pr-autofix |
Triage all open PRs by tier and act |
autofix this pr |
Single-PR mode on the current branch's open PR |
monitor open prs |
Periodic triage without merging |
auto-merge ready prs |
Tier 1 only: enable auto-merge on land-ready PRs |
address pr feedback |
Tier 3/4 only: walk thread lifecycle |
Process
Four phases. Tier-based dispatch decides which actions apply per PR.
Phase 0: Transport preflight (BLOCKING, runs once)
Every script this command calls reaches GitHub through gh. An agent sandbox
that proxies egress leaves gh installed and GH_TOKEN set while refusing
GitHub for the whole session, so each script fails with HTTP 403 and none of
those failures says anything about the PR. Decide the transport once, before
triage:
# CLAUDE_PLUGIN_ROOT is set in a vendored install; falls back to .claude in-repo.
SCRIPTS_DIR="${COPILOT_PLUGIN_ROOT:-${CLAUDE_PLUGIN_ROOT:-.claude}}/skills/github/scripts/utils"
python3 "$SCRIPTS_DIR/check_github_transport.py"
Non-POSIX hosts do not run the block above. The authoritative, per-harness
launcher for this one command is check_transport in the scripts map of
pr-review-config.yaml: the copilot entry runs it under PowerShell and
resolves the interpreter (python3, then py -3, then python), because a
Windows host may expose only the launcher. Read it from the map for the harness
you are on rather than transcribing a second copy here, which would drift.
| Verdict |
Action |
Transport: gh |
Continue. Every script below works as written. |
Transport: gh_unusable |
Continue in MCP mode; see the rule block below. |
| exit 3 |
A quota window or a transport wobble, not a transport change. Stop and retry later. |
| exit 4 |
A credential fault. Stop and report it; do not switch transports around a fixable token. |
MCP mode rules. The mapping from each script to its GitHub MCP operation
is in the github skill's references/transport-routing.md, which also gives
the per-harness spelling for the operation names. On top of it:
Read operations (triage, CI status, check logs, review threads, PR and
issue bodies) all have MCP equivalents. Use them freely.
Write operations (replies, resolving threads, arming auto-merge, merging)
also have MCP equivalents, but rule 3 governs whether you may use them at
all, and the grant in this file's frontmatter does not include any of them.
Do not read this row as permission: it says the tool exists, not that the
operation is allowed here.
Pushing is not on that list and has no MCP equivalent. push_files builds
a new remote commit out of file contents you supply; it does not transfer
local commits or branch history, so it cannot stand in for git push.
test_pr_merge_ready.py, check_pr_live_state.py, why_pr_blocked.py,
triage_red_check.py, run_completion_gate.py, check_pr_round_cap.py,
have no MCP equivalent, because each computes a
verdict from several gh calls plus local logic. triage_red_check.py is
named explicitly because the CI-failure triage step below makes it
mandatory before any log reading, and a blocked session must derive that
verdict by hand rather than falling back to gh. Most of their inputs are
reachable: gather the same fields with pull_request_read and apply the gate
definitions in this file by hand. Record in the PR handoff that the verdict
was derived, not scripted.
One input is not reachable, and it is load-bearing. No exposed MCP operation
reads a branch ruleset, so the required-context set is unavailable, which is
exactly the case where a check-run list reads clean on a PR that cannot
merge. test_pr_merge_ready.py therefore cannot be reconstructed as a PASS
at all. Report the checks and merge state you did read, say the
required-context set was not read, and treat merge readiness as unknown.
The round cap still applies in this mode: it is what stops a T3/T4 PR
iterating without bound, and it is reconstructed by hand here like the other
verdicts in rule 2. Concurrency between two sessions working the same branch
is held by the Force-Push Safety SHA gate below, which is a hard gate rather
than an advisory one: it re-reads the ref immediately before the push and
pins --force-with-lease to an observed SHA, so a competing session's commit
makes the push fail rather than silently win. Git is also a separate
transport from the GitHub API (a push has succeeded while
the API was failing), so a session refused for the API can still push, and
the SHA gate is what makes that safe.
A transport failure is an unknown, never a verdict. Never classify a PR as
T2 (CI fix), BLOCKED, or DIRTY because a call failed. Report the PR as
untriaged with the transport as the reason.
Phase 1: Triage
Run test_pr_merge_ready.py for every open PR. Classify each into a tier (T1-T5) using the table below. Sort the queue by tier ascending.
Phase 2: Act per tier
Walk the queue. For each PR, apply the tier's action set. T1 first (land-ready), then T2 (CI fix), then T3/T4 (threads). T5 applies to bot-authored PRs that pass the merge-state gates (not BEHIND or DIRTY) but still have a failure or unresolved threads, including a BLOCKED one; the tier-dispatch block terminates such a PR after the auto-merge disarm gate so a human handles it. A bot PR that is BEHIND or DIRTY stays at that merge-state tier and the automated loop processes it.
Per-PR live-state gate (BLOCKING). Before any action runs on a PR (any tier: arming auto-merge, pushing a CI fix, posting a thread reply), call check_pr_live_state.py and branch on the JSON envelope Data.action field. The session-start triage snapshot is stale by the time the walk reaches each row in a repo with heavy merge automation, and the consequences of acting on a stale row are concrete: armed auto-merge on a redundant PR, conflict merges into a closed branch, duplicate logic landed twice.
# One outer fetch covers all per-PR calls; --skip-fetch keeps the loop cheap.
git fetch --quiet origin "+refs/heads/main:refs/remotes/origin/main"
resolve_pr_scripts_dir() {
repo_root="$(git rev-parse --show-toplevel 2>/dev/null || pwd)"
for root in \
"${COPILOT_PLUGIN_ROOT:-}" \
"${CLAUDE_PLUGIN_ROOT:-}" \
"$repo_root/.claude" \
"${HOME:-}/.copilot/installed-plugins/_direct/project-toolkit" \
"${HOME:-}/.copilot/installed-plugins"/*/project-toolkit \
"${HOME:-}/.claude/plugins/cache"/*/project-toolkit; do
if [ -n "$root" ] && [ -d "$root/skills/github/scripts/pr" ]; then
printf '%s\n' "$root/skills/github/scripts/pr"
return 0
fi
done
printf '%s\n' ".claude/skills/github/scripts/pr"
}
SCRIPTS_DIR="$(resolve_pr_scripts_dir)"
# late-live-state-guard:start
recheck_pr_live_state() {
local late_live late_rc late_action late_reason late_state late_head late_base
if late_live=$(python3 "$SCRIPTS_DIR/check_pr_live_state.py" \
--pull-request "$PR" --skip-fetch \
--expected-head-sha "${EXPECTED_HEAD_SHA:-}" \
--expected-base-ref "${EXPECTED_BASE_REF:-}" \
--expected-base-sha "${EXPECTED_BASE_SHA:-}" \
--output-format json); then
late_rc=0
else
late_rc=$?
fi
late_action=$(printf '%s' "$late_live" | jq -r '.Data.action // empty' 2>/dev/null)
if [ "$late_rc" -eq 0 ] && [ "$late_action" = "ACT" ]; then
return 0
fi
late_reason=$(printf '%s' "$late_live" | jq -r '.Data.reason // "live-state check failed"' 2>/dev/null)
late_state=$(printf '%s' "$late_live" | jq -r '.Data.state // "UNKNOWN"' 2>/dev/null)
late_head=$(printf '%s' "$late_live" | jq -r '.Data.head_sha // "unknown"' 2>/dev/null)
late_base=$(printf '%s' "$late_live" | jq -r '.Data.base_ref // "main"' 2>/dev/null)
echo "Skipping mutation for #$PR: $late_reason"
if [ "$late_state" = "MERGED" ]; then
echo "Merged head SHA: $late_head"
echo "Preserve unpushed commits or a net patch. Reapply them on a follow-up branch from current origin/$late_base."
elif [ "$late_state" = "CLOSED" ]; then
echo "Closed PR head SHA: $late_head"
echo "Preserve unpushed commits or a net patch before leaving the old branch."
fi
return 75
}
run_pr_mutation_if_live() {
if recheck_pr_live_state; then
"$@"
return $?
fi
return 75
}
# late-live-state-guard:end
# SESSION_ID must be set before the loop (e.g. from the session log or a uuid).
# Per PR, immediately before any per-tier action:
# Step 1: Live-state gate (BLOCKING).
LIVE=$(python3 "$SCRIPTS_DIR/check_pr_live_state.py" \
--pull-request "$PR" --skip-fetch --output-format json)
ACTION=$(echo "$LIVE" | jq -r '.Data.action')
if [ "$ACTION" = "SKIP" ]; then
REASON=$(echo "$LIVE" | jq -r '.Data.reason')
echo "Skipping #$PR: $REASON"
# If Data.superseded_by_base.fully_superseded == true, recommend close
# via the queue's close-handling path; do NOT push or merge.
continue
fi
EXPECTED_HEAD_SHA=$(echo "$LIVE" | jq -r '.Data.head_sha // empty')
EXPECTED_BASE_REF=$(echo "$LIVE" | jq -r '.Data.base_ref // empty')
EXPECTED_BASE_SHA=$(echo "$LIVE" | jq -r '.Data.base_sha // empty')
if [ -z "$EXPECTED_HEAD_SHA" ] || [ -z "$EXPECTED_BASE_REF" ] || [ -z "$EXPECTED_BASE_SHA" ]; then
echo "Cannot bind mutation to the live PR identity for #$PR; skipping."
continue
fi
# ACTION == "ACT": proceed with the tier's planned action set.
# tier-dispatch:start
# Step 2.5: Tier read, then the auto-merge disarm gate, then the round-cap
# circuit breaker (BLOCKING for T3/T4). The two gates run in that
# order for the reason given at the disarm gate below; do not swap them back.
# T3/T4 PRs iterate: post a fix, wait for CI or a bot review, repeat. Nothing
# capped how many times that loop could run, and prose caps have been
# ignored repeatedly (the documented failure mode, not a hypothetical one):
# one PR ran 11+ bot review rounds over 46 hours wall clock before a human
# intervened, and two others each ran 18 rounds. check_pr_round_cap.py records one round per call against a
# hidden marker comment on the PR (stored as
# a hidden marker comment) and returns Data.action=ESCALATE when
# either the round count or the wall-clock budget is exceeded. Call it once
# per pass through this loop for a T3/T4 PR, after the tier is known and after
# the auto-merge disarm gate below, before any thread-lifecycle or CI-fix
# action. It used to say "immediately after the tier is known", which was true
# until the disarm gate moved ahead of it to close CWE-284; the disarm gate and
# the unknown-tier exit now both run in between.
# Tier comes from test_pr_merge_ready.py, the authoritative tier source;
# check_pr_live_state.py emits no tier field, so reading $LIVE here pins TIER
# at UNKNOWN. Computed once, also consumed by the auto-merge disarm gate below.
# Read `.Tier`, not `.Data.Tier`: unlike the github_core.output emitters,
# test_pr_merge_ready.py has no --output-format flag and prints its result
# dict directly (`print(json.dumps(result, indent=2))`), so there is no Data
# envelope to traverse.
# A pinned UNKNOWN breaks the two gates in OPPOSITE directions, so do not
# read it as "the gates turn off": this gate tests TIER = T3 or T4, which
# UNKNOWN never satisfies, so it goes inert; the disarm gate below tests
# TIER != T1, which UNKNOWN always satisfies, so it fires on every armed PR
# and strips auto-merge from genuine T1 PRs too.
# tests/commands/test_pr_autofix_field_contract.py checks every read in this
# file against its producer's real schema, and
# tests/commands/test_pr_autofix_tier_dispatch_runtime.py executes the block
# between the tier-dispatch markers under bash with fake producers, so the two
# gate directions below are asserted behavior rather than described behavior.
if ! AUTHOR_CTX=$(python3 "$SCRIPTS_DIR/get_pr_context.py" --pull-request "$PR" \
--field author_is_bot --output-format json 2>/dev/null); then
# Focused mode keeps this read off the review-thread pagination path. A
# stale installed helper can still reject `--field`; fall back once so the
# existing absent-field diagnostic keeps naming a copy that predates the author_is_bot field rather
# than collapsing it into the generic unreadable branch.
if ! AUTHOR_CTX=$(python3 "$SCRIPTS_DIR/get_pr_context.py" --pull-request "$PR" \
--output-format json 2>/dev/null); then
AUTHOR_CTX=""
fi
fi
# Bot-author lookup, read BEFORE the tier producer because the tier depends on
# it. classify_tier only reaches T5 when `is_bot and
# (has_ci_failures or has_threads)`, and its `is_bot` parameter defaults to
# False, so a producer call that omits --is-bot cannot return T5 at all: every
# affected bot PR that reached work-tier classification came back T2, T3, or T4
# and was processed in the unattended loop. T5 is reached only when the
# merge state passes the earlier gates (not BEHIND or DIRTY) AND
# `is_bot and (has_ci_failures or has_threads)`. BLOCKED with a failure or a
# thread reaches T5 too. A bot PR that is BEHIND or DIRTY stays
# at its merge-state tier and does not reach the T5 handoff, which is correct:
# the automated loop handles it.
# Author identity is stable during one pass, so this answer is kept for tier
# production. The focused `--field author_is_bot` mode keeps the read down to
# one `gh pr view --json author` call instead of a full context walk. Auto-merge
# is mutation-sensitive and is fetched again at the disarm gate below, in the
# matching `--field auto_merge_method` mode. That split is deliberate: the
# one-fetch contract is retired because a stale auto-merge verdict fails open.
# The classification itself is NOT made here. get_pr_context.py emits
# `author_is_bot` from github_core.bot_config.is_bot, the repository's one
# authoritative bot-author rule. Re-deriving it here as a `[bot]` suffix test
# would disagree with that rule on the logins this repository actually sees:
# bot_config.py maps `app/copilot-swe-agent`, the spelling `gh pr view --json
# author` returns for the Copilot coding agent, onto `copilot-swe-agent[bot]`,
# and neither that spelling nor `Copilot` carries a `[bot]` suffix.
# jq can emit a valid first value then exit nonzero on a malformed suffix.
# The assignment must be the condition: checking the document with a second jq
# call can succeed on a later value even when this filter failed.
if ! IS_BOT=$(printf '%s' "$AUTHOR_CTX" | jq -r 'if (.Data | has("author_is_bot") | not) then "absent" elif (.Data.author_is_bot | type) == "boolean" then (.Data.author_is_bot | tostring) else "unknown" end' 2>/dev/null); then
IS_BOT="unknown"
fi
# `absent` is a separate verdict from `unknown` because it has a separate cause
# and a separate remedy. resolve_pr_scripts_dir above tries $COPILOT_PLUGIN_ROOT
# then $CLAUDE_PLUGIN_ROOT, then $repo_root/.claude, and only after that the three
# installed-plugin caches; the caches never outrank the checkout, which is what
# ci-scripts.md MUST-8 requires. So $SCRIPTS_DIR/get_pr_context.py is a stale copy
# in exactly two situations: either plugin-root variable is set and points at an
# install that predates the fix, or this session is running outside a checkout that
# carries skills/github/scripts/pr and falls through to a cache. Diagnose in that
# order, plugin roots first. A copy predating the author_is_bot field emits no
# author_is_bot key at all, which fails closed like any other unreadable author
# and would otherwise reclassify EVERY PR with a failing check or an unresolved
# thread as T5, repo-wide, announced by one indistinguishable line. Naming the
# stale helper is what turns that from a silent reclassification into a fixable
# report. Same hazard the "Checkout ownership for the readiness helper"
# section below records for test_pr_merge_ready.py.
# Empty stdin or a jq parse error yields an empty string, not "unknown", which is
# neither "false" nor any verdict the branch below can name; the fail-closed
# branch would then be taken with no message at all. The sibling AUTO_MERGE read
# further down documents the same trap. Normalize it here so every path out of
# this read is a verdict with a name.
IS_BOT=${IS_BOT:-unknown}
# Fail CLOSED: an author this session could not classify is treated as a bot.
# Fail CLOSED here because the two errors are not symmetric.
# Guessing "human" on an unreadable author hands a PR nobody vouched for to the
# unattended loop, which is the outcome the T5 tier exists to prevent.
# Guessing "bot" costs a human one manual look at a PR that may not have needed
# one, which is recoverable. Only a real JSON boolean `false` buys the
# non-bot path; a missing field, a null, or a string spelling of a boolean is
# "absent" or "unknown" and takes the closed branch, matching the type-checked
# read the PAGES_COMPLETE guard below uses for the same reason.
# The notice fires on anything that is not the literal `true`, not on the two
# named verdicts, so a future value out of the jq expression cannot slip through
# the closed branch unannounced the way the empty string did.
if [ "$IS_BOT" = "false" ]; then
IS_BOT_FLAG=""
else
IS_BOT_FLAG="--is-bot"
if [ "$IS_BOT" = "absent" ]; then
echo "Cannot read author bot state for #$PR: $SCRIPTS_DIR/get_pr_context.py emits no author_is_bot field, so that helper is outdated; reinstall the plugin or run from the repository checkout. Classifying as a bot PR (fail closed)."
elif [ "$IS_BOT" != "true" ]; then
echo "Cannot read author bot state for #$PR; classifying as a bot PR (fail closed)."
fi
fi
# Unquoted on purpose, and this is the one place in this block where that is
# correct: the variable holds either the single literal token --is-bot or the
# empty string, and quoting it would pass an empty argument that argparse
# rejects. It is never attacker-influenced; both values are written above.
# shellcheck disable=SC2086
# The tier this produces gates the auto-merge disarm below via
# TIER_TRUSTED_T1, and this runs against the checked-out PR branch with no
# trusted-ref comparison, so it must NOT read --dispositions-file. A PR that
# edited the registry could dispose its own failing security check, reach T1,
# and keep auto-merge armed (CWE-829, CWE-284). Only the completion gate,
# which byte-compares every tracked file its criteria name against the
# trusted ref first, may honor a disposition.
if MERGE_READY=$(python3 "$SCRIPTS_DIR/test_pr_merge_ready.py" --pull-request "$PR" $IS_BOT_FLAG 2>/dev/null); then
MERGE_READY_RC=0
else
MERGE_READY_RC=$?
fi
# Deliberately no 2>/dev/null on either jq below. The producer's stderr is
# suppressed above, so a jq parse error is the only signal an operator gets that
# the producer emitted something unreadable, and both guards below would
# otherwise skip the PR with no explanation. Adding the redirect here was tried
# and the runtime suite failed it by name; see the malformed-producer case.
if ! TIER=$(printf '%s' "$MERGE_READY" | jq -r '.Tier // "UNKNOWN"'); then
TIER="UNKNOWN"
fi
TIER=${TIER:-UNKNOWN}
# Captured once and read twice, because the tier alone does not say whether the
# evidence behind it was complete. classify_tier returns T1 on CanMerge, and
# CanMerge is `len(reasons) == 0` with fetched_pages_complete computed after it
# and never appended to reasons (test_pr_merge_ready.py, check_merge_readiness).
# So a fetch truncated at the pagination cap that happens to surface no
# unresolved thread and no failing required check classifies T1, which the
# producer's own docstring warns about: "a partial fetch that happens to find no
# failing checks is not evidence that no failing checks exist."
# This mattered only after the tier read above was fixed. While TIER was pinned
# at UNKNOWN, TIER != T1 held for every PR, so the disarm gate below stripped
# auto-merge from the truncated-fetch case by accident. Making T1 reachable
# removes that accident, so the exemption has to be earned rather than assumed.
# Anything other than the literal `true` denies the exemption: the real producer
# always emits the boolean, so healthy input is unaffected, and a missing or
# unreadable field is exactly the state that must not buy a merge.
# The read has been wrong twice, in opposite directions, so both are pinned.
# First it said `// "unknown"`, and jq's alternative operator fires on `false`
# as well as `null`, so a producer reporting an incomplete fetch was relabelled
# "unknown": the operator was told the field could not be read when it had been
# read fine. Both deny the exemption, which is why no test could tell them apart
# until one was added that reads the message.
# Then the repair used a bare `tostring`, which does not check the JSON type, so
# the *string* "true" came out as `true` and bought the exemption. That is the
# worse direction: malformed evidence granting a merge is the thing this guard
# exists to refuse. Only a real JSON boolean is accepted now; every other type,
# including a string spelling of a boolean, is "unknown" and denies.
if ! PAGES_COMPLETE=$(printf '%s' "$MERGE_READY" | jq -r 'if (.fetched_pages_complete | type) == "boolean" then (.fetched_pages_complete | tostring) else "unknown" end'); then
PAGES_COMPLETE="unknown"
fi
PAGES_COMPLETE=${PAGES_COMPLETE:-unknown}
# Exit 1 is the producer's documented not-ready verdict and is valid for every
# non-T1 tier. Any higher exit, or T1 paired with exit 1, contradicts the
# payload and cannot buy a merge.
if [ "$MERGE_READY_RC" -gt 1 ] || { [ "$MERGE_READY_RC" -eq 1 ] && [ "$TIER" = "T1" ]; }; then
TIER="UNKNOWN"
PAGES_COMPLETE="unknown"
fi
# .claude/skills/pr-review/pr-review-config.yaml already ANDs this field into its
# completion-gate criterion, so this is the same safety rule applied at the
# other place a merge can be armed, not a new policy.
# Fail closed on a tier the producer never declared. Empty or malformed stdout
# and a JSON error object all normalize to UNKNOWN. That skips the T3/T4 breaker
# below AND satisfies
# TIER != T1 in the disarm gate, so without this guard the loop would keep
# acting on a PR whose tier it never learned. Acting is the harm here; disarming
# is not, so the guard stops the acting and still runs the disarm gate.
# Do not gate on exit status instead:
# test_pr_merge_ready.py exits 1 for any not-merge-ready PR, so T2 through T4 are
# legitimately non-zero.
# The accepted set is the producer's own, quoted verbatim from
# test_pr_merge_ready.py, which classify_tier's docstring names as the range of
# its return value:
# _TIER_ORDER = (
# "T1", "T2", "T3", "T4", "T5",
# "BEHIND", "BLOCKED", "DIRTY", "SKIP", "UNSUPPORTED", "STACKED",
# )
# The six beyond the T1-T5 ladder are real: SKIP for a draft, closed, or merged
# PR, BEHIND/DIRTY from the merge-state lookup, BLOCKED for a PR waiting on an
# outside gate with no failure or thread, and UNSUPPORTED for a
# mergeStateStatus this repository has no verified merge path for, and STACKED
# for a merge-ready PR whose base is not the default branch.
# Listing only
# the ladder rejected those as producer failures and silently disabled the
# documented BEHIND and DIRTY handling.
# tests/commands/test_pr_autofix_tier_contract.py pins this list against the
# producer so the two cannot drift apart again.
# Recognized and actionable are two different questions, and collapsing them is
# what put SKIP on the acting path. The tier table below reads
# "| SKIP | Draft, merged, or closed | No action |", so SKIP terminates here.
# Letting it reach the disarm gate means TIER != T1 holds and auto-merge is
# stripped from a PR that went draft, merged, or closed after the live-state
# gate ran.
# SKIP and an unknown tier both terminate the PR, but at different points, and
# the difference is which one has a reason not to disarm. SKIP names a state:
# the PR is a draft, merged, or closed, so stripping auto-merge is either
# meaningless or destroys a choice its author made deliberately. An unknown tier
# names no state at all, so "armed but not provably T1" is exactly true of it,
# which is the disarm gate's own trigger condition. It therefore falls through
# to that gate and stops immediately after, before the round-cap breaker and
# before any tier action.
# The cost of that direction is real and is accepted: a transient producer
# failure on a healthy T1 PR strips an auto-merge its author armed, and they
# have to arm it again. The other direction leaves a PR this session could not
# assess free to land itself, which is not recoverable. Copilot reported the
# arm as it first shipped, where it exited before the disarm gate; that made a
# producer crash the one path where this loop leaves auto-merge armed on a PR
# it never assessed, and contradicted this change's own claim that the armed
# set only shrinks.
# UNSUPPORTED is recognized and terminates, like SKIP, but it terminates one
# gate later, for the same reason the unknown-tier arm does. SKIP names a state
# whose author chose it, so stripping auto-merge would destroy that choice.
# UNSUPPORTED names a mergeStateStatus with no verified merge path, so "armed
# but not provably T1" is exactly true of it and the disarm gate below must run
# first. It is a separate arm rather than a T4 because T4 dispatches into the
# round-cap thread-fix loop, and an UNSUPPORTED PR routinely carries zero
# threads and zero CI failures: that loop would have no action to take and
# would terminate only by burning the round cap and posting an escalation
# comment on a PR with nothing to escalate.
# STACKED terminates at the same point as UNSUPPORTED, for the same reason, and
# it is the T1 arm's replacement, not a new kind of work. The producer returns it
# only for a PR that would otherwise be T1, so every check, thread, and
# merge-state gate already passed. What remains is the merge step, and the squash
# merge in the T1 path folds a PR into its base: for a stacked PR that base is
# the parent PR's branch, so the merge collapses the stack instead of landing
# work on the default branch (observed on a stacked series where
# triage reported T1, CLEAN, CanMerge=true for every member). It is
# "armed but not provably T1", so the disarm gate below runs first. T3 and T4
# would have no action to take, so it must not enter the round-cap loop.
TIER_KNOWN=yes
TIER_TERMINAL=no
case "$TIER" in
SKIP)
echo "Tier SKIP for #$PR (draft, merged, or closed); no action."
continue
;;
UNSUPPORTED)
MERGE_STATE=$(printf '%s' "$MERGE_READY" | jq -r '.MergeStateStatus // ""')
echo "Tier UNSUPPORTED for #$PR (mergeStateStatus '${MERGE_STATE:-<missing>}' has no verified merge path); disarming auto-merge if armed, then skipping."
TIER_TERMINAL=yes
;;
STACKED)
BASE_REF=$(printf '%s' "$MERGE_READY" | jq -r '.BaseRef // ""')
DEFAULT_BRANCH=$(printf '%s' "$MERGE_READY" | jq -r '.DefaultBranch // ""')
echo "Tier STACKED for #$PR (base '${BASE_REF:-<missing>}' is not the default branch '${DEFAULT_BRANCH:-<missing>}'); disarming auto-merge if armed, then handing to a human."
TIER_TERMINAL=yes
;;
T1|T2|T3|T4|T5|BEHIND|BLOCKED|DIRTY) ;;
*)
echo "Cannot determine tier for #$PR (tier producer failed or emitted no tier); disarming auto-merge if armed, then skipping."
TIER_KNOWN=no
;;
esac
# Ordered before the round-cap breaker deliberately, and this order is load
# bearing. The breaker's ESCALATE path terminates the PR, and while it sat first
# that exit ran before this gate, so a T3 or T4 PR that reached its cap was
# handed to a human with native auto-merge still armed: GitHub can then land it
# on its own, with readiness never proven by this session (CWE-284). Copilot
# found it. Like the completeness case above it was opened by the tier-read fix
# rather than found beside it, since a pinned UNKNOWN never matched T3 or T4, so
# the breaker never fired and this gate disarmed every armed PR anyway.
# Disarming is not acting on a PR, it is taking a capability away from one, so
# there is no tier this is unsafe to run first. A test asserted the opposite
# contract and is flipped in the same change.
# Step 2.6: Auto-merge disarm gate (BLOCKING). Numbered after the
# tier read and before the round-cap breaker, which is where it now runs.
# If the PR has auto-merge armed but is not T1-ready, a conflict refresh or CI
# fix push could immediately land a PR whose readiness was never explicitly
# verified in this session. Disable auto-merge now, before any commit or push.
# TIER and PAGES_COMPLETE were both read from the readiness producer above.
# Refresh context here because auto-merge can be armed while readiness is being
# fetched. Reusing the author lookup would let that stale null bypass disarm,
# so this gate deliberately spends a second context read for fresh evidence.
if ! CTX=$(python3 "$SCRIPTS_DIR/get_pr_context.py" --pull-request "$PR" \
--field auto_merge_method \
--output-format json 2>/dev/null); then
CTX=""
fi
if ! AUTO_MERGE=$(printf '%s' "$CTX" | jq -r 'if (.Data | has("auto_merge_method") | not) then "unknown" elif (.Data.auto_merge_method | type) == "string" then .Data.auto_merge_method elif (.Data.auto_merge_method | type) == "null" then "null" else "unknown" end' 2>/dev/null); then
AUTO_MERGE=""
fi
# Empty stdin or a jq parse error yields an empty string, not a verdict.
# A schema-invalid value such as `false` is also unreadable evidence here:
# `false // "null"` would launder it into "definitely unarmed" and bypass the
# disarm gate on malformed input. Accept only a string or a real null.
AUTO_MERGE=${AUTO_MERGE:-unknown}
if [ "$AUTO_MERGE" = "unknown" ]; then
echo "Cannot read auto-merge state for #$PR (context fetch or parse failed); skipping."
continue
fi
# "Not provably T1" rather than "not T1": a T1 whose evidence came from a
# truncated fetch has not earned the exemption, so it disarms with the rest.
if [ "$TIER" = "T1" ] && [ "$PAGES_COMPLETE" = "true" ]; then
TIER_TRUSTED_T1=yes
else
TIER_TRUSTED_T1=no
fi
if [ "$AUTO_MERGE" != "null" ] && [ "$TIER_TRUSTED_T1" != "yes" ]; then
if [ "$TIER" = "T1" ]; then
echo "Auto-merge armed on #$PR and the tier is T1, but the merge-readiness fetch was incomplete (fetched_pages_complete=$PAGES_COMPLETE); disabling before acting."
else
echo "Auto-merge armed on non-T1 PR #$PR (method: $AUTO_MERGE); disabling before acting."
fi
# No --output-format needed here. set_pr_auto_merge.py once registered no
# such option, so argparse exited 2 before the mutation ran and this gate
# took its failure branch on every armed non-T1 PR, leaving auto-merge
# armed. The script now accepts the flag, and the default
# already prints the AutoMergeEnabled object the verification checklist
# asks for.
if run_pr_mutation_if_live \
python3 "$SCRIPTS_DIR/set_pr_auto_merge.py" \
--pull-request "$PR" --disable; then
MUTATION_RC=0
else
MUTATION_RC=$?
fi
# Captured in both arms rather than read from $? inside the else. The
# single-arm form holds the right value today only because nothing sits
# between the `if` and the read; this form does not depend on that.
if [ "$MUTATION_RC" -ne 0 ]; then
if [ "$MUTATION_RC" -ne 75 ]; then
# 75 is the wrapper's own skip and it already printed the reason.
# Any other status means the disable was attempted and did not
# land, so auto-merge is still armed on a PR whose readiness this
# session never verified. Say that. The old wording, "skipping to
# avoid unguarded merge", named the opposite of the state it left.
echo "Failed to disable auto-merge on #$PR (rc=$MUTATION_RC); auto-merge is still armed and GitHub can land the PR unattended. Skipping; this one needs a human."
fi
continue
fi
fi
# The unknown-tier, UNSUPPORTED, and STACKED arms resume here, one gate later
# than SKIP leaves, so all three have had auto-merge stripped above. Everything
# below needs a tier with an action behind it, and none of these has one, so all
# three stop now.
if [ "$TIER_KNOWN" = "no" ] || [ "$TIER_TERMINAL" = "yes" ]; then
continue
fi
# T5 terminates here, and making it reachable is what created the need. The
# round-cap breaker below fires on T3 and T4 only, which was complete while
# --is-bot was never forwarded: a bot PR with threads or CI failures classified
# T3 or T4 and hit the breaker. Now the same PR classifies T5, so without this
# arm it would fall past a condition that no longer matches, into the tier
# actions, with no cap and no human handoff. That is strictly worse than the
# behavior the flag was added to fix: the breaker is the circuit added after a PR
# ran 11+ rounds over 46 hours, and T5 would have been the
# one tier running the unattended loop with it switched off.
# The tier table reads "| T5 | Bot PR that passes merge-state gates but has
# failures or threads | Handle individually |", so the executable arm is a
# handoff rather than a capped loop.
# Placed here rather than at the SKIP arm for the reason that arm records: SKIP
# names a state where disarming is meaningless or destructive, while a T5 PR is
# "armed but not provably T1", which is the disarm gate's own trigger condition.
# It therefore falls through that gate first, exactly like the unknown-tier exit
# one gate above, and stops before any tier action.
if [ "$TIER" = "T5" ]; then
echo "Tier T5 for #$PR (bot-authored, passed merge-state gates, has failure or threads); handing to a human."
continue
fi
if [ "$TIER" = "T3" ] || [ "$TIER" = "T4" ]; then
# This loop runs from the shared checkout, whose HEAD is not
# the PR's. The orphaned-commit scan compares the live PR head with a local
# HEAD, so point it at the worktree that holds the PR branch. Without it the
# ancestry check exits 1 or 128 and the scan reports `unverified` with no
# `.commits` and no `force_push_suspected`; read `reason`. No matching
# worktree passes no flag, and the script falls back to the current
# directory.
PR_HEAD_REF=$(printf '%s' "${LIVE:-}" | jq -r '.Data.head_ref // empty' 2>/dev/null)
PR_HEAD_REPO=$(printf '%s' "${LIVE:-}" | jq -r '.Data.head_repo // empty' 2>/dev/null)
PR_WORKTREE=""
# A branch name is chosen by the PR author, so the ref alone does not identify
# the worktree. Also require that its origin is the PR head repository. HEAD
# need not hold the live head: a force-pushed PR leaves the worktree diverged,
# and that is the case this scan lists. The result feeds a report, so this is
# looser than the exact head match cleanup demands before it deletes.
# A missing input matches nothing: no --worktree is passed.
# pr-worktree-select:begin
if [ -n "$PR_HEAD_REF" ] && [ -n "$PR_HEAD_REPO" ] && [ -n "$EXPECTED_HEAD_SHA" ]; then
WANT_REPO=$(printf '%s' "$PR_HEAD_REPO" | tr 'A-Z' 'a-z')
# awk fields are written $(N), not $N: the skill loader rewrites a bare $<digit> as an argument.
while IFS= read -r CANDIDATE; do
[ -n "$CANDIDATE" ] || continue
ORIGIN_URL=$(git -C "$CANDIDATE" remote get-url origin 2>/dev/null | tr 'A-Z' 'a-z')
ORIGIN_URL=${ORIGIN_URL%/}
ORIGIN_URL=${ORIGIN_URL%.git}
case "$ORIGIN_URL" in
*"/$WANT_REPO" | *":$WANT_REPO") PR_WORKTREE="$CANDIDATE"; break ;;
esac
done < <(git worktree list --porcelain 2>/dev/null | awk -v ref="refs/heads/$PR_HEAD_REF" \
'/^worktree /{path=substr($(0), 10)} $(1) == "branch" && $(2) == ref {print path}')
fi
# pr-worktree-select:end
ROUND_CAP_ARGS=(--pull-request "$PR" --output-format json)
if [ -n "$PR_WORKTREE" ]; then
ROUND_CAP_ARGS+=(--worktree "$PR_WORKTREE")
fi
ROUND_CAP=$(python3 "$SCRIPTS_DIR/check_pr_round_cap.py" "${ROUND_CAP_ARGS[@]}")
ROUND_ACTION=$(echo "$ROUND_CAP" | jq -r '.Data.action // empty')
# The scan result is set when the record is escalated, including an ACT
# verdict right after a reset. Print it on every arm: it names the local
# commits the live head lacks, and the reader should not run git log by hand.
ROUND_ORPHANS=$(echo "$ROUND_CAP" | jq -r '.Data.orphaned_warning // empty')
if [ -n "$ROUND_ORPHANS" ]; then
echo "$ROUND_ORPHANS"
fi
if [ "$ROUND_ACTION" != "ACT" ]; then
ROUND_REASON=$(echo "$ROUND_CAP" | jq -r '.Data.reason // "round-cap check f
…(truncated)
1---2name: pr-autofix-33description: Fix PRs autonomously. Triage open PRs by tier, address thread feedback, fix CI failures, and enable auto-merge when the 4-condition Ready-to-Merge gate passes. Use when you say `pr-autofix`, `autofix this pr`, or `monitor open prs`. Do NOT use to answer review comments interactively on one PR (use pr-review), and do NOT use to run the six quality axes over your working changes (use pr-quality-all).4metadata:5 source: https://skillmd.com/skills/rjmurillo/pr-autofix-36---78# PR Autofix910<!-- # taste-lint: ignore file-size, this skill is one end-to-end PR workflow; splitting it would hide required mutation gates from the agent. -->1112<!--13size-exception rationale (carried forward under ADR-064).1415What the check wants: the skill_size validator blocks a SKILL.md over 500 lines16or 24576 bytes and tells you to decompose it into references/.1718Why the idiomatic fix only partly applies: this file carries the entire19Ready-to-Merge protocol by design ("Nothing outside it is needed to run this20skill"). The body includes the tier ladder, Ready-to-Merge gate definition,21thread-lifecycle state machine, and CI-failure triage procedure, and the22Process phases are one annotated bash program whose ordering IS the safety23argument. Moving a live-state gate or a disarm gate out of the loaded body is a24behavioral change that must be measured against the eval harness before25shipping, so none moved.26What moved to references/: Post-merge cleanup (references/post-merge-cleanup.md),27the test_pr_merged.py exit-code contract (references/merge-check-exit-codes.md),28and Extension Points (references/extension-points.md). Each has a read-when29condition in the body and moved verbatim. The first two run only after a merge30or for a legacy caller; none of the three gates a mutation.31What stayed and why: the Process phases, Tier Definitions (the tier table and32the merge-path rows carry the UNSUPPORTED and STACKED disarm gates), Fix33Patterns (its examples are the late live-state wrapper and the armed34auto-merge thread guard that tests/test_pr_autofix_late_live_state_gate.py35reads in this file), Ready-to-Merge, Force-Push Safety, the Scripts command36block and merge-path table (the only place the guarded merge commands are37spelled), the Completion Gate, Verification, and Anti-Patterns.38The 500-line target is not met: the body stays over it, so size-exception stays.39ADR-064 changed where this file lives, not what it carries.40Preserved invariant: One loaded workflow owns mutation safety, live-state revalidation, and merge readiness.41Behavioral tests: `tests/test_pr_autofix_late_live_state_gate.py`, `tests/test_pr_autofix_force_push_lease.py`, `tests/test_pr_autofix_worktree_identity.py`, `tests/skills/pr-autofix/test_check_pr_round_cap.py`42Review trigger: Revisit when a measured split keeps those tests green and Ready-to-Merge behavior unchanged.43vendor-portability: upstream-only. Test paths reference rjmurillo/ai-agents contributor fixtures; installed plugin consumers do not have these files.44-->4546Autonomous PR monitor and fixer. This file carries the whole protocol,47including the Ready-to-Merge definition below. Two bundled dependencies are48required beyond it, both from the github skill: Phase 0 runs its transport49preflight, and MCP mode reads its routing reference. Everything else needed50to run this skill is here.5152Migrated from the pr-autofix command under ADR-064, which makes skills the single53user-invocable surface. The command file is gone, so its path is named here in54plain text rather than as a citation to something a reader could open.5556## Triggers5758| Trigger phrase | Operation |59|----------------|-----------|60| `pr-autofix` | Triage all open PRs by tier and act |61| `autofix this pr` | Single-PR mode on the current branch's open PR |62| `monitor open prs` | Periodic triage without merging |63| `auto-merge ready prs` | Tier 1 only: enable auto-merge on land-ready PRs |64| `address pr feedback` | Tier 3/4 only: walk thread lifecycle |6566## Process6768Four phases. Tier-based dispatch decides which actions apply per PR.6970### Phase 0: Transport preflight (BLOCKING, runs once)7172Every script this command calls reaches GitHub through `gh`. An agent sandbox73that proxies egress leaves `gh` installed and `GH_TOKEN` set while refusing74GitHub for the whole session, so each script fails with HTTP 403 and none of75those failures says anything about the PR. Decide the transport once, before76triage:7778```bash79# CLAUDE_PLUGIN_ROOT is set in a vendored install; falls back to .claude in-repo.80SCRIPTS_DIR="${COPILOT_PLUGIN_ROOT:-${CLAUDE_PLUGIN_ROOT:-.claude}}/skills/github/scripts/utils"81python3 "$SCRIPTS_DIR/check_github_transport.py"82```8384Non-POSIX hosts do not run the block above. The authoritative, per-harness85launcher for this one command is `check_transport` in the `scripts` map of86`pr-review-config.yaml`: the `copilot` entry runs it under PowerShell and87resolves the interpreter (`python3`, then `py -3`, then `python`), because a88Windows host may expose only the launcher. Read it from the map for the harness89you are on rather than transcribing a second copy here, which would drift.9091| Verdict | Action |92|---------|--------|93| `Transport: gh` | Continue. Every script below works as written. |94| `Transport: gh_unusable` | Continue in MCP mode; see the rule block below. |95| exit 3 | A quota window or a transport wobble, not a transport change. Stop and retry later. |96| exit 4 | A credential fault. Stop and report it; do not switch transports around a fixable token. |9798**MCP mode rules.** The mapping from each script to its GitHub MCP operation99is in the github skill's `references/transport-routing.md`, which also gives100the per-harness spelling for the operation names. On top of it:1011021. Read operations (triage, CI status, check logs, review threads, PR and103 issue bodies) all have MCP equivalents. Use them freely.104 Write operations (replies, resolving threads, arming auto-merge, merging)105 also have MCP equivalents, but rule 3 governs whether you may use them at106 all, and the grant in this file's frontmatter does not include any of them.107 Do not read this row as permission: it says the tool exists, not that the108 operation is allowed here.109 Pushing is not on that list and has no MCP equivalent. `push_files` builds110 a new remote commit out of file contents you supply; it does not transfer111 local commits or branch history, so it cannot stand in for `git push`.1122. `test_pr_merge_ready.py`, `check_pr_live_state.py`, `why_pr_blocked.py`,113 `triage_red_check.py`, `run_completion_gate.py`, `check_pr_round_cap.py`,114 have no MCP equivalent, because each computes a115 verdict from several `gh` calls plus local logic. `triage_red_check.py` is116 named explicitly because the CI-failure triage step below makes it117 mandatory before any log reading, and a blocked session must derive that118 verdict by hand rather than falling back to `gh`. Most of their inputs are119 reachable: gather the same fields with `pull_request_read` and apply the gate120 definitions in this file by hand. Record in the PR handoff that the verdict121 was derived, not scripted.122 One input is not reachable, and it is load-bearing. No exposed MCP operation123 reads a branch ruleset, so the required-context set is unavailable, which is124 exactly the case where a check-run list reads clean on a PR that cannot125 merge. `test_pr_merge_ready.py` therefore cannot be reconstructed as a PASS126 at all. Report the checks and merge state you did read, say the127 required-context set was not read, and treat merge readiness as unknown.1283. The round cap still applies in this mode: it is what stops a T3/T4 PR129 iterating without bound, and it is reconstructed by hand here like the other130 verdicts in rule 2. Concurrency between two sessions working the same branch131 is held by the Force-Push Safety SHA gate below, which is a hard gate rather132 than an advisory one: it re-reads the ref immediately before the push and133 pins `--force-with-lease` to an observed SHA, so a competing session's commit134 makes the push fail rather than silently win. Git is also a separate135 transport from the GitHub API (a push has succeeded while136 the API was failing), so a session refused for the API can still push, and137 the SHA gate is what makes that safe.1381394. A transport failure is an unknown, never a verdict. Never classify a PR as140 T2 (CI fix), BLOCKED, or DIRTY because a call failed. Report the PR as141 untriaged with the transport as the reason.142143### Phase 1: Triage144145Run `test_pr_merge_ready.py` for every open PR. Classify each into a tier (T1-T5) using the table below. Sort the queue by tier ascending.146147### Phase 2: Act per tier148149Walk the queue. For each PR, apply the tier's action set. T1 first (land-ready), then T2 (CI fix), then T3/T4 (threads). T5 applies to bot-authored PRs that pass the merge-state gates (not BEHIND or DIRTY) but still have a failure or unresolved threads, including a BLOCKED one; the tier-dispatch block terminates such a PR after the auto-merge disarm gate so a human handles it. A bot PR that is BEHIND or DIRTY stays at that merge-state tier and the automated loop processes it.150151**Per-PR live-state gate (BLOCKING).** Before any action runs on a PR (any tier: arming auto-merge, pushing a CI fix, posting a thread reply), call `check_pr_live_state.py` and branch on the JSON envelope `Data.action` field. The session-start triage snapshot is stale by the time the walk reaches each row in a repo with heavy merge automation, and the consequences of acting on a stale row are concrete: armed auto-merge on a redundant PR, conflict merges into a closed branch, duplicate logic landed twice.152153```bash154# One outer fetch covers all per-PR calls; --skip-fetch keeps the loop cheap.155git fetch --quiet origin "+refs/heads/main:refs/remotes/origin/main"156resolve_pr_scripts_dir() {157 repo_root="$(git rev-parse --show-toplevel 2>/dev/null || pwd)"158 for root in \159 "${COPILOT_PLUGIN_ROOT:-}" \160 "${CLAUDE_PLUGIN_ROOT:-}" \161 "$repo_root/.claude" \162 "${HOME:-}/.copilot/installed-plugins/_direct/project-toolkit" \163 "${HOME:-}/.copilot/installed-plugins"/*/project-toolkit \164 "${HOME:-}/.claude/plugins/cache"/*/project-toolkit; do165 if [ -n "$root" ] && [ -d "$root/skills/github/scripts/pr" ]; then166 printf '%s\n' "$root/skills/github/scripts/pr"167 return 0168 fi169 done170 printf '%s\n' ".claude/skills/github/scripts/pr"171}172SCRIPTS_DIR="$(resolve_pr_scripts_dir)"173174# late-live-state-guard:start175recheck_pr_live_state() {176 local late_live late_rc late_action late_reason late_state late_head late_base177 if late_live=$(python3 "$SCRIPTS_DIR/check_pr_live_state.py" \178 --pull-request "$PR" --skip-fetch \179 --expected-head-sha "${EXPECTED_HEAD_SHA:-}" \180 --expected-base-ref "${EXPECTED_BASE_REF:-}" \181 --expected-base-sha "${EXPECTED_BASE_SHA:-}" \182 --output-format json); then183 late_rc=0184 else185 late_rc=$?186 fi187188 late_action=$(printf '%s' "$late_live" | jq -r '.Data.action // empty' 2>/dev/null)189 if [ "$late_rc" -eq 0 ] && [ "$late_action" = "ACT" ]; then190 return 0191 fi192193 late_reason=$(printf '%s' "$late_live" | jq -r '.Data.reason // "live-state check failed"' 2>/dev/null)194 late_state=$(printf '%s' "$late_live" | jq -r '.Data.state // "UNKNOWN"' 2>/dev/null)195 late_head=$(printf '%s' "$late_live" | jq -r '.Data.head_sha // "unknown"' 2>/dev/null)196 late_base=$(printf '%s' "$late_live" | jq -r '.Data.base_ref // "main"' 2>/dev/null)197 echo "Skipping mutation for #$PR: $late_reason"198 if [ "$late_state" = "MERGED" ]; then199 echo "Merged head SHA: $late_head"200 echo "Preserve unpushed commits or a net patch. Reapply them on a follow-up branch from current origin/$late_base."201 elif [ "$late_state" = "CLOSED" ]; then202 echo "Closed PR head SHA: $late_head"203 echo "Preserve unpushed commits or a net patch before leaving the old branch."204 fi205 return 75206}207208run_pr_mutation_if_live() {209 if recheck_pr_live_state; then210 "$@"211 return $?212 fi213 return 75214}215# late-live-state-guard:end216217# SESSION_ID must be set before the loop (e.g. from the session log or a uuid).218# Per PR, immediately before any per-tier action:219220# Step 1: Live-state gate (BLOCKING).221LIVE=$(python3 "$SCRIPTS_DIR/check_pr_live_state.py" \222 --pull-request "$PR" --skip-fetch --output-format json)223ACTION=$(echo "$LIVE" | jq -r '.Data.action')224if [ "$ACTION" = "SKIP" ]; then225 REASON=$(echo "$LIVE" | jq -r '.Data.reason')226 echo "Skipping #$PR: $REASON"227 # If Data.superseded_by_base.fully_superseded == true, recommend close228 # via the queue's close-handling path; do NOT push or merge.229 continue230fi231EXPECTED_HEAD_SHA=$(echo "$LIVE" | jq -r '.Data.head_sha // empty')232EXPECTED_BASE_REF=$(echo "$LIVE" | jq -r '.Data.base_ref // empty')233EXPECTED_BASE_SHA=$(echo "$LIVE" | jq -r '.Data.base_sha // empty')234if [ -z "$EXPECTED_HEAD_SHA" ] || [ -z "$EXPECTED_BASE_REF" ] || [ -z "$EXPECTED_BASE_SHA" ]; then235 echo "Cannot bind mutation to the live PR identity for #$PR; skipping."236 continue237fi238# ACTION == "ACT": proceed with the tier's planned action set.239240# tier-dispatch:start241# Step 2.5: Tier read, then the auto-merge disarm gate, then the round-cap242# circuit breaker (BLOCKING for T3/T4). The two gates run in that243# order for the reason given at the disarm gate below; do not swap them back.244# T3/T4 PRs iterate: post a fix, wait for CI or a bot review, repeat. Nothing245# capped how many times that loop could run, and prose caps have been246# ignored repeatedly (the documented failure mode, not a hypothetical one):247# one PR ran 11+ bot review rounds over 46 hours wall clock before a human248# intervened, and two others each ran 18 rounds. check_pr_round_cap.py records one round per call against a249# hidden marker comment on the PR (stored as250# a hidden marker comment) and returns Data.action=ESCALATE when251# either the round count or the wall-clock budget is exceeded. Call it once252# per pass through this loop for a T3/T4 PR, after the tier is known and after253# the auto-merge disarm gate below, before any thread-lifecycle or CI-fix254# action. It used to say "immediately after the tier is known", which was true255# until the disarm gate moved ahead of it to close CWE-284; the disarm gate and256# the unknown-tier exit now both run in between.257# Tier comes from test_pr_merge_ready.py, the authoritative tier source;258# check_pr_live_state.py emits no tier field, so reading $LIVE here pins TIER259# at UNKNOWN. Computed once, also consumed by the auto-merge disarm gate below.260# Read `.Tier`, not `.Data.Tier`: unlike the github_core.output emitters,261# test_pr_merge_ready.py has no --output-format flag and prints its result262# dict directly (`print(json.dumps(result, indent=2))`), so there is no Data263# envelope to traverse.264# A pinned UNKNOWN breaks the two gates in OPPOSITE directions, so do not265# read it as "the gates turn off": this gate tests TIER = T3 or T4, which266# UNKNOWN never satisfies, so it goes inert; the disarm gate below tests267# TIER != T1, which UNKNOWN always satisfies, so it fires on every armed PR268# and strips auto-merge from genuine T1 PRs too.269# tests/commands/test_pr_autofix_field_contract.py checks every read in this270# file against its producer's real schema, and271# tests/commands/test_pr_autofix_tier_dispatch_runtime.py executes the block272# between the tier-dispatch markers under bash with fake producers, so the two273# gate directions below are asserted behavior rather than described behavior.274if ! AUTHOR_CTX=$(python3 "$SCRIPTS_DIR/get_pr_context.py" --pull-request "$PR" \275 --field author_is_bot --output-format json 2>/dev/null); then276 # Focused mode keeps this read off the review-thread pagination path. A277 # stale installed helper can still reject `--field`; fall back once so the278 # existing absent-field diagnostic keeps naming a copy that predates the author_is_bot field rather279 # than collapsing it into the generic unreadable branch.280 if ! AUTHOR_CTX=$(python3 "$SCRIPTS_DIR/get_pr_context.py" --pull-request "$PR" \281 --output-format json 2>/dev/null); then282 AUTHOR_CTX=""283 fi284fi285# Bot-author lookup, read BEFORE the tier producer because the tier depends on286# it. classify_tier only reaches T5 when `is_bot and287# (has_ci_failures or has_threads)`, and its `is_bot` parameter defaults to288# False, so a producer call that omits --is-bot cannot return T5 at all: every289# affected bot PR that reached work-tier classification came back T2, T3, or T4290# and was processed in the unattended loop. T5 is reached only when the291# merge state passes the earlier gates (not BEHIND or DIRTY) AND292# `is_bot and (has_ci_failures or has_threads)`. BLOCKED with a failure or a293# thread reaches T5 too. A bot PR that is BEHIND or DIRTY stays294# at its merge-state tier and does not reach the T5 handoff, which is correct:295# the automated loop handles it.296# Author identity is stable during one pass, so this answer is kept for tier297# production. The focused `--field author_is_bot` mode keeps the read down to298# one `gh pr view --json author` call instead of a full context walk. Auto-merge299# is mutation-sensitive and is fetched again at the disarm gate below, in the300# matching `--field auto_merge_method` mode. That split is deliberate: the301# one-fetch contract is retired because a stale auto-merge verdict fails open.302# The classification itself is NOT made here. get_pr_context.py emits303# `author_is_bot` from github_core.bot_config.is_bot, the repository's one304# authoritative bot-author rule. Re-deriving it here as a `[bot]` suffix test305# would disagree with that rule on the logins this repository actually sees:306# bot_config.py maps `app/copilot-swe-agent`, the spelling `gh pr view --json307# author` returns for the Copilot coding agent, onto `copilot-swe-agent[bot]`,308# and neither that spelling nor `Copilot` carries a `[bot]` suffix.309# jq can emit a valid first value then exit nonzero on a malformed suffix.310# The assignment must be the condition: checking the document with a second jq311# call can succeed on a later value even when this filter failed.312if ! IS_BOT=$(printf '%s' "$AUTHOR_CTX" | jq -r 'if (.Data | has("author_is_bot") | not) then "absent" elif (.Data.author_is_bot | type) == "boolean" then (.Data.author_is_bot | tostring) else "unknown" end' 2>/dev/null); then313 IS_BOT="unknown"314fi315# `absent` is a separate verdict from `unknown` because it has a separate cause316# and a separate remedy. resolve_pr_scripts_dir above tries $COPILOT_PLUGIN_ROOT317# then $CLAUDE_PLUGIN_ROOT, then $repo_root/.claude, and only after that the three318# installed-plugin caches; the caches never outrank the checkout, which is what319# ci-scripts.md MUST-8 requires. So $SCRIPTS_DIR/get_pr_context.py is a stale copy320# in exactly two situations: either plugin-root variable is set and points at an321# install that predates the fix, or this session is running outside a checkout that322# carries skills/github/scripts/pr and falls through to a cache. Diagnose in that323# order, plugin roots first. A copy predating the author_is_bot field emits no324# author_is_bot key at all, which fails closed like any other unreadable author325# and would otherwise reclassify EVERY PR with a failing check or an unresolved326# thread as T5, repo-wide, announced by one indistinguishable line. Naming the327# stale helper is what turns that from a silent reclassification into a fixable328# report. Same hazard the "Checkout ownership for the readiness helper"329# section below records for test_pr_merge_ready.py.330# Empty stdin or a jq parse error yields an empty string, not "unknown", which is331# neither "false" nor any verdict the branch below can name; the fail-closed332# branch would then be taken with no message at all. The sibling AUTO_MERGE read333# further down documents the same trap. Normalize it here so every path out of334# this read is a verdict with a name.335IS_BOT=${IS_BOT:-unknown}336# Fail CLOSED: an author this session could not classify is treated as a bot.337# Fail CLOSED here because the two errors are not symmetric.338# Guessing "human" on an unreadable author hands a PR nobody vouched for to the339# unattended loop, which is the outcome the T5 tier exists to prevent.340# Guessing "bot" costs a human one manual look at a PR that may not have needed341# one, which is recoverable. Only a real JSON boolean `false` buys the342# non-bot path; a missing field, a null, or a string spelling of a boolean is343# "absent" or "unknown" and takes the closed branch, matching the type-checked344# read the PAGES_COMPLETE guard below uses for the same reason.345# The notice fires on anything that is not the literal `true`, not on the two346# named verdicts, so a future value out of the jq expression cannot slip through347# the closed branch unannounced the way the empty string did.348if [ "$IS_BOT" = "false" ]; then349 IS_BOT_FLAG=""350else351 IS_BOT_FLAG="--is-bot"352 if [ "$IS_BOT" = "absent" ]; then353 echo "Cannot read author bot state for #$PR: $SCRIPTS_DIR/get_pr_context.py emits no author_is_bot field, so that helper is outdated; reinstall the plugin or run from the repository checkout. Classifying as a bot PR (fail closed)."354 elif [ "$IS_BOT" != "true" ]; then355 echo "Cannot read author bot state for #$PR; classifying as a bot PR (fail closed)."356 fi357fi358# Unquoted on purpose, and this is the one place in this block where that is359# correct: the variable holds either the single literal token --is-bot or the360# empty string, and quoting it would pass an empty argument that argparse361# rejects. It is never attacker-influenced; both values are written above.362# shellcheck disable=SC2086363# The tier this produces gates the auto-merge disarm below via364# TIER_TRUSTED_T1, and this runs against the checked-out PR branch with no365# trusted-ref comparison, so it must NOT read --dispositions-file. A PR that366# edited the registry could dispose its own failing security check, reach T1,367# and keep auto-merge armed (CWE-829, CWE-284). Only the completion gate,368# which byte-compares every tracked file its criteria name against the369# trusted ref first, may honor a disposition.370if MERGE_READY=$(python3 "$SCRIPTS_DIR/test_pr_merge_ready.py" --pull-request "$PR" $IS_BOT_FLAG 2>/dev/null); then371 MERGE_READY_RC=0372else373 MERGE_READY_RC=$?374fi375# Deliberately no 2>/dev/null on either jq below. The producer's stderr is376# suppressed above, so a jq parse error is the only signal an operator gets that377# the producer emitted something unreadable, and both guards below would378# otherwise skip the PR with no explanation. Adding the redirect here was tried379# and the runtime suite failed it by name; see the malformed-producer case.380if ! TIER=$(printf '%s' "$MERGE_READY" | jq -r '.Tier // "UNKNOWN"'); then381 TIER="UNKNOWN"382fi383TIER=${TIER:-UNKNOWN}384# Captured once and read twice, because the tier alone does not say whether the385# evidence behind it was complete. classify_tier returns T1 on CanMerge, and386# CanMerge is `len(reasons) == 0` with fetched_pages_complete computed after it387# and never appended to reasons (test_pr_merge_ready.py, check_merge_readiness).388# So a fetch truncated at the pagination cap that happens to surface no389# unresolved thread and no failing required check classifies T1, which the390# producer's own docstring warns about: "a partial fetch that happens to find no391# failing checks is not evidence that no failing checks exist."392# This mattered only after the tier read above was fixed. While TIER was pinned393# at UNKNOWN, TIER != T1 held for every PR, so the disarm gate below stripped394# auto-merge from the truncated-fetch case by accident. Making T1 reachable395# removes that accident, so the exemption has to be earned rather than assumed.396# Anything other than the literal `true` denies the exemption: the real producer397# always emits the boolean, so healthy input is unaffected, and a missing or398# unreadable field is exactly the state that must not buy a merge.399# The read has been wrong twice, in opposite directions, so both are pinned.400# First it said `// "unknown"`, and jq's alternative operator fires on `false`401# as well as `null`, so a producer reporting an incomplete fetch was relabelled402# "unknown": the operator was told the field could not be read when it had been403# read fine. Both deny the exemption, which is why no test could tell them apart404# until one was added that reads the message.405# Then the repair used a bare `tostring`, which does not check the JSON type, so406# the *string* "true" came out as `true` and bought the exemption. That is the407# worse direction: malformed evidence granting a merge is the thing this guard408# exists to refuse. Only a real JSON boolean is accepted now; every other type,409# including a string spelling of a boolean, is "unknown" and denies.410if ! PAGES_COMPLETE=$(printf '%s' "$MERGE_READY" | jq -r 'if (.fetched_pages_complete | type) == "boolean" then (.fetched_pages_complete | tostring) else "unknown" end'); then411 PAGES_COMPLETE="unknown"412fi413PAGES_COMPLETE=${PAGES_COMPLETE:-unknown}414# Exit 1 is the producer's documented not-ready verdict and is valid for every415# non-T1 tier. Any higher exit, or T1 paired with exit 1, contradicts the416# payload and cannot buy a merge.417if [ "$MERGE_READY_RC" -gt 1 ] || { [ "$MERGE_READY_RC" -eq 1 ] && [ "$TIER" = "T1" ]; }; then418 TIER="UNKNOWN"419 PAGES_COMPLETE="unknown"420fi421# .claude/skills/pr-review/pr-review-config.yaml already ANDs this field into its422# completion-gate criterion, so this is the same safety rule applied at the423# other place a merge can be armed, not a new policy.424# Fail closed on a tier the producer never declared. Empty or malformed stdout425# and a JSON error object all normalize to UNKNOWN. That skips the T3/T4 breaker426# below AND satisfies427# TIER != T1 in the disarm gate, so without this guard the loop would keep428# acting on a PR whose tier it never learned. Acting is the harm here; disarming429# is not, so the guard stops the acting and still runs the disarm gate.430# Do not gate on exit status instead:431# test_pr_merge_ready.py exits 1 for any not-merge-ready PR, so T2 through T4 are432# legitimately non-zero.433# The accepted set is the producer's own, quoted verbatim from434# test_pr_merge_ready.py, which classify_tier's docstring names as the range of435# its return value:436# _TIER_ORDER = (437# "T1", "T2", "T3", "T4", "T5",438# "BEHIND", "BLOCKED", "DIRTY", "SKIP", "UNSUPPORTED", "STACKED",439# )440# The six beyond the T1-T5 ladder are real: SKIP for a draft, closed, or merged441# PR, BEHIND/DIRTY from the merge-state lookup, BLOCKED for a PR waiting on an442# outside gate with no failure or thread, and UNSUPPORTED for a443# mergeStateStatus this repository has no verified merge path for, and STACKED444# for a merge-ready PR whose base is not the default branch.445# Listing only446# the ladder rejected those as producer failures and silently disabled the447# documented BEHIND and DIRTY handling.448# tests/commands/test_pr_autofix_tier_contract.py pins this list against the449# producer so the two cannot drift apart again.450# Recognized and actionable are two different questions, and collapsing them is451# what put SKIP on the acting path. The tier table below reads452# "| SKIP | Draft, merged, or closed | No action |", so SKIP terminates here.453# Letting it reach the disarm gate means TIER != T1 holds and auto-merge is454# stripped from a PR that went draft, merged, or closed after the live-state455# gate ran.456# SKIP and an unknown tier both terminate the PR, but at different points, and457# the difference is which one has a reason not to disarm. SKIP names a state:458# the PR is a draft, merged, or closed, so stripping auto-merge is either459# meaningless or destroys a choice its author made deliberately. An unknown tier460# names no state at all, so "armed but not provably T1" is exactly true of it,461# which is the disarm gate's own trigger condition. It therefore falls through462# to that gate and stops immediately after, before the round-cap breaker and463# before any tier action.464# The cost of that direction is real and is accepted: a transient producer465# failure on a healthy T1 PR strips an auto-merge its author armed, and they466# have to arm it again. The other direction leaves a PR this session could not467# assess free to land itself, which is not recoverable. Copilot reported the468# arm as it first shipped, where it exited before the disarm gate; that made a469# producer crash the one path where this loop leaves auto-merge armed on a PR470# it never assessed, and contradicted this change's own claim that the armed471# set only shrinks.472# UNSUPPORTED is recognized and terminates, like SKIP, but it terminates one473# gate later, for the same reason the unknown-tier arm does. SKIP names a state474# whose author chose it, so stripping auto-merge would destroy that choice.475# UNSUPPORTED names a mergeStateStatus with no verified merge path, so "armed476# but not provably T1" is exactly true of it and the disarm gate below must run477# first. It is a separate arm rather than a T4 because T4 dispatches into the478# round-cap thread-fix loop, and an UNSUPPORTED PR routinely carries zero479# threads and zero CI failures: that loop would have no action to take and480# would terminate only by burning the round cap and posting an escalation481# comment on a PR with nothing to escalate.482# STACKED terminates at the same point as UNSUPPORTED, for the same reason, and483# it is the T1 arm's replacement, not a new kind of work. The producer returns it484# only for a PR that would otherwise be T1, so every check, thread, and485# merge-state gate already passed. What remains is the merge step, and the squash486# merge in the T1 path folds a PR into its base: for a stacked PR that base is487# the parent PR's branch, so the merge collapses the stack instead of landing488# work on the default branch (observed on a stacked series where489# triage reported T1, CLEAN, CanMerge=true for every member). It is490# "armed but not provably T1", so the disarm gate below runs first. T3 and T4491# would have no action to take, so it must not enter the round-cap loop.492TIER_KNOWN=yes493TIER_TERMINAL=no494case "$TIER" in495 SKIP)496 echo "Tier SKIP for #$PR (draft, merged, or closed); no action."497 continue498 ;;499 UNSUPPORTED)500 MERGE_STATE=$(printf '%s' "$MERGE_READY" | jq -r '.MergeStateStatus // ""')501 echo "Tier UNSUPPORTED for #$PR (mergeStateStatus '${MERGE_STATE:-<missing>}' has no verified merge path); disarming auto-merge if armed, then skipping."502 TIER_TERMINAL=yes503 ;;504 STACKED)505 BASE_REF=$(printf '%s' "$MERGE_READY" | jq -r '.BaseRef // ""')506 DEFAULT_BRANCH=$(printf '%s' "$MERGE_READY" | jq -r '.DefaultBranch // ""')507 echo "Tier STACKED for #$PR (base '${BASE_REF:-<missing>}' is not the default branch '${DEFAULT_BRANCH:-<missing>}'); disarming auto-merge if armed, then handing to a human."508 TIER_TERMINAL=yes509 ;;510 T1|T2|T3|T4|T5|BEHIND|BLOCKED|DIRTY) ;;511 *)512 echo "Cannot determine tier for #$PR (tier producer failed or emitted no tier); disarming auto-merge if armed, then skipping."513 TIER_KNOWN=no514 ;;515esac516# Ordered before the round-cap breaker deliberately, and this order is load517# bearing. The breaker's ESCALATE path terminates the PR, and while it sat first518# that exit ran before this gate, so a T3 or T4 PR that reached its cap was519# handed to a human with native auto-merge still armed: GitHub can then land it520# on its own, with readiness never proven by this session (CWE-284). Copilot521# found it. Like the completeness case above it was opened by the tier-read fix522# rather than found beside it, since a pinned UNKNOWN never matched T3 or T4, so523# the breaker never fired and this gate disarmed every armed PR anyway.524# Disarming is not acting on a PR, it is taking a capability away from one, so525# there is no tier this is unsafe to run first. A test asserted the opposite526# contract and is flipped in the same change.527# Step 2.6: Auto-merge disarm gate (BLOCKING). Numbered after the528# tier read and before the round-cap breaker, which is where it now runs.529# If the PR has auto-merge armed but is not T1-ready, a conflict refresh or CI530# fix push could immediately land a PR whose readiness was never explicitly531# verified in this session. Disable auto-merge now, before any commit or push.532# TIER and PAGES_COMPLETE were both read from the readiness producer above.533# Refresh context here because auto-merge can be armed while readiness is being534# fetched. Reusing the author lookup would let that stale null bypass disarm,535# so this gate deliberately spends a second context read for fresh evidence.536if ! CTX=$(python3 "$SCRIPTS_DIR/get_pr_context.py" --pull-request "$PR" \537 --field auto_merge_method \538 --output-format json 2>/dev/null); then539 CTX=""540fi541if ! AUTO_MERGE=$(printf '%s' "$CTX" | jq -r 'if (.Data | has("auto_merge_method") | not) then "unknown" elif (.Data.auto_merge_method | type) == "string" then .Data.auto_merge_method elif (.Data.auto_merge_method | type) == "null" then "null" else "unknown" end' 2>/dev/null); then542 AUTO_MERGE=""543fi544# Empty stdin or a jq parse error yields an empty string, not a verdict.545# A schema-invalid value such as `false` is also unreadable evidence here:546# `false // "null"` would launder it into "definitely unarmed" and bypass the547# disarm gate on malformed input. Accept only a string or a real null.548AUTO_MERGE=${AUTO_MERGE:-unknown}549if [ "$AUTO_MERGE" = "unknown" ]; then550 echo "Cannot read auto-merge state for #$PR (context fetch or parse failed); skipping."551 continue552fi553# "Not provably T1" rather than "not T1": a T1 whose evidence came from a554# truncated fetch has not earned the exemption, so it disarms with the rest.555if [ "$TIER" = "T1" ] && [ "$PAGES_COMPLETE" = "true" ]; then556 TIER_TRUSTED_T1=yes557else558 TIER_TRUSTED_T1=no559fi560if [ "$AUTO_MERGE" != "null" ] && [ "$TIER_TRUSTED_T1" != "yes" ]; then561 if [ "$TIER" = "T1" ]; then562 echo "Auto-merge armed on #$PR and the tier is T1, but the merge-readiness fetch was incomplete (fetched_pages_complete=$PAGES_COMPLETE); disabling before acting."563 else564 echo "Auto-merge armed on non-T1 PR #$PR (method: $AUTO_MERGE); disabling before acting."565 fi566 # No --output-format needed here. set_pr_auto_merge.py once registered no567 # such option, so argparse exited 2 before the mutation ran and this gate568 # took its failure branch on every armed non-T1 PR, leaving auto-merge569 # armed. The script now accepts the flag, and the default570 # already prints the AutoMergeEnabled object the verification checklist571 # asks for.572 if run_pr_mutation_if_live \573 python3 "$SCRIPTS_DIR/set_pr_auto_merge.py" \574 --pull-request "$PR" --disable; then575 MUTATION_RC=0576 else577 MUTATION_RC=$?578 fi579 # Captured in both arms rather than read from $? inside the else. The580 # single-arm form holds the right value today only because nothing sits581 # between the `if` and the read; this form does not depend on that.582 if [ "$MUTATION_RC" -ne 0 ]; then583 if [ "$MUTATION_RC" -ne 75 ]; then584 # 75 is the wrapper's own skip and it already printed the reason.585 # Any other status means the disable was attempted and did not586 # land, so auto-merge is still armed on a PR whose readiness this587 # session never verified. Say that. The old wording, "skipping to588 # avoid unguarded merge", named the opposite of the state it left.589 echo "Failed to disable auto-merge on #$PR (rc=$MUTATION_RC); auto-merge is still armed and GitHub can land the PR unattended. Skipping; this one needs a human."590 fi591 continue592 fi593fi594# The unknown-tier, UNSUPPORTED, and STACKED arms resume here, one gate later595# than SKIP leaves, so all three have had auto-merge stripped above. Everything596# below needs a tier with an action behind it, and none of these has one, so all597# three stop now.598if [ "$TIER_KNOWN" = "no" ] || [ "$TIER_TERMINAL" = "yes" ]; then599 continue600fi601# T5 terminates here, and making it reachable is what created the need. The602# round-cap breaker below fires on T3 and T4 only, which was complete while603# --is-bot was never forwarded: a bot PR with threads or CI failures classified604# T3 or T4 and hit the breaker. Now the same PR classifies T5, so without this605# arm it would fall past a condition that no longer matches, into the tier606# actions, with no cap and no human handoff. That is strictly worse than the607# behavior the flag was added to fix: the breaker is the circuit added after a PR608# ran 11+ rounds over 46 hours, and T5 would have been the609# one tier running the unattended loop with it switched off.610# The tier table reads "| T5 | Bot PR that passes merge-state gates but has611# failures or threads | Handle individually |", so the executable arm is a612# handoff rather than a capped loop.613# Placed here rather than at the SKIP arm for the reason that arm records: SKIP614# names a state where disarming is meaningless or destructive, while a T5 PR is615# "armed but not provably T1", which is the disarm gate's own trigger condition.616# It therefore falls through that gate first, exactly like the unknown-tier exit617# one gate above, and stops before any tier action.618if [ "$TIER" = "T5" ]; then619 echo "Tier T5 for #$PR (bot-authored, passed merge-state gates, has failure or threads); handing to a human."620 continue621fi622if [ "$TIER" = "T3" ] || [ "$TIER" = "T4" ]; then623 # This loop runs from the shared checkout, whose HEAD is not624 # the PR's. The orphaned-commit scan compares the live PR head with a local625 # HEAD, so point it at the worktree that holds the PR branch. Without it the626 # ancestry check exits 1 or 128 and the scan reports `unverified` with no627 # `.commits` and no `force_push_suspected`; read `reason`. No matching628 # worktree passes no flag, and the script falls back to the current629 # directory.630 PR_HEAD_REF=$(printf '%s' "${LIVE:-}" | jq -r '.Data.head_ref // empty' 2>/dev/null)631 PR_HEAD_REPO=$(printf '%s' "${LIVE:-}" | jq -r '.Data.head_repo // empty' 2>/dev/null)632 PR_WORKTREE=""633 # A branch name is chosen by the PR author, so the ref alone does not identify634 # the worktree. Also require that its origin is the PR head repository. HEAD635 # need not hold the live head: a force-pushed PR leaves the worktree diverged,636 # and that is the case this scan lists. The result feeds a report, so this is637 # looser than the exact head match cleanup demands before it deletes.638 # A missing input matches nothing: no --worktree is passed.639 # pr-worktree-select:begin640 if [ -n "$PR_HEAD_REF" ] && [ -n "$PR_HEAD_REPO" ] && [ -n "$EXPECTED_HEAD_SHA" ]; then641 WANT_REPO=$(printf '%s' "$PR_HEAD_REPO" | tr 'A-Z' 'a-z')642 # awk fields are written $(N), not $N: the skill loader rewrites a bare $<digit> as an argument.643 while IFS= read -r CANDIDATE; do644 [ -n "$CANDIDATE" ] || continue645 ORIGIN_URL=$(git -C "$CANDIDATE" remote get-url origin 2>/dev/null | tr 'A-Z' 'a-z')646 ORIGIN_URL=${ORIGIN_URL%/}647 ORIGIN_URL=${ORIGIN_URL%.git}648 case "$ORIGIN_URL" in649 *"/$WANT_REPO" | *":$WANT_REPO") PR_WORKTREE="$CANDIDATE"; break ;;650 esac651 done < <(git worktree list --porcelain 2>/dev/null | awk -v ref="refs/heads/$PR_HEAD_REF" \652 '/^worktree /{path=substr($(0), 10)} $(1) == "branch" && $(2) == ref {print path}')653 fi654 # pr-worktree-select:end655 ROUND_CAP_ARGS=(--pull-request "$PR" --output-format json)656 if [ -n "$PR_WORKTREE" ]; then657 ROUND_CAP_ARGS+=(--worktree "$PR_WORKTREE")658 fi659 ROUND_CAP=$(python3 "$SCRIPTS_DIR/check_pr_round_cap.py" "${ROUND_CAP_ARGS[@]}")660 ROUND_ACTION=$(echo "$ROUND_CAP" | jq -r '.Data.action // empty')661 # The scan result is set when the record is escalated, including an ACT662 # verdict right after a reset. Print it on every arm: it names the local663 # commits the live head lacks, and the reader should not run git log by hand.664 ROUND_ORPHANS=$(echo "$ROUND_CAP" | jq -r '.Data.orphaned_warning // empty')665 if [ -n "$ROUND_ORPHANS" ]; then666 echo "$ROUND_ORPHANS"667 fi668 if [ "$ROUND_ACTION" != "ACT" ]; then669 ROUND_REASON=$(echo "$ROUND_CAP" | jq -r '.Data.reason // "round-cap check f670671…(truncated)