Skip to content

Latest commit

 

History

History
334 lines (267 loc) · 14.7 KB

File metadata and controls

334 lines (267 loc) · 14.7 KB

GitHub: pull-request ready for review

The GitHub commands behind the pull-request skill's ready-for-review phase. The phase owns the order, the gates and the completion criteria; this file holds the commands and the GitHub and gh facts behind them.

Find the PR for the branch

The repository is resolved once, before the PR, and every read and write below targets it (target repository): the writes name it, and the exported GH_REPO carries it to every other gh call, the scripts' included. A shell that runs a later block runs this block's first two lines first. A non-zero exit from target-repo.sh ends the phase with its stderr reported. <checkout> is the checkout of the PR's repository the session works on, as 2.5.3 defines it, so neither the repository nor the branch depends on the shell's directory.

REPO=$(bash "<skill-dir>/scripts/target-repo.sh" --dir "<checkout>") || exit 1
export GH_REPO="$REPO"
BRANCH=$(git -C "<checkout>" branch --show-current)
PR_NUMBER=$(gh pr view "$BRANCH" -R "$REPO" --json number -q '.number' 2>/dev/null)

Read the draft flag

gh pr view "$PR_NUMBER" --json isDraft -q '.isDraft'

Check for a hold

bash "<skill-dir>/scripts/check-ready-holds.sh" "$PR_NUMBER"               # a person drives the run
bash "<skill-dir>/scripts/check-ready-holds.sh" "$PR_NUMBER" --unattended  # no person drives it

Exit 0: no hold. Exit 3: held or superseded, one reason per line on stdout. Exit 2: a gh read or a parse failed, so no hold was ruled out. Exit 1: a bad argument. Exit 5: gh or jq is missing. The script reads the title, body, labels and closing issue references with gh pr view, and each closing issue's state over REST.

Read the pre-ready steps at the base

The PR's own base branch, in the PR's own base repository. The repository comes from the PR's URL, which names the base repository, never from gh's {owner}/{repo} default: in a fork checkout with no upstream remote, that default resolves to the fork the PR's author controls. -f ref= with -X GET sends the branch name as an encoded query parameter. -i puts the status line on stdout, where the reader reads it: only a 404 means no file, and any other failure (auth, 5xx, no response) fails closed.

The reader honors the list only when the base is the base repository's default branch, read from that same repository. A failed lookup leaves the value empty and the reader fails closed on it: on error gh api prints the error body to stdout, so each lookup clears its value on a non-zero exit.

BASE=$(gh pr view "$PR_NUMBER" --json baseRefName -q '.baseRefName') || BASE=""
BASE_REPO=$(gh pr view "$PR_NUMBER" --json url -q '.url | split("/")[3:5] | join("/")') || BASE_REPO=""
DEFAULT_BRANCH=$(gh api "repos/$BASE_REPO" --jq '.default_branch') || DEFAULT_BRANCH=""
PRE_READY_RESPONSE=$(gh api -i -X GET "repos/$BASE_REPO/contents/docs/conventions/source-control.yaml" \
  -f ref="$BASE" -H "Accept: application/vnd.github.raw")
printf '%s' "$PRE_READY_RESPONSE" |
  bash "<skill-dir>/scripts/read-pre-ready.sh" --base "$BASE" --default-branch "$DEFAULT_BRANCH" --http-response

On a 404, gh also prints gh: Not Found (HTTP 404) to stderr; that line is expected.

Record the head before the refresh

Run the wait, flip and confirm blocks below in the same shell as this one, since they share HEAD_BEFORE, HEAD_SHA, RUNS_BEFORE and ready_run_seen. When 2.5.2 is skipped, still run this line, before the push.

HEAD_BEFORE=$(gh pr view "$PR_NUMBER" --json headRefOid -q '.headRefOid') || exit 1

Read the base branch

BASE=$(gh pr view "$PR_NUMBER" --json baseRefName -q '.baseRefName')

Refresh the base with a merge

Never on a Dependabot head: delegate requests its rebase instead, as merge.md, Behind-branch exceptions says.

The update names the decision's head_sha as expected_head_sha, pinning it to that decision. We wait up to 60 seconds for the head to leave head_sha before fetching it; UPDATED=0 after the block is a failed update. DECISION is the decision the phase read; a run that lost it reads it again. <branch-checkout> is the checkout holding the branch, as the phase's update sequence defines it.

DECISION_HEAD=$(jq -r .head_sha <<<"$DECISION") || exit 1
[ -n "$DECISION_HEAD" ] && [ "$DECISION_HEAD" != unknown ] || exit 1

UPDATED=0
if gh api --method PUT "repos/$REPO/pulls/$PR_NUMBER/update-branch" \
  -f expected_head_sha="$DECISION_HEAD" >/dev/null; then
  for _ in $(seq 12); do   # 12 polls x 5 s = 60 s
    NOW=$(gh pr view "$PR_NUMBER" --json headRefOid -q '.headRefOid')
    [ -n "$NOW" ] && [ "$NOW" != "$DECISION_HEAD" ] && { UPDATED=1; break; }
    sleep 5
  done
fi
[ "$UPDATED" = 1 ] && git -C "<branch-checkout>" fetch "$REMOTE" "$BRANCH" &&
  git -C "<branch-checkout>" merge --ff-only FETCH_HEAD

The PR's head commit, for the completion check:

gh pr view "$PR_NUMBER" --json headRefOid -q '.headRefOid'

Read the base's review and signing rules

Both answers come from the base's rulesets and, where one exists, its classic branch protection. A protection read that fails counts as no rule.

RULES=$(gh api --paginate --slurp "repos/$REPO/rules/branches/$BASE" | jq -c 'add // []')
CLASSIC=$(gh api "repos/$REPO/branches/$BASE/protection" 2>/dev/null) || CLASSIC='{}'
# true: an update dismisses approvals
jq -nr --argjson r "$RULES" --argjson c "$CLASSIC" 'any($r[]; .type == "pull_request"
  and .parameters.dismiss_stale_reviews_on_push == true)
  or $c.required_pull_request_reviews.dismiss_stale_reviews == true'
# true: the base requires signed commits
jq -nr --argjson r "$RULES" --argjson c "$CLASSIC" 'any($r[]; .type == "required_signatures")
  or $c.required_signatures.enabled == true'

Whether the head commit is signed, for the same choice:

git -C "<branch-checkout>" cat-file commit HEAD | grep -q '^gpgsig' && echo signed

Post the range-diff

Exit 0 means the pull request has a reviewer: a person's review, or a review request. Post the comparison after the push, in one conversation comment.

PEOPLE=$(gh api --paginate --slurp "repos/$REPO/pulls/$PR_NUMBER/reviews" |
  jq 'add // [] | map(select(.user.type != "Bot")) | length')
REQUESTED=$(gh pr view "$PR_NUMBER" --json reviewRequests -q '.reviewRequests | length')
[ "${PEOPLE:-0}" -gt 0 ] || [ "${REQUESTED:-0}" -gt 0 ]
{
  echo 'Rebased onto the base. Before and after (`git range-diff`):'
  echo '```text'
  cat "$RANGE_DIFF_FILE"
  echo '```'
} | gh pr comment "$PR_NUMBER" -R "$REPO" --body-file -

Read the diff

gh pr diff "$PR_NUMBER"

Read the closing claims

The issues GitHub would close on merge, each with its repository, then each issue's body and open sub-issues read in that repository, and the body's Siblings: line. Unlike the Refs issue read, no read here swallows a failure: a non-zero exit or an empty body is a failed read, which the phase counts as not delivered.

CLAIMS=$(gh pr view "$PR_NUMBER" --json closingIssuesReferences \
  -q '.closingIssuesReferences[] | "\(.repository.owner.login)/\(.repository.name) \(.number)"') || exit 1
while read -r ISSUE_REPO ISSUE_NUM; do
  [[ -n "$ISSUE_NUM" ]] || continue
  gh issue view "$ISSUE_NUM" --repo "$ISSUE_REPO" --json state,body,subIssues   # a failure here is a failed read
done <<< "$CLAIMS"
gh pr view "$PR_NUMBER" --json body -q '.body' | grep -E '^Siblings: '

Record the skipped steps

One conversation comment per run, after the hold re-check and right before the flip. One --step per step --skip removed; the comment is built in full before it is posted, so a failed build posts nothing:

LOGIN=$(gh api user --jq .login) || exit 1
COMMENT=$(bash "<skill-dir>/scripts/ready-skip-comment.sh" --login "$LOGIN" \
  --reason "$REASON" --step code-review) || exit 1
printf '%s\n' "$COMMENT" | gh pr comment "$PR_NUMBER" -R "$REPO" --body-file -

check-ready-holds.sh reads the title, body, labels and closing issue references, never comments, so the comment cannot set or lift a hold there.

Wait for the push's CI run

The run lists here and below name no workflow: they count every pull_request run for the head SHA, so they work in any repository without knowing its CI file name. A run listed for the head SHA means the push's event reached the workflows; the wait never looks at a run's result. The push starts one run per workflow, possibly a few seconds apart, so the wait ends only when the count is above zero and unchanged across two polls, keeping a late sibling out of the flip's snapshot. Skip the wait when the head is unchanged, but still run the PR_TREE and HEAD_SHA assignments, which the flip block reads.

HEAD_SHA is the PR worktree's HEAD, the commit the verify gate recorded: pr-worktree.sh finds the worktree that has the PR's head branch checked out with the PR's head commit in its history, whichever checkout the shell sits in, and exits non-zero when none has. <checkout> is the checkout the phase names (PR worktree), and the flip's verify-gate.sh check reads the record through --dir "$PR_TREE". GitHub's headRefOid can lag a push by a read, so the block polls the PR's head until it equals HEAD_SHA, up to 60 seconds, instead of trusting the first read. A head that never matches (a peer push, a push that failed, local commits never pushed) leaves HEAD_MATCH=0, and the flip below refuses.

PR_TREE=$(bash "<skill-dir>/scripts/pr-worktree.sh" --pr "$PR_NUMBER" --dir "<checkout>") || exit 1
HEAD_SHA=$(git -C "$PR_TREE" rev-parse HEAD) || exit 1
HEAD_MATCH=0
for _ in $(seq 12); do   # 12 polls x 5 s = 60 s
  [ "$(gh pr view "$PR_NUMBER" --json headRefOid -q '.headRefOid')" = "$HEAD_SHA" ] && { HEAD_MATCH=1; break; }
  sleep 5
done
if [ "$HEAD_SHA" != "$HEAD_BEFORE" ]; then
  FOUND=0 PREV=0
  for _ in $(seq 18); do   # 18 polls x 5 s = 90 s
    N=$(gh run list --commit "$HEAD_SHA" --event pull_request -L 100 \
      --json databaseId -q 'length') || N=0
    [ "${N:-0}" -gt 0 ] && [ "$N" = "$PREV" ] && { FOUND=1; break; }
    PREV=${N:-0}
    sleep 5
  done
fi

FOUND=0 after the loop is a timeout: report it and flip anyway.

--commit and --event filter the list server side, and -L 100 lifts the default page so a repository with many workflows is counted in full. Pointer: gh run list for the flags and the default limit.

Flip to ready

Snapshot the head's run ids first, so the confirmation can tell a run the flip started from an earlier draft one:

RUNS_BEFORE=$(gh run list --commit "$HEAD_SHA" --event pull_request -L 100 \
  --json databaseId -q 'map(.databaseId)') || RUNS_BEFORE='[]'
[ "$HEAD_MATCH" = 1 ] &&
  [ "$(gh pr view "$PR_NUMBER" --json headRefOid -q '.headRefOid')" = "$HEAD_SHA" ] &&
  bash "<skill-dir>/scripts/verify-gate.sh" check --head "$HEAD_SHA" --dir "$PR_TREE" &&
  gh pr ready "$PR_NUMBER" -R "$REPO"

The two head tests exit 1 when the PR's head on GitHub is not HEAD_SHA: the wait never saw it match, or it moved since. Report the head GitHub returned and leave the PR a draft. verify-gate.sh check exits 0 only when the record that ends 2.5.3 holds pass, or skipped, when --skip removed verify or pre_ready disabled it, for exactly HEAD_SHA; exit 3 is a recorded failure and exit 2 a missing or unreadable result. The && keeps the refusal and the flip in one command, so a refused check cannot be followed by the flip. gh pr ready takes no expected head, so a push landing between the last head read and the flip is not caught. The && does not cover the cloud-session routes below: before either, run everything before gh pr ready above as its own preceding command, and flip only on exit 0.

In a cloud session gh pr ready fails, because the flip is a GraphQL mutation. The proxy's REST route, guarded the same way:

[ "$HEAD_MATCH" = 1 ] &&
  [ "$(gh pr view "$PR_NUMBER" --json headRefOid -q '.headRefOid')" = "$HEAD_SHA" ] &&
  bash "<skill-dir>/scripts/verify-gate.sh" check --head "$HEAD_SHA" --dir "$PR_TREE" &&
  gh api --method POST "repos/$REPO/pulls/$PR_NUMBER/ccr/ready_for_review"

Or the GitHub MCP update_pull_request call with draft: false. It is a tool call, so a shell && cannot cover it: run the head tests and verify-gate.sh check as their own preceding command and make the call only on exit 0.

Confirm a ready run

A new run id for the head after the flip shows a run started, not that it carries the ready payload: a draft-payload run that registers late is also a new id, and it cancels the ready run through the per-PR concurrency group. Define ready_run_seen first, always, since the toggle below calls it (24 polls x 5 s = 120 s):

ready_run_seen() {
  for _ in $(seq 24); do
    N=$(gh run list --commit "$HEAD_SHA" --event pull_request -L 100 \
      --json databaseId -q "map(select(.databaseId as \$id | $RUNS_BEFORE | index(\$id) | not)) | length") || N=0
    [ "${N:-0}" -gt 0 ] && return 0
    sleep 5
  done
  return 1
}

When the wait above timed out (FOUND=0), the push's run had not registered when RUNS_BEFORE was taken and a new id proves nothing: do not call ready_run_seen here, go straight to the toggle, which starts a run after the draft one has registered. Otherwise call it right after the flip:

ready_run_seen

When it returns 1, toggle once and wait again; a rerun replays the draft payload, so it does not help:

RUNS_BEFORE=$(gh run list --commit "$HEAD_SHA" --event pull_request -L 100 \
  --json databaseId -q 'map(.databaseId)') || RUNS_BEFORE='[]'
gh pr ready "$PR_NUMBER" -R "$REPO" --undo && gh pr ready "$PR_NUMBER" -R "$REPO" && ready_run_seen

Exit 0 after the toggle means a new run appeared; report it as "a new run appeared", never as a confirmed ready run, and report the toggle either way. In a cloud session the toggle goes through the same routes as the flip.