#!/usr/bin/env bash
# Compact PR status for agents. Prints only what needs a decision.
#
#   pr-digest [PR]            one-shot digest
#   pr-digest --watch [PR]    poll until checks and review settle, a check newly fails, or
#                             an unseen review finding arrives; then digest
#   pr-digest --all [PR]      re-print findings already shown once
#   pr-digest --web-e2e       also wait for the Web E2E result
#   pr-digest --all-checks    also wait for every optional check
#   pr-digest --logs JOB_ID   failing CI log, stripped of timestamp noise
#   pr-digest --reply ID BODY reply to a review comment thread
#
# Exit: 0 green · 10 check failures · 11 open comments · 12 still pending
#       20 local/remote out of sync · 1 error. --watch exits 0 on any verdict.
set -uo pipefail

POLL=${PR_DIGEST_POLL:-30}
BODY_CHARS=${PR_DIGEST_BODY_CHARS:-600}
SEEN_DIR=${PR_DIGEST_SEEN_DIR:-$HOME/.cache/pr-digest}
CACHE_DIR=$SEEN_DIR/http
# How many empty polls to allow before accepting that a PR has no check runs.
EMPTY_POLLS=${PR_DIGEST_EMPTY_POLLS:-3}
SHOW_ALL=0

die() { echo "pr-digest: $*" >&2; exit 1; }

seen_path() { echo "$SEEN_DIR/${1//\//-}-$2"; }

# One line per failed check run or commit status on a head. The head and the
# job URL make a re-run or a new commit's failure distinct from an earlier one.
failure_ids() {
  local head=$1 runs=$2 statuses=$3 workflows=$4
  {
    jq -r --arg h "$head" '.[] | select(.conclusion != null and (.conclusion | test("^(success|neutral|skipped)$") | not))
      | "\($h) run \(.name) \(.html_url // "")"' <<<"$runs"
    jq -r --arg h "$head" '.[] | select(.state | test("^(failure|error)$")) | "\($h) status \(.context)"' <<<"$statuses"
    failed_workflows "$runs" "$workflows" | jq -r --arg h "$head" '.[] | "\($h) workflow \(.html_url)"'
  } | sort -u
}

# A failed API call must never look like a clean PR, so every fetch is checked.
# `die` here exits only the command substitution, so every caller carries its
# own `|| die` for the abort to reach the script.
# Keep stderr out of the payload — mixing it in corrupts JSON for jq.
api() {
  local out
  if ! out=$(gh api "$@" 2>/dev/null); then
    die "gh api request failed (not retried)"
  fi
  printf '%s' "$out"
}

# The value of one response header, from the header block `get` captured.
header() { awk -F': ' -v k="$1" 'tolower($1) == k { print $2; exit }' <<<"$2"; }

# Seconds to wait out a rate limit, or a failure when the refusal is not one.
rate_limit_wait() {
  local after remaining reset now
  after=$(header retry-after "$1")
  remaining=$(header x-ratelimit-remaining "$1")
  reset=$(header x-ratelimit-reset "$1")
  if [[ $after =~ ^[0-9]+$ ]]; then
    echo $((after + 1))
  elif [ "$remaining" = 0 ] && [[ $reset =~ ^[0-9]+$ ]]; then
    now=$(date +%s)
    echo $((reset > now ? reset - now + 1 : 1))
  elif grep -qi 'rate limit' <<<"$2"; then
    # A secondary limit can come without either header; GitHub asks for a minute.
    echo 60
  else
    return 1
  fi
}

# GET one URL, sending the ETag of the last answer. An unchanged resource
# answers 304 from the cache, which GitHub does not count against the hourly
# rate limit, so a watch costs almost nothing between changes and many agents
# can watch PRs at once on one account. Out of quota, wait for the reset rather
# than failing the watch. The cache is shared, so writes replace it atomically.
get() {
  local url=$1 file etag resp status headers wait tmp tries=0
  file="$CACHE_DIR/${url//[^A-Za-z0-9._-]/_}"
  mkdir -p "$CACHE_DIR"
  while [ "$tries" -lt 5 ]; do
    tries=$((tries + 1))
    etag=""
    [ -s "$file" ] && etag=$(head -n 1 "$file")
    resp=$(gh api -i ${etag:+-H "If-None-Match: $etag"} "$url" 2>/dev/null)
    status=$(head -n 1 <<<"$resp" | awk '{ print $2 }')
    headers=$(awk 'NR > 1 && /^\r?$/ { exit } NR > 1' <<<"$resp" | tr -d '\r')
    case $status in
      200)
        tmp=$(mktemp "$file.XXXXXX") || return 1
        { echo "$(header etag "$headers")"; awk 'body { print; next } /^\r?$/ { body = 1 }' <<<"$resp"; } >"$tmp"
        mv "$tmp" "$file"
        tail -n +2 "$file"
        return 0
        ;;
      304)
        if [ -s "$file" ]; then touch "$file"; tail -n +2 "$file"; return 0; fi
        ;;
      403|429)
        wait=$(rate_limit_wait "$headers" "$resp") || return 1
        echo "pr-digest: GitHub rate limit, waiting ${wait}s" >&2
        sleep "$wait"
        ;;
      *) return 1 ;;
    esac
  done
  return 1
}

# Every page of a list endpoint as one JSON array; $2 picks the list out of an
# endpoint that wraps it in an object.
get_list() {
  local url=$1 path=${2:-.} sep='?' page=1 body pages="" n
  [[ $url == *\?* ]] && sep='&'
  while :; do
    body=$(get "$url${sep}per_page=100&page=$page") || return 1
    pages+=$body$'\n'
    n=$(jq "($path // []) | length" <<<"$body") || return 1
    [ "$n" -lt 100 ] && break
    page=$((page + 1))
  done
  jq -cs "map($path // []) | add // []" <<<"$pages"
}

check_runs() {
  get_list "repos/$1/commits/$2/check-runs" .check_runs |
    jq '[.[] | {name, status, conclusion, html_url, app: .app.slug}]'
}

# A workflow queued behind a runner backlog has no jobs yet, so it shows up
# here before it creates any check run. Only runs the PR's own commits trigger
# count; a manual dispatch on the same commit is not part of the PR's checks.
# A newer run of the same workflow replaces an older one.
workflow_runs() {
  get_list "repos/$1/actions/runs?head_sha=$2" .workflow_runs |
    jq '[.[] | select(.event | test("^(pull_request|pull_request_target|push)$"))
      | {id, workflow_id, event, name, status, conclusion, html_url}]
      | group_by([.workflow_id, .event]) | map(max_by(.id))'
}

# Workflow runs that ended unsuccessfully without a failed job of their own,
# such as one that never started; nothing else would report them.
failed_workflows() {
  jq --argjson runs "$1" '[.[] | . as $w
    | select(.conclusion != null and (.conclusion | test("^(success|neutral|skipped)$") | not))
    | select([$runs[] | select((.html_url // "") | startswith($w.html_url + "/job/"))
              | select(.conclusion != null and (.conclusion | test("^(success|neutral|skipped)$") | not))]
             | length == 0)]' <<<"$2"
}

# Vercel only deploys the marketing site, and fork PRs always fail it with
# "Authorization required to deploy.", so it never gates a PR here.
commit_statuses() {
  get_list "repos/$1/commits/$2/status" .statuses |
    jq '[.[] | select(.context | startswith("Vercel") | not) | {context, state}]'
}

# The checks the base branch requires, as a JSON array, or empty when none are
# named or they cannot be read.
REQUIRED=""
ALL_CHECKS=0
WEB_E2E=0
WEB_E2E_CHECK="Web E2E / Web E2E"
required_checks() {
  local branch
  REQUIRED=""
  branch=$(get "repos/$1/branches/$2") || return 0
  REQUIRED=$(jq -c '.protection.required_status_checks.contexts // [] | select(length > 0)' <<<"$branch")
}

# A watched check that has not appeared yet is still pending. A check run or
# status that has appeared counts once in the all-checks mode.
pending_count() {
  jq -n --argjson req "${REQUIRED:-[]}" --argjson runs "$1" --argjson statuses "$2" \
    --argjson workflows "$3" --argjson all "$ALL_CHECKS" --argjson web "$WEB_E2E" \
    --arg web_check "$WEB_E2E_CHECK" '
    ($all == 1 or ($req | length == 0)) as $all_pending
    | ($req + (if $web == 1 then [$web_check] else [] end) | unique) as $watched
    | ([$watched[] as $c
       | ([$runs[] | select(.name == $c)]) as $r
       | ([$statuses[] | select(.context == $c)]) as $s
       | select(($r | length) + ($s | length) == 0
                or (($all_pending | not) and (($r | any(.status != "completed"))
                                              or ($s | any(.state == "pending")))))] | length)
    + (if $all_pending then
        ([$runs[], $workflows[] | select(.status != "completed")] | length)
        + ([$statuses[] | select(.state == "pending")] | length)
       else 0 end)'
}

pending_reviewer() {
  local head=$1 pull=$2 runs=$3 route name app
  route=$(jq -r '[.labels[]?.name | select(. == "review:cr" or . == "review:greptile")] | max // ""' <<<"$pull")
  case "$route" in
    review:cr) name=CodeRabbit; app=coderabbitai ;;
    review:greptile) name="Greptile Review"; app=greptile-apps ;;
    *)
      if [ "$QODO_ACTIVE" = true ] && { [ -z "$QODO_SHA" ] || [[ $head != "$QODO_SHA"* && $QODO_SHA != "$head"* ]]; }; then
        echo "Qodo review"
      fi
      return 0
      ;;
  esac

  if jq -e --arg app "$app" --arg name "$name" \
      'any(.[]; .app == $app and .name == $name and .conclusion == "success")' <<<"$runs" >/dev/null; then
    return 0
  fi
  if jq -e --arg bot "$app[bot]" --arg head "$head" \
      'any(.[]; .user.login == $bot and .commit_id == $head and .submitted_at != null)' <<<"$REVIEWS" >/dev/null; then
    return 0
  fi
  if [ "$app" = greptile-apps ] && jq -e --arg head "$head" '
      any(.[]; .user.login == "greptile-apps[bot]" and (.body | startswith("<!-- greptile_summary -->")
        and test("Last reviewed commit:[^\n]*\\(https://github\\.com/[^/]+/[^/]+/commit/" + $head + "\\)")))' \
      <<<"$CONVO" >/dev/null; then
    return 0
  fi
  echo "$name"
}

# gh pr view, with gh's hint banner dropped from stderr but its errors kept.
pr_view() {
  gh pr view "$@" 2> >(grep -vE '^(hint:|    |  - )' >&2)
}

logs() {
  local job=$1 keep out
  keep='^[0-9]+\) |^ *(Error|TimeoutError|AssertionError):|^ *(Locator|Expected|Received|Timeout|Call log):|^ *- (Expect|waiting for|locator resolved)|^ *>? *[0-9]+ \| |^ *\^|^ *at .*\.(spec|test)\.[jt]sx?:[0-9]|^ *[0-9]+ (failed|passed|flaky|skipped)|^ *(✘|✗|×) |^##\[error\]'
  out=$(gh run view --job "$job" --log-failed 2>/dev/null |
    perl -pe 's/^[^\t]*\t[^\t]*\t\S+\s//' |
    grep -v '^\[WebServer\]' |
    grep -E "$keep" |
    perl -pe 's/\e\[[0-9;]*m//g' |
    awk '!/^##\[error\]/ || !seen[$0]++' |
    tail -n "${PR_DIGEST_LOG_LINES:-80}")
  if [ -n "$out" ]; then
    echo "$out"
    return 0
  fi
  out=$(gh run view --job "$job" --log-failed 2>/dev/null |
    perl -pe 's/^[^\t]*\t[^\t]*\t\S+\s//' |
    grep -vE '^\s*$|^\[WebServer\]' | tail -n 40)
  if [ -n "$out" ]; then
    echo "$out"
    return 0
  fi
  die "no failed log for job $job"
}

# The reply endpoint needs the pull number, which the comment itself carries.
reply() {
  local repo id=$1 body=$2 pr
  repo=$(gh repo view --json nameWithOwner --jq .nameWithOwner 2>/dev/null) || die "not a GitHub repo"
  pr=$(api "repos/$repo/pulls/comments/$id" --jq '.pull_request_url | split("/") | last')
  [ -n "$pr" ] || die "could not resolve the pull request for comment $id"
  api "repos/$repo/pulls/$pr/comments/$id/replies" -f body="$body" --jq '"replied \(.id)"'
}

# Every unanswered review finding on the PR, as JSON in OPEN. Sets globals rather
# than printing so the watch loop can poll it without consuming the output.
findings() {
  local pr=$1 repo=$2 viewer=$3 head=$4
  # Review bots pad bodies with collapsed sections, HTML markers and badge
  # images; the prose around them is the whole finding. Remove each <details>
  # block from the inside out — truncating at the first one drops the prose
  # that follows it, and cutting to the last one drops the prose between.
  local clean_def='
    def clean:
      gsub("<!--[\\s\\S]*?-->"; "")
      | reduce range(0; 6) as $_ (.;
          sub("<details>(?:(?!<details>)[\\s\\S])*?</details>"; ""))
      | gsub("<img[^>]*alt=\"(?<a>[^\"]*)\"[^>]*>"; "\(.a)")
      | gsub("<[^>]+>"; "") | gsub("\\s+"; " ")
      | explode
      | map(select(. >= 32 and (. < 127 or . > 159)))
      | implode
      | sub("^ +"; "") | sub(" +$"; "") | .[0:$n];'

  # Deploy tables, preview links, rate-limit notices, screenshot galleries, and sticky bot
  # summaries are status chrome — not findings that need a reply. Actionable
  # bot conversation comments are not noise and must block green.
  local noise_def='
    def noise:
      .user.type == "Bot" and (
        .user.login == "vercel[bot]"
        or (.user.login == "coderabbitai[bot]" and (.body |
          sub("^<!-- coderabbit-ai-generated:v1 -->\\s*"; "")
          | startswith("<!-- This is an auto-generated comment: summarize by coderabbit.ai -->")
            or startswith("<!-- This is an auto-generated comment: rate limited by coderabbit.ai -->")))
        or (.user.login == "greptile-apps[bot]" and (.body |
          startswith("<h3>Greptile Summary</h3>") or startswith("<!-- greptile_summary -->")))
        or ((.user.login | startswith("qodo-")) and (.body | ltrimstr("\n") |
          startswith("<h3>PR Summary by Qodo</h3>") or startswith("<h3>Code Review by Qodo</h3>")
            or startswith("No code issues found.") or startswith("<h3>Qodo is busy working</h3>")
            or startswith("<!-- qodo:")
            or test("^\\[Code review\\]\\([^)]*\\) by qodo was updated up to the latest commit ")))
        or (.user.login == "github-actions[bot]" and (.body |
          startswith("<!-- rakazo-playwright-screenshots -->")
            or startswith("<!-- rakazo-preview -->")
            or . == "/agentic_review" or . == "@greptileai"))
      );'

  # Compare complete URL tokens, never substrings or bare comment IDs.
  local link_def='
    def links($url):
      [scan("https?://[^\\s<>\\\"()\\[\\]]+")] | map(sub("[.,;:!?]+$"; "")) | index($url) != null;'

  # Qodo keeps its findings in one sticky comment that it edits on every head,
  # so the comment itself is noise and each numbered finding is read instead.
  # Only the latest review counts (the part above "Previous reviews"); a struck
  # title or a Resolved/Outdated tag closes a finding. The commit marker names
  # the head that review covered.
  local qodo_def='
    def qodo_bot: .user.type == "Bot" and (.user.login | startswith("qodo-"));
    def qodo_review:
      qodo_bot and (.body | ltrimstr("\n") |
        startswith("<h3>Code Review by Qodo</h3>") or startswith("No code issues found."));
    def qodo_current: .body | split("<summary><strong>Previous reviews</strong>")[0];
    def qodo_restarted: qodo_review and (qodo_current | contains("<h3>New Review Started</h3>"));
    def qodo_in_progress:
      qodo_restarted or (qodo_bot and (.body | ltrimstr("\n") |
        startswith("<h3>Qodo is busy working</h3>") or startswith("<!-- qodo:")));
    def qodo_active:
      qodo_review or qodo_in_progress or (qodo_bot and (.body | ltrimstr("\n") |
        startswith("<h3>PR Summary by Qodo</h3>")));
    def decode:
      gsub("&#x27;|&#39;"; "'"'"'") | gsub("&quot;"; "\"") | gsub("&lt;"; "<")
      | gsub("&gt;"; ">") | gsub("&amp;"; "&");
    def printable: explode | map(select(. >= 32 and (. < 127 or . > 159))) | implode;
    def qodo_sha:
      [select(qodo_restarted | not) | qodo_current
       | scan("<!-- https://github\\.com/[^ ]+/commit/([0-9a-f]{7,40}) -->") | .[0]] | first;
    def qodo_findings:
      [qodo_current | split("<summary>\\s+(?=\\d+\\.\\s)"; null) | .[1:][]
       | capture("^(?<n>\\d+)\\.\\s+(?<head>[\\s\\S]*?)</summary>(?<rest>[\\s\\S]*)")
       | [.head | scan("<code>([^<]*)</code>") | .[0] | printable] as $tags
       | {n: (.n | tonumber),
          title: (.head | sub("<code>[\\s\\S]*$"; "") | gsub("<[^>]+>"; "") | decode
                  | gsub("\\s+"; " ") | printable | sub("^ "; "") | sub(" $"; "")),
          closed: ((.head | test("<s>")) or ($tags | any(test("Resolved|Outdated")))),
          new: ($tags | any(test("New"))),
          category: ($tags | map(select(test("New") | not)) | join(", ")),
          detail: ((.rest | capture("<pre>(?<p>[\\s\\S]*?)</pre>").p) // "")}];'

  # Inline review threads. One stays open until *you* have replied to it; a bot
  # follow-up confirming your fix must not mark it handled.
  local inline open
  inline=$(get_list "repos/$repo/pulls/$pr/comments") \
    || die "could not read review comments"
  open=$(jq --arg me "$viewer" --argjson n "$BODY_CHARS" "
    $clean_def
    [.[] | select(.in_reply_to_id != null and .user.login == \$me)] as \$mine
    | [.[] | select(.in_reply_to_id == null and .user.login != \$me)
           | . as \$root
           # A review bot marking its own finding addressed edits the root; that
           # edit confirms the reply rather than reopening the finding.
           | (if .user.type == \"Bot\" and (.body | test(\"Confirmed as addressed|Addressed in commit\"))
              then .created_at else .updated_at end) as \$since
           | select([\$mine[] | select(.in_reply_to_id == \$root.id
                        and .created_at > \$since)] | length == 0)
           | {key: \"\(.id):\(.updated_at)\", id, author: .user.login, path,
              line: (.line // .original_line), body: (.body | clean)}]" <<<"$inline")

  # Conversation comments have no threads. One stays open until *you* post a
  # later conversation comment that quotes its permalink; any later post of
  # yours is not enough, and a bot confirming a fix must not close it. Compare
  # against updated_at so an edit after your reply reopens the finding.
  local convo noise_n convo_open
  convo=$(get_list "repos/$repo/issues/$pr/comments") \
    || die "could not read conversation comments"
  noise_n=$(jq "
    $noise_def
    [.[] | select(noise)] | length" <<<"$convo")
  convo_open=$(jq --arg me "$viewer" --argjson n "$BODY_CHARS" "
    $clean_def
    $noise_def
    $link_def
    [.[] | select(.user.login == \$me)
         | {id, created_at, body, html_url}] as \$mine
    | [.[]
       | select(.user.login != \$me)
       | select(noise | not)
       | . as \$c
       | select(
           [\$mine[]
            | select(.created_at > \$c.updated_at
                     and (.body | links(\$c.html_url)))]
           | length == 0)
       | {key: \"\(.id):\(.updated_at)\", id, author: .user.login,
          path: \"(conversation)\", line: 0, body: (.body | clean)}]" <<<"$convo")

  # A Qodo finding stays open until Qodo marks it resolved, or until *you* post
  # a conversation comment that quotes the sticky permalink and the finding's
  # title. Its key is its title, not the comment's updated_at, so re-reviews
  # of a new head do not reopen findings already answered, while a finding
  # added by an edit is unseen and wakes the watch.
  local qodo qodo_open
  qodo=$(jq --arg me "$viewer" "
    $qodo_def
    $link_def
    [.[] | select(.user.login == \$me) | .body | ascii_downcase] as \$mine
    | [.[] | select(qodo_review) | . as \$c | qodo_findings as \$all
       | \$all[] | select(.closed | not)
       | (.title | ascii_downcase) as \$t
       # A longer title that contains this one must not answer it too.
       | [\$all[].title | ascii_downcase | select(. != \$t and contains(\$t))] as \$longer
       | . + {id: \$c.id, author: \$c.user.login,
              answered: ([\$mine[] | reduce \$longer[] as \$l (.; split(\$l) | join(\" \"))
                          | select(\$t != \"\" and links(\$c.html_url | ascii_downcase) and contains(\$t))]
                         | length > 0)}]" <<<"$convo")
  qodo_open=$(jq --argjson n "$BODY_CHARS" "
    $clean_def
    $qodo_def
    [.[] | select(.answered | not)
     | {key: \"q\(.id):\(.title)\", id, author, path: \"(qodo \(.n))\", line: 0,
        body: (\"\(.title) [\(.category)\(if .new then \", new\" else \"\" end)] \"
               + (.detail | gsub(\"\\n>\"; \"\\n\") | clean | decode))}]" <<<"$qodo")

  # A human can request changes in a review summary with no line comment and no
  # conversation comment attached, so that surface has to be read too.
  local reviews review_open
  reviews=$(get_list "repos/$repo/pulls/$pr/reviews") \
    || die "could not read reviews"
  review_open=$(jq --arg me "$viewer" --argjson n "$BODY_CHARS" "
    $clean_def
    group_by(.user.login)
    | map(sort_by(.submitted_at, .id)
          | map(select(.state == \"APPROVED\" or .state == \"CHANGES_REQUESTED\" or .state == \"DISMISSED\"))
          | last)
    | [.[] | select(. != null and .user.login != \$me)
         | select(.state == \"CHANGES_REQUESTED\" and (.body // \"\") != \"\")
         | {key: \"r\(.id):\(.submitted_at)\", id, author: .user.login,
            path: \"(review \(.state))\", line: 0, body: (.body | clean)}]" <<<"$reviews")

  read -r QODO_ACTIVE QODO_SHA < <(jq -r --arg head "$head" "$qodo_def
    ([.[] | select(qodo_review) | {sha: qodo_sha, at: .updated_at} | select(.sha != null)]
      | max_by([(.sha as \$sha | (\$sha | startswith(\$head)) or (\$head | startswith(\$sha))), .at]))
    as \$completed
    | [any(.[]; qodo_active), (if any(.[]; qodo_in_progress and .updated_at > \$completed.at)
         then \"\" else \$completed.sha // \"\" end)]
    | @tsv" <<<"$convo") || die "could not read Qodo status"
  OPEN=$(jq -s 'add' <<<"$open$convo_open$qodo_open$review_open")
  INLINE=$inline CONVO=$convo REVIEWS=$reviews NOISE_N=$noise_n QODO=$qodo
}

digest() {
  local pr=$1 repo=$2 viewer=$3 pull=$4

  local meta head state mergeable branch
  meta=$(pr_view "$pr" --repo "$repo" \
    --json headRefOid,state,mergeable,headRefName,reviewDecision) || die "no PR $pr"
  head=$(jq -r .headRefOid <<<"$meta")
  state=$(jq -r .state <<<"$meta")
  mergeable=$(jq -r .mergeable <<<"$meta")
  branch=$(jq -r .headRefName <<<"$meta")
  local decision; decision=$(jq -r '.reviewDecision // ""' <<<"$meta")

  echo "PR $pr · $branch · $state · $mergeable${decision:+ · $decision}"
  [ "$state" = "OPEN" ] || { echo "VERDICT $state"; return 0; }

  # Sync only matters when this checkout is on the PR's branch; inspecting
  # someone else's PR from elsewhere is not a mismatch worth reporting. An
  # upstream that will not resolve — a shallow clone, no tracking ref — is
  # unknown rather than wrong, and must not mask the rest of the verdict.
  local sync=0 local_sha upstream_sha
  if [ "$(git branch --show-current 2>/dev/null)" = "$branch" ]; then
    local_sha=$(git rev-parse HEAD 2>/dev/null || echo "")
    upstream_sha=$(git rev-parse '@{upstream}' 2>/dev/null || echo "")
    if { [ -n "$local_sha" ] && [ "$local_sha" != "$head" ]; } ||
       { [ -n "$upstream_sha" ] && [ "$upstream_sha" != "$head" ]; }; then
      echo "OUT OF SYNC local=${local_sha:0:8} upstream=${upstream_sha:0:8} pr=${head:0:8}"
      sync=20
    fi
  fi

  local runs statuses workflows wf_failed pending failed
  runs=$(check_runs "$repo" "$head") || die "could not read check runs"
  statuses=$(commit_statuses "$repo" "$head") || die "could not read commit statuses"
  workflows=$(workflow_runs "$repo" "$head") || die "could not read workflow runs"
  wf_failed=$(failed_workflows "$runs" "$workflows")

  # Legacy commit statuses gate a PR exactly like check runs do, so they have to
  # reach the verdict rather than only being printed.
  pending=$(pending_count "$runs" "$statuses" "$workflows")
  failed=$(( $(jq '[.[] | select(.conclusion != null and (.conclusion | test("^(success|neutral|skipped)$") | not))] | length' <<<"$runs") +
             $(jq '[.[] | select(.state | test("^(failure|error)$"))] | length' <<<"$statuses") +
             $(jq length <<<"$wf_failed") ))

  jq -r --argjson wf "$workflows" '"checks " + (if length == 0 then "none"
    else ([.[].conclusion // "pending"] | group_by(.) | map("\(length) \(.[0])") | join(" · ")) end)
    + ([$wf[] | select(.status != "completed") | .status]
       | group_by(.) | map(" · \(length) workflow \(.[0])") | join(""))' <<<"$runs"
  jq -r '.[] | select(.state != "success") | "STATUS \(.context) \(.state)"' <<<"$statuses"
  jq -r '.[] | "FAIL workflow \(.name) [\(.conclusion)]\n     \(.html_url)"' <<<"$wf_failed"

  # Report the failed step and skipped successors without inferring whether
  # tests ran: a test assertion failure can also skip later report steps.
  if [ "$failed" -gt 0 ]; then
    while IFS=$'\t' read -r name conclusion url; do
      local job step_info=""
      job=${url##*/job/}
      if [[ $job =~ ^[0-9]+$ ]]; then
        step_info=$(gh api "repos/$repo/actions/jobs/$job" --jq '
          (.steps // []) as $s
          | ([$s[] | select(.conclusion == "failure" or .conclusion == "cancelled")] | first) as $bad
          | if $bad == null then ""
            else " · step \"\($bad.name)\" \($bad.conclusion)"
                 + (if ([$s[] | select(.number > $bad.number and .conclusion == "skipped")] | length) > 0
                    then " (later steps skipped)" else "" end)
            end' 2>/dev/null)
      fi
      echo "FAIL $name [$conclusion]$step_info"
      echo "     job=$job $url"
    done < <(jq -r '.[] | select(.conclusion != null and (.conclusion | test("^(success|neutral|skipped)$") | not)) | [.name,.conclusion,.html_url] | @tsv' <<<"$runs")
  fi

  findings "$pr" "$repo" "$viewer" "$head"
  local open=$OPEN inline=$INLINE convo=$CONVO reviews=$REVIEWS noise_n=$NOISE_N
  local open_n seen_file
  open_n=$(jq length <<<"$open")
  echo "comments $(jq length <<<"$inline") inline · $(jq length <<<"$convo") conversation ($noise_n noise) · $(jq length <<<"$reviews") reviews · $open_n awaiting your reply"
  [ "$decision" = "CHANGES_REQUESTED" ] && echo "REVIEW changes requested"
  if [ -n "$QODO_SHA" ]; then
    local at="head"
    [[ $head == "$QODO_SHA"* || $QODO_SHA == "$head"* ]] || at="${QODO_SHA:0:8}, not the head yet"
    jq -r --arg at "$at" '"qodo reviewed \($at) · \([.[] | select(.answered | not)] | length) open · \([.[] | select(.answered)] | length) answered"
      + ([.[] | select(.answered) | "\n  answered (qodo \(.n)) \(.title)"] | join(""))' <<<"$QODO"
  fi

  if [ "$open_n" -gt 0 ]; then
    # Show a finding in full once. On later cycles it stays listed — nothing is
    # hidden — but as a single line, so re-observing an unfixed PR stays cheap.
    seen_file=$(seen_path "$repo" "$pr")
    mkdir -p "$SEEN_DIR"; touch "$seen_file"
    if [ "$SHOW_ALL" = 1 ]; then
      jq -r '.[] | "\n[\(.id)] \(.author) \(.path):\(.line)\n  \(.body)"' <<<"$open"
    else
      jq -r --rawfile seen "$seen_file" '
        ($seen | split("\n")) as $s
        | .[] | .key as $k
        | if ($s | index($k)) then
            "[\(.id)] \(.author) \(.path):\(.line) — still open (shown earlier)"
          else "\n[\(.id)] \(.author) \(.path):\(.line)\n  \(.body)" end' <<<"$open"
    fi
    jq -r '.[].key' <<<"$open" >> "$seen_file"
    sort -u -o "$seen_file" "$seen_file"
  fi

  # A verdict describes one commit. If the head moved while we were reading,
  # everything above may already be stale. A failed re-read is an error, not
  # an out-of-sync signal — callers must not push to "reconcile" a blind miss.
  local head_now
  head_now=$(pr_view "$pr" --repo "$repo" --json headRefOid --jq .headRefOid) \
    || die "could not re-read PR $pr head"
  if [ "$head_now" != "$head" ]; then
    echo "VERDICT out-of-sync (head moved during this observation)"
    return 20
  fi

  if [ "$sync" -ne 0 ]; then echo "VERDICT out-of-sync"; return 20; fi
  if [ "$failed" -gt 0 ]; then echo "VERDICT failures"; return 10; fi
  if [ "$open_n" -gt 0 ] || [ "$decision" = "CHANGES_REQUESTED" ]; then
    echo "VERDICT open-comments"; return 11
  fi
  if [ "$pending" -gt 0 ]; then echo "VERDICT pending ($pending)"; return 12; fi
  local reviewer
  reviewer=$(pending_reviewer "$head" "$pull" "$runs")
  if [ -n "$reviewer" ]; then echo "VERDICT pending ($reviewer)"; return 12; fi
  echo "VERDICT green"
  return 0
}

main() {
  local watch=0 pr=""
  while [ $# -gt 0 ]; do
    case $1 in
      --watch) watch=1 ;;
      --all) SHOW_ALL=1 ;;
      --web-e2e) WEB_E2E=1 ;;
      --all-checks) ALL_CHECKS=1 ;;
      --logs)
        shift
        command -v perl >/dev/null || die "perl not found"
        logs "${1:?job id}"
        exit $?
        ;;
      --reply) shift; reply "${1:?comment id}" "${2:?reply body}"; exit $? ;;
      -h|--help) sed -n '2,12p' "$0"; exit 0 ;;
      *) pr=$1 ;;
    esac
    shift
  done

  command -v gh >/dev/null || die "gh not found"
  command -v jq >/dev/null || die "jq not found"
  # Check-run and status URLs name a head SHA, so their cached answers go stale
  # with each push; drop any not used for a day.
  [ -d "$CACHE_DIR" ] && find "$CACHE_DIR" -type f -mtime +0 -delete 2>/dev/null

  local repo viewer
  repo=$(gh repo view --json nameWithOwner --jq .nameWithOwner 2>/dev/null) || die "not a GitHub repo"
  # Prefer GraphQL: integration tokens often cannot GET /user, and a failed
  # REST call still writes its error body to stdout — composing it with
  # `$(a || b)` would concatenate that body onto the real login.
  viewer=$(gh api graphql -f query='query { viewer { login } }' --jq .data.viewer.login 2>/dev/null) \
    || viewer=$(gh api user --jq .login 2>/dev/null) \
    || die "could not resolve authenticated user"
  case $viewer in ''|null|\{*) die "could not resolve authenticated user" ;; esac
  [ -n "$pr" ] || pr=$(gh pr view --json number --jq .number 2>/dev/null) || die "no PR for this branch"
  local pull
  pull=$(get "repos/$repo/pulls/$pr") || die "could not read PR $pr"
  required_checks "$repo" "$(jq -r .base.ref <<<"$pull")"

  if [ "$watch" -eq 1 ]; then
    local head runs statuses workflows empty=0 baseline="" first=1 seen
    seen=$(seen_path "$repo" "$pr")
    while :; do
      pull=$(get "repos/$repo/pulls/$pr") || die "could not read PR $pr"
      [ "$(jq -r '.state // "open"' <<<"$pull")" = open ] || break
      head=$(jq -r .head.sha <<<"$pull")
      # Re-read each poll (free while unchanged) in case the PR was retargeted.
      required_checks "$repo" "$(jq -r .base.ref <<<"$pull")"
      runs=$(check_runs "$repo" "$head") || die "could not read check runs"
      statuses=$(commit_statuses "$repo" "$head") || die "could not read commit statuses"
      workflows=$(workflow_runs "$repo" "$head") || die "could not read workflow runs"
      # Wake as soon as there is something to act on, rather than when the slowest
      # check settles: a check that newly failed, or a finding not yet shown.
      # Failures already present at the start were seen and do not wake it again.
      if [ "$first" = 1 ]; then
        baseline=$(failure_ids "$head" "$runs" "$statuses" "$workflows"); first=0
      elif [ -n "$(comm -13 <(echo "$baseline") <(failure_ids "$head" "$runs" "$statuses" "$workflows"))" ]; then
        break
      fi
      findings "$pr" "$repo" "$viewer" "$head"
      if [ -n "$(comm -13 <(sort -u "$seen" 2>/dev/null) <(jq -r '.[].key' <<<"$OPEN" | sort -u))" ]; then
        break
      fi
      if [ "$(pending_count "$runs" "$statuses" "$workflows")" = "0" ] \
        && [ -z "$(pending_reviewer "$head" "$pull" "$runs")" ]; then
        # Nothing outstanding. Wait a few polls before believing a PR that has
        # reported nothing at all, in case checks are still registering.
        if [ -n "$REQUIRED" ] || [ "$(jq 'length' <<<"$runs")" != "0" ] ||
           [ "$(jq 'length' <<<"$statuses")" != "0" ] ||
           [ "$empty" -ge "$EMPTY_POLLS" ]; then
          break
        fi
        empty=$((empty + 1))
      fi
      sleep "$POLL"
    done
    # The verdict line carries the result. A watch that ends on anything but an
    # error exits 0, so a background runner does not report it as failed.
    digest "$pr" "$repo" "$viewer" "$pull"
    [ $? -eq 1 ] && exit 1
    exit 0
  fi

  digest "$pr" "$repo" "$viewer" "$pull"
}

main "$@"
