#!/usr/bin/env bash
# Copyright 2024-2026 The Spice.ai OSS Authors
#
# scripts/signoff — Local CI attestation ("developer sign-off").
#
# Run the fast quality checks on your own machine, then attest to the exact
# commit you pushed. On the pull request a single `Attestation` check validates
# your sign-off and lets the PR into the merge queue, where the *full* suite of
# tests and checks runs as the real gate.
#
# Pure reverts skip this entirely: a PR that only reverts commits already on the
# base branch passes the Attestation check automatically (validated in pr.yml),
# since the merge queue still re-runs the full suite on the merged result. See
# docs/dev/ci_signoff.md ("Reverts are fast-tracked").
#
# This is Spice's take on 37signals' approach of moving CI back to developer
# machines (https://world.hey.com/dhh/we-re-moving-continuous-integration-back-to-developer-machines-3ac6c611),
# modeled on their open-source tool basecamp/gh-signoff. The twist: local
# sign-off only gates *entry* to the merge queue — the queue still runs the
# whole suite on the merged result, so a bad attestation can never reach trunk.
#
# Usage:
#   scripts/signoff                 Run checks, then sign off on HEAD  (or: make signoff)
#   scripts/signoff -f              Sign off even with a dirty/unpushed tree
#   scripts/signoff --no-verify     Sign off without running the checks (honor system)
#   scripts/signoff --note TEXT     Add TEXT to the status description (e.g. where
#                                   the checks ran, for a --no-verify sign-off)
#   scripts/signoff verify          Run the checks on HEAD but post no status
#                                   (for trees that are not a pushed PR head, such
#                                   as the combined branch of scripts/signoff-batch)
#   scripts/signoff status          Show the sign-off status of HEAD
#   scripts/signoff mine            Show attestation status for all your open PRs
#   scripts/signoff clear-pending   Restate a left-behind pending status as incomplete
#   scripts/signoff preflight-disk  Check the work volume's free space (CI: run
#                                   before the toolchain setup steps)
#   scripts/signoff preflight-lockfile
#                                   Check Cargo.lock against the manifests (CI:
#                                   run after the toolchain setup, before any build)
#   scripts/signoff check           Show whether trunk requires sign-off
#   scripts/signoff install         Configure the trunk ruleset (maintainers)
#   scripts/signoff install --yes   Apply the ruleset change (default is a dry-run)
#
# Environment:
#   SIGNOFF_BRANCH    Branch/ruleset to target for install/check (default: trunk)
#   SIGNOFF_REMOTE    Git remote to use in a JJ workspace (default: origin)
#   SIGNOFF_ACTOR     Attribution login (remote workflow sets this to the
#                     human who dispatched the run; defaults to gh/git user)
#   SIGNOFF_REMOTE_RUN  Set by .github/workflows/signoff.yml — pending/failure
#                     statuses, "via remote" description, GitHub step summary
#   SIGNOFF_DEBUG     Set to any value for verbose debug logging
#   SIGNOFF_SKIP_TARGETED_LINT  Set to any value to skip the branch-scoped
#                     pre-lint. Note this skips the targeted unit tests too:
#                     package discovery is gated on this variable, so the tests
#                     phase has no packages to run against.
#   SIGNOFF_SKIP_TARGETED_TESTS Set to any value to skip the branch-scoped unit
#                     tests that run after the pre-lint. This one does skip only
#                     the tests; the pre-lint still runs.
#   SIGNOFF_MIN_FREE_GIB  Free space (GiB) the work volume must have before a
#                     remote run starts its Rust checks (default: 25). Checked
#                     twice: by the `preflight-disk` step before the toolchain
#                     setup, and again inside the run. Below it a remote run
#                     stops immediately as an infrastructure failure; a local
#                     run only warns.
#   SIGNOFF_STEP_BUDGET_MINUTES  The `Sign off` step's own `timeout-minutes`,
#                     threaded in by signoff.yml so the script can see its
#                     deadline. A run whose checks end within
#                     SIGNOFF_STEP_BUDGET_GRACE_SECONDS (default: 120) of it is
#                     classified as signalled and publishes no verdict (#13843).
#
# Targeted pre-lint always diffs against trunk (not configurable).
# When the branch has no Rust-affecting changes vs trunk (.rs, Cargo.toml,
# Cargo.lock, rust-toolchain*, .cargo/*, clippy/rustfmt/nextest/layers config,
# the lint guards, the root Makefile), Rust lint/build/tests are skipped
# (both local and remote); the sign-off status is still posted.
#
# Remote alternative to local `make signoff` (both dispatch GitHub Actions):
#   make signoff-remote
#   gh workflow run signoff.yml -f branch=<branch>

set -euo pipefail

readonly VERSION="1.5.0"
# Fixed, not configurable: it must match the hardcoded context the Attestation
# workflow (pr.yml) looks for, so an env override would silently break the gate.
readonly STATUS_CONTEXT="signoff"
readonly TARGET_BRANCH="${SIGNOFF_BRANCH:-trunk}"
readonly TARGET_REMOTE="${SIGNOFF_REMOTE:-origin}"
# Seconds to wait between attempts at a commit-status POST; the number of
# attempts is one more than the number of entries. A verdict can cost hours of
# runner time and exists nowhere but that POST, so one transient response must
# not discard it. Empty means post once. Overridable so the unit tests do not
# pay for the waits.
readonly STATUS_POST_BACKOFF="${SIGNOFF_STATUS_POST_BACKOFF-5 15 30 60}"
DEBUG="${SIGNOFF_DEBUG:-}"
VCS=""
JJ_REMOTE_URL=""
# Packages excluded from workspace lint (must match Makefile lint-rust excludes).
readonly LINT_EXCLUDED_PACKAGES="libnfs lopdf ttf-parser pdf-extract"

# Build under the same cargo profile the merge queue uses: `pr.yml` sets
# RUST_PROFILE to `lint`, while the Makefile's fallback is `dev`. Two costs come
# with that fallback. `dev` carries full debug info, which the clippy pass
# generates and then throws away because it only ever emits metadata. And the two
# profiles write to different target directories, so a runner that has just
# built a pull request shares nothing with the sign-off that follows it.
# Matching the merge queue also makes the attestation describe the build that
# actually gates the merge. An explicit RUST_PROFILE still wins.
export RUST_PROFILE="${RUST_PROFILE:-lint}"

# True when running under the Remote Sign-off workflow. Drives pending/failure
# statuses, "via remote" descriptions, and the GitHub Actions step summary.
# GITHUB_ACTIONS alone is not enough — other workflows must not inherit this.
is_remote_run() { [[ -n "${SIGNOFF_REMOTE_RUN:-}" ]]; }

# True when running inside any GitHub Actions job, remote sign-off or not.
#
# Kept separate from is_remote_run because they answer different questions.
# is_remote_run means "this is the Remote Sign-off workflow", which is what
# licenses posting statuses and calling a stop fatal. This one means only "the
# `::error::` and step-summary channels exist here", and the lockfile preflight
# needs that weaker fact: `pr.yml` invokes it as `scripts/signoff
# preflight-lockfile` from a job that is not a sign-off run at all, and its
# failure still has to reach the run summary rather than only the log body.
in_actions() { [[ -n "${GITHUB_ACTIONS:-}" ]]; }

# The single source of truth for the checks required to merge. `install` writes
# exactly this list into the trunk ruleset's required status checks. Every name
# here must be produced under the same name on both the PR head (to allow
# queue entry) and `merge_group` (to gate the merged result).
readonly REQUIRED_CHECKS=(
  "Attestation"              # sign-off gate (pr.yml) — the PR's only quality check
  "enforce-pull-with-spice"  # PR hygiene (enforce-pulls-with-spice.yml)
  "Rust Lint"                # pr.yml
  "Build and Test"           # pr.yml
  "Build (release profile)"  # pr.yml
  "Integration Tests (part 1)"
  "Integration Tests (part 2)"
  "Integration Tests (part 3)"
  "ADBC Integration Tests"   # integration_adbc.yml
  # `Features Check` (features.yml) is deliberately absent. That workflow is
  # disabled, so no run reports the context, and a required check nothing
  # reports blocks every pull request rather than passing it — which is what
  # happened the one time it was required (added to the ruleset 2026-07-10
  # 05:00, reverted 05:06). Re-enable the workflow before listing it again.
  "Check Rust Licenses"      # license_check.yml
  "E2E Test CI"              # e2e_test_ci.yml (gate job)
  # verus_verify.yml. The only check that reads the Verus proofs (hash-index
  # and the results-cache namespace prefix today): a normal `cargo build`
  # erases the specifications, so nothing else here would notice a
  # postcondition that no longer holds. One job, one context — never a
  # per-crate required check. The name is crate-agnostic so a later crate
  # does not need another ruleset rename.
  "Verify Verus proofs"
)
# GitHub Actions app id — pins each required check to Actions so a hand-POSTed
# commit status can't satisfy a required check (only `signoff` is a raw status).
readonly ACTIONS_INTEGRATION_ID=15368

# --- output helpers ----------------------------------------------------------

readonly OK="✓"
readonly NO="✗"

# Colors for `mine`'s human-facing report only — every other command's output
# stays plain text (docs/scripts may grep it). Respects NO_COLOR and piping.
if [[ -t 1 && -z "${NO_COLOR:-}" && "${TERM:-dumb}" != "dumb" ]]; then
  readonly C_RED=$'\033[31m' C_GREEN=$'\033[32m' C_YELLOW=$'\033[33m' C_CYAN=$'\033[36m' \
    C_DIM=$'\033[2m' C_BOLD=$'\033[1m' C_RESET=$'\033[0m'
else
  readonly C_RED='' C_GREEN='' C_YELLOW='' C_CYAN='' C_DIM='' C_BOLD='' C_RESET=''
fi

debug() { [[ -n "$DEBUG" ]] && echo "debug: $*" >&2 || true; }
info()  { echo "$*" >&2; }
fail()  { echo "${NO} $*" >&2; exit 1; }

# Prefix each non-empty line of stdin with "$1" (for indented list output).
bullet() { local prefix="$1" line; while IFS= read -r line; do [[ -n "$line" ]] && echo "${prefix}${line}"; done; }

# True when "$1" holds at least one character that is not a tab, newline, CR, or
# space — i.e. the string carries content rather than only separators.
#
# This replaces `[[ -n "${var//[$'\t\n\r ']/}" ]]`. That expansion is quadratic
# or worse in bash 3.2 (still /bin/bash on macOS, which `#!/usr/bin/env bash`
# resolves to), so applying it to a branch's changed-file list — ~107 KB for a
# 900-file diff — takes hours: measured 1.8s at 3 KB, 14s at 6 KB, 91s at 12 KB,
# extrapolating to ~11h at 107 KB. A glob match short-circuits on the first
# content character instead, and stays fast (~20ms at 107 KB) even in the
# all-whitespace worst case, where it has to scan the whole string.
readonly SIGNOFF_SEPARATORS=$'\t\n\r '
has_content() { [[ "$1" == *[!$SIGNOFF_SEPARATORS]* ]]; }

# --- preconditions -----------------------------------------------------------

# Detect Git first so colocated JJ repositories retain the existing Git behavior.
# Fall back to JJ for non-colocated workspaces, which intentionally have no .git
# directory for Git or gh to discover.
detect_vcs() {
  if command -v git >/dev/null 2>&1 && git rev-parse --show-toplevel >/dev/null 2>&1; then
    VCS="git"
    return
  fi

  if command -v jj >/dev/null 2>&1 && jj root >/dev/null 2>&1; then
    VCS="jj"
    [[ "$TARGET_REMOTE" =~ ^[[:alnum:]_.:/-]+$ ]] \
      || fail "invalid JJ remote name: '${TARGET_REMOTE}'"

    local name url remotes
    remotes=$(jj --color=never git remote list) \
      || fail "could not list JJ remotes"
    while read -r name url; do
      if [[ "$name" == "$TARGET_REMOTE" ]]; then
        JJ_REMOTE_URL="$url"
        break
      fi
    done <<<"$remotes"
    [[ -n "$JJ_REMOTE_URL" ]] \
      || fail "JJ remote '${TARGET_REMOTE}' not found — add it with 'jj git remote add', or set SIGNOFF_REMOTE"
    [[ "$JJ_REMOTE_URL" != -* ]] \
      || fail "invalid URL for JJ remote '${TARGET_REMOTE}'"
    return
  fi

  fail "not inside a Git checkout or JJ workspace"
}

# gh covers every path; Git is used in a Git checkout and JJ in a non-colocated
# workspace. The default signoff flow parses JSON via `gh --jq`, not jq itself.
require_tools() {
  command -v gh >/dev/null 2>&1 || fail "GitHub CLI (gh) not found — install from https://cli.github.com"
  detect_vcs
  gh auth status >/dev/null 2>&1 || fail "not logged in to GitHub — run 'gh auth login'"
}

# Only the subcommands that parse JSON with the jq binary (status/check/install).
require_jq() {
  command -v jq >/dev/null 2>&1 || fail "jq not found — install from https://jqlang.github.io/jq"
}

# owner/repo of the current checkout, from the gh context. gh cannot infer a
# repository from a non-colocated JJ workspace, so give it that workspace's
# configured remote URL explicitly.
repo_slug() {
  if [[ "$VCS" == "jj" ]]; then
    gh repo view "$JJ_REMOTE_URL" --json nameWithOwner --jq .nameWithOwner 2>/dev/null \
      || fail "could not determine the GitHub repository from JJ remote '${TARGET_REMOTE}'"
  else
    gh repo view --json nameWithOwner --jq .nameWithOwner 2>/dev/null \
      || fail "could not determine the GitHub repository — run this inside a clone of the repo"
  fi
}

jj_revision_is_remote() {
  local revision="$1" sha
  sha=$(jj --color=never --no-pager log \
    -r "${revision} & remote_bookmarks(remote=exact:\"${TARGET_REMOTE}\")" \
    --no-graph -T 'commit_id') \
    || fail "could not inspect JJ bookmarks on '${TARGET_REMOTE}'"
  [[ -n "$sha" ]]
}

# A normal `jj commit` leaves an empty working-copy commit on top of the commit
# that was bookmarked and pushed. Treat that parent as HEAD. If @ itself has a
# bookmark, contains changes, or is already a remote bookmark, it is the commit
# the developer is trying to attest instead.
current_revision() {
  local force="${1:-false}"
  if [[ "$VCS" == "git" ]]; then
    echo "HEAD"
    return
  fi

  local at_bookmark at_empty
  at_bookmark=$(jj --color=never --no-pager log -r '@ & bookmarks()' --no-graph -T 'commit_id') \
    || fail "could not inspect JJ bookmarks"
  at_empty=$(jj --color=never --no-pager log -r '@ & empty()' --no-graph -T 'commit_id') \
    || fail "could not inspect the JJ working-copy commit"
  if jj_revision_is_remote "@" || [[ -n "$at_bookmark" ]] || [[ -z "$at_empty" ]]; then
    echo "@"
    return
  fi

  local parent_count
  parent_count=$(jj --color=never --no-pager log -r '@' --no-graph -T 'parents.len()') \
    || fail "could not inspect the JJ working-copy parent"
  if [[ "$parent_count" == "1" ]]; then
    echo "@-"
  elif $force; then
    echo "@"
  else
    fail "empty JJ working-copy commit has ${parent_count} parents — select the commit to sign off, or pass -f"
  fi
}

revision_sha() {
  local revision="$1"
  if [[ "$VCS" == "jj" ]]; then
    jj --color=never --no-pager log -r "$revision" --no-graph -T 'commit_id'
  else
    git rev-parse "$revision"
  fi
}

local_user_name() {
  if [[ "$VCS" == "jj" ]]; then
    jj config get user.name 2>/dev/null
  else
    git config user.name 2>/dev/null
  fi
}

# Refuse to sign off on a tree that isn't exactly what's pushed: the attestation
# is bound to a single commit SHA, so it must match the commit under review.
ensure_clean_and_pushed() {
  local revision="$1"
  if [[ "$VCS" == "jj" ]]; then
    jj_revision_is_remote "$revision" \
      || fail "JJ revision ${revision} is not a bookmark tip on '${TARGET_REMOTE}' — bookmark and push it with 'jj git push', or pass -f"
    return
  fi

  if [[ -n "$(git status --porcelain)" ]]; then
    fail "working tree has uncommitted changes — commit or stash them, or pass -f"
  fi
  if ! git rev-parse --abbrev-ref '@{push}' >/dev/null 2>&1; then
    fail "current branch has no upstream — push it first (git push -u origin HEAD), or pass -f"
  fi
  if [[ -n "$(git log '@{push}..' --oneline)" ]]; then
    fail "branch has commits that aren't pushed — push them first, or pass -f"
  fi
  # ...and not behind either, so HEAD is exactly the pushed tip under review.
  if [[ -n "$(git log 'HEAD..@{push}' --oneline)" ]]; then
    fail "branch is behind its remote — pull the latest, then sign off (or pass -f)"
  fi
}

# --- branch → package mapping (targeted pre-lint) ----------------------------

# Targeted pre-lint always diffs against trunk (fixed, not configurable).
readonly LINT_BASE_BRANCH="trunk"

# Resolve trunk to a local git/jj ref usable with merge-base / jj diff.
# Fails if the ref isn't present locally (caller may fall back to API).
resolve_local_trunk_ref() {
  if [[ "$VCS" == "jj" ]]; then
    if jj --color=never --no-pager log \
      -r "remote_bookmarks(exact:\"${LINT_BASE_BRANCH}\", remote=exact:\"${TARGET_REMOTE}\")" \
      --no-graph -T 'commit_id' -n 1 >/dev/null 2>&1; then
      echo "${LINT_BASE_BRANCH}@${TARGET_REMOTE}"
      return 0
    fi
    if jj --color=never --no-pager log -r "bookmarks(exact:\"${LINT_BASE_BRANCH}\")" \
      --no-graph -T 'commit_id' -n 1 >/dev/null 2>&1; then
      echo "$LINT_BASE_BRANCH"
      return 0
    fi
    return 1
  fi

  if git rev-parse --verify "refs/remotes/${TARGET_REMOTE}/${LINT_BASE_BRANCH}" >/dev/null 2>&1; then
    echo "${TARGET_REMOTE}/${LINT_BASE_BRANCH}"
    return 0
  fi
  if git rev-parse --verify "refs/heads/${LINT_BASE_BRANCH}" >/dev/null 2>&1; then
    echo "$LINT_BASE_BRANCH"
    return 0
  fi
  return 1
}

# GitHub compare API — works on shallow clones where merge-base is unavailable.
# Prints one filename per line. Returns non-zero if the API call fails or the
# compare is truncated beyond usefulness (caller skips targeted lint).
github_compare_files() {
  local head_sha="$1"
  local repo payload

  repo=$(repo_slug) || return 1

  # three-dot compare: merge-base of trunk...head → head (same as a PR diff).
  # GitHub caps the files list at 300; when truncated, skip targeted pre-lint
  # rather than linting an incomplete package set.
  # Emit the file count, then both paths of each rename and other filenames.
  # Keep stderr so auth/rate-limit/network errors from `gh` are visible when
  # the compare fallback fails (caller still degrades to full workspace lint).
  payload=$(gh api "repos/${repo}/compare/${LINT_BASE_BRANCH}...${head_sha}" \
    --jq 'if (.files | type) != "array" then error("compare response has no file list") else (.files | length), (.files[] | .filename, .previous_filename // empty) end') \
    || return 1

  local count rest
  count="${payload%%$'\n'*}"
  # The compare API caps its file list at 300 without a truncation flag.
  if [[ ! "$count" =~ ^[0-9]+$ ]] || (( count >= 300 )); then
    debug "GitHub compare is truncated (300+ files) — skipping targeted pre-lint"
    return 1
  fi
  rest="${payload#*$'\n'}"
  # When there are no files, payload is a single line ("0") and rest==payload.
  if [[ "$rest" == "$payload" ]]; then
    return 0
  fi
  printf '%s\n' "$rest"
}

# List paths changed on this branch relative to the merge-base with trunk.
# With a dirty tree (signoff -f), includes uncommitted working-tree changes when
# using local git. Falls back to the GitHub compare API on shallow clones
# (remote sign-off).
changed_files_vs_trunk() {
  local revision="$1"
  local base_ref base_sha head_sha files

  if [[ "$VCS" == "jj" ]]; then
    if base_ref=$(resolve_local_trunk_ref); then
      # `jj diff --from A --to B` is the branch delta; working-copy edits on an
      # empty @ parent are already in `revision` when current_revision selected @.
      # Name-only emits rename destinations. The reverse diff supplies their
      # source paths, which may be the side that affects Rust.
      {
        jj --color=never --no-pager diff --from "$base_ref" --to "$revision" --name-only || return 1
        jj --color=never --no-pager diff --from "$revision" --to "$base_ref" --name-only || return 1
      } | sort -u || return 1
      return 0
    fi
    debug "JJ trunk not local — trying GitHub compare API"
    head_sha=$(revision_sha "$revision") || return 1
    github_compare_files "$head_sha"
    return
  fi

  if base_ref=$(resolve_local_trunk_ref) \
    && base_sha=$(git merge-base HEAD "$base_ref" 2>/dev/null); then
    # No second revision → working tree vs trunk (covers committed + dirty -f).
    # Untracked files are invisible to `git diff` but still need package mapping
    # under `scripts/signoff -f` (dirty tree).
    {
      git diff --no-renames --name-only --diff-filter=ACDMRT "$base_sha" || return 1
      git ls-files --others --exclude-standard || return 1
    } | sort -u || return 1
    return 0
  fi

  debug "merge-base with trunk unavailable (shallow clone?) — trying GitHub compare API"
  head_sha=$(git rev-parse HEAD) || return 1
  files=$(github_compare_files "$head_sha") || return 1
  printf '%s\n' "$files"
}

# Map changed file paths (stdin, one per line) to workspace package specs for
# `-p`. Uses `cargo metadata` so names match the members (including nested
# members under crates/data-connectors/*). A member whose name another package in
# Cargo.lock also uses prints as `name@version`, because a bare `-p name` is then
# ambiguous and cargo refuses it.
packages_for_changed_files() {
  command -v cargo >/dev/null 2>&1 || fail "cargo not found — required for sign-off checks"
  # Targeted pre-lint is an optional fail-fast step: without python3, skip it
  # (return non-zero, caller tolerates) — the full workspace lint still runs.
  if ! command -v python3 >/dev/null 2>&1; then
    info "python3 not found — skipping targeted pre-lint (full workspace lint still runs)"
    return 1
  fi

  local files
  # Read paths first — the program below reads metadata from stdin.
  files=$(cat)
  has_content "$files" || return 0

  # Metadata streams over stdin rather than the environment: it is ~700 KB
  # against a 1 MiB ARG_MAX covering argv plus the whole environment of exec(),
  # and once the workspace outgrows that headroom python3 would stop starting
  # and the targeted pre-lint would silently vanish. The changed-file list is a
  # branch diff, small enough to stay in the environment. Keep cargo's stderr so
  # its own error (missing rustc, bad manifest, …) stays visible.
  cargo metadata --no-deps --format-version 1 \
    | CHANGED_FILES="$files" SIGNOFF_LINT_EXCLUDED="$LINT_EXCLUDED_PACKAGES" python3 -c '
import json, os, re, sys
from collections import Counter
from pathlib import Path

try:
    meta = json.load(sys.stdin)
except ValueError:
    raise SystemExit("cargo metadata failed — is this a Cargo workspace?")
excluded = set(os.environ.get("SIGNOFF_LINT_EXCLUDED", "").split())
workspace_root = Path(meta["workspace_root"]).resolve()
try:
    lockfile = (workspace_root / "Cargo.lock").read_text()
except OSError:
    lockfile = ""
locked_names = Counter(re.findall(r"^\[\[package\]\]\nname = \"([^\"]+)\"$", lockfile, re.M))

# Longest package root first so nested members (connector-postgres) win over
# a parent path if both ever appeared (they should not for exclusive members).
packages = []
for p in meta["packages"]:
    name = p["name"]
    if name in excluded:
        continue
    root = Path(p["manifest_path"]).resolve().parent
    try:
        root.relative_to(workspace_root)
    except ValueError:
        continue
    spec = name + "@" + p["version"] if locked_names[name] > 1 else name
    packages.append((str(root) + os.sep, spec))
packages.sort(key=lambda x: len(x[0]), reverse=True)

found = set()
for raw in os.environ["CHANGED_FILES"].splitlines():
    path = raw.strip()
    if not path:
        continue
    # Normalize under the workspace for prefix matching. Trailing-sep roots
    # avoid matching sibling packages that share a prefix (runtime vs
    # runtime-auth).
    abs_path = str((workspace_root / path).resolve())
    for root, spec in packages:
        if abs_path == root.rstrip(os.sep) or abs_path.startswith(root):
            found.add(spec)
            break

for spec in sorted(found):
    print(spec)
'
}

# Resolve workspace packages touched by the current branch vs trunk. Prints a
# space-separated list, or nothing if there are no package changes.
changed_workspace_packages() {
  local revision="$1"
  local files packages

  info "Diff base for targeted pre-lint: ${LINT_BASE_BRANCH}"

  if ! files=$(changed_files_vs_trunk "$revision"); then
    info "Could not list changed files vs ${LINT_BASE_BRANCH} — skipping targeted pre-lint"
    return 0
  fi
  if ! has_content "$files"; then
    debug "no changed files vs ${LINT_BASE_BRANCH}"
    return 0
  fi
  debug "changed files:"$'\n'"$files"

  packages=$(printf '%s\n' "$files" | packages_for_changed_files) || true
  if ! has_content "$packages"; then
    debug "no workspace packages in the changed files"
    return 0
  fi

  # Collapse newlines → spaces for `make PACKAGES=…`.
  echo "$packages" | tr '\n' ' ' | sed 's/[[:space:]]*$//'
}

# Feature set each named package carries in a full workspace resolve, formatted
# for `--features` and package-qualified so multi-package selections stay
# unambiguous.
#
# Without this a scoped `-p <crate>` run gets that crate's *own* defaults, which
# is not what the workspace build produces: `runtime` declares 54 features and no
# `default`, so `cargo clippy -p runtime` compiles it with zero features — a
# configuration no real build ever produces, because `spiced`'s defaults unify 35
# features into `runtime` across the workspace. The targeted steps would lint and
# test different code than the gate, which is both the false-failure class that
# SIGNOFF_SKIP_TARGETED_LINT exists to dodge and a guaranteed cache miss.
# Deriving the set from the resolve keeps the two in step with no hand-maintained
# list to drift.
workspace_features_for_packages() {
  local packages="$1"
  has_content "$packages" || return 0
  command -v python3 >/dev/null 2>&1 || return 0

  # A resolve carrying dependencies is ~10 MB here, an order of magnitude past
  # ARG_MAX, so it can only reach python over stdin.
  # Read the gate's feature set from this branch's Makefile. Older branches may
  # lack the helper, in which case the full gate still supplies its own defaults.
  local gate_features
  local -a metadata_args=(--format-version 1)
  gate_features=$(signoff_make --no-print-directory -s print-rust-gate-features 2>/dev/null) || gate_features=""
  [[ -z "$gate_features" ]] || metadata_args+=(--features "$gate_features")
  cargo metadata "${metadata_args[@]}" 2>/dev/null | python3 -c '
import json, sys

try:
    meta = json.load(sys.stdin)
except ValueError:
    raise SystemExit(0)

wanted = set(sys.argv[1].split())
# Match on workspace members only: a dependency can share a name with a member.
# A spec is `name` or, when the name is ambiguous, `name@version`.
members = set(meta.get("workspace_members", []))
packages = {p["id"]: p for p in meta["packages"]}

features = []
for node in meta.get("resolve", {}).get("nodes", []):
    package = packages.get(node["id"])
    if node["id"] not in members or package is None:
        continue
    name = package["name"]
    if name not in wanted and name + "@" + package["version"] not in wanted:
        continue
    # `default` is already on -- nothing here passes --no-default-features.
    features.extend(
        f"{name}/{feat}" for feat in sorted(node["features"]) if feat != "default"
    )
print(",".join(features))
' "$packages" || return 0
}

# Narrow a package-qualified feature list (`pkg/feat,…`) to the given packages.
# Cargo rejects a feature naming a package outside the `-p` selection outright
# ("the package 'x' does not contain this feature: y/z"), so any caller that
# builds a subset of the packages the features were resolved for has to filter
# first. Prints the kept features, or nothing when none survive.
features_for_packages() {
  local features="$1" packages="$2"
  has_content "$features" || return 0
  has_content "$packages" || return 0

  awk -v feats="$features" -v pkgs="$packages" 'BEGIN {
    n = split(pkgs, selected, /[ \t\n]+/)
    for (i = 1; i <= n; i++) {
      if (selected[i] == "") continue
      at = index(selected[i], "@")
      keep[at ? substr(selected[i], 1, at - 1) : selected[i]] = 1
    }

    m = split(feats, entries, /,/)
    out = ""
    for (i = 1; i <= m; i++) {
      slash = index(entries[i], "/")
      if (slash == 0) continue
      if (substr(entries[i], 1, slash - 1) in keep) {
        out = (out == "" ? entries[i] : out "," entries[i])
      }
    }
    print out
  }'
}

# Filter a space-separated package list to those with a library target. The
# unit-test gate is lib-only, and `--lib` is a fatal `no library targets found`
# on bin-only crates (spice, testoperator, …). Prints the filtered list, or
# nothing when none qualify or the metadata is unavailable (caller then skips
# the targeted tests; the full run still covers them).
packages_with_lib_targets() {
  local packages="$1"
  has_content "$packages" || return 0
  command -v python3 >/dev/null 2>&1 || return 0

  # Metadata streams in over stdin rather than an environment variable: this
  # workspace's `cargo metadata` output is ~700 KB against a 1 MiB ARG_MAX on
  # macOS, and that cap covers argv plus the whole environment of exec(). Once
  # the workspace outgrows the remaining headroom, python3 would stop starting
  # at all and the targeted tests would silently disappear. That forces
  # `python3 -c` over the heredoc used elsewhere here, since stdin is now data.
  # The package list stays in argv — it is a handful of crate names.
  cargo metadata --no-deps --format-version 1 2>/dev/null | python3 -c '
import json, sys

try:
    meta = json.load(sys.stdin)
except ValueError:
    # cargo metadata failed or produced nothing: print no packages, so the
    # caller skips the targeted tests instead of showing a decode traceback.
    raise SystemExit(0)

candidates = set(sys.argv[1].split())
# A proc-macro crate lib target is what `--lib` selects for it, so it counts.
LIB_KINDS = {"lib", "rlib", "proc-macro"}

with_lib = []
for p in meta["packages"]:
    if not any(LIB_KINDS & set(t["kind"]) for t in p["targets"]):
        continue
    # Keep the spec as given: `name@version` stays qualified for `-p`.
    for spec in (p["name"], p["name"] + "@" + p["version"]):
        if spec in candidates:
            with_lib.append(spec)
print(" ".join(sorted(with_lib)))
' "$packages" || return 0
}

# Append a short markdown section to the GitHub Actions job summary (no-op
# outside Actions, or when the summary file isn't writable).
append_step_summary() {
  local text="$1"
  [[ -n "${GITHUB_STEP_SUMMARY:-}" ]] || return 0
  printf '%s\n' "$text" >>"$GITHUB_STEP_SUMMARY" 2>/dev/null || true
}

# A status post that never lands leaves the commit carrying whatever it had.
# For a remote run that is the `pending` posted on the way in, which the
# Attestation check renders as a failure and which every reader — `signoff
# mine`, the PR-sweep tooling — takes for a run still in flight, so nobody
# re-dispatches. That state is indistinguishable from a live run, and a warning
# in the log of a finished job does not reach anyone looking at the PR.
warn_status_not_recorded() {
  local sha="$1" state="$2" attempts="$3"
  info "warning: could not post ${STATUS_CONTEXT}=${state} on ${sha:0:12} after ${attempts} attempt(s)"

  # A `pending` that fails to post strands nothing: the commit keeps whatever it
  # had, and this run still has its own verdict to post later. It is the verdict
  # failing that leaves a reader holding a `pending` they cannot tell from a run
  # still going, so that is what the summary is for.
  if [[ "$state" != "pending" ]]; then
    append_step_summary \
      "### Sign-off"$'\n'"**Verdict not recorded** on \`${sha:0:12}\` — the \`${STATUS_CONTEXT}=${state}\` status did not post after ${attempts} attempt(s). Any \`pending\` left on this commit is stale, not a run in flight: sign off again."$'\n'
  fi
}

# What GitHub keeps of a commit status description; the rest is discarded
# silently. Named rather than written inline at the slice below because the
# suite asserts every verdict fits it, and a second copy of the number is a
# guard that can pass while the real cut still truncates.
readonly STATUS_DESC_MAX_CHARS=140

# A failure verdict with its attribution, cut to fit the cap. The
# `(triggered by <user>)` suffix is last in every verdict, so a plain slice at
# STATUS_DESC_MAX_CHARS drops the name of whoever triggered the run — mid-word
# — while keeping every word of the detail (#14076). Composing the suffix here,
# once, and budgeting the *message* against what remains of the cap is what
# makes the attribution the part that can never be lost, whatever a future arm
# says. `${#}` and the slice count in the same units the shell does, so this
# agrees with the cut in post_commit_status by construction.
failure_status_desc() {
  local message="$1" user="$2"
  local suffix=" (triggered by ${user})"
  local budget=$((STATUS_DESC_MAX_CHARS - ${#suffix}))
  if ((budget < 0)); then
    budget=0
  fi
  if ((${#message} > budget)); then
    message="${message:0:budget}"
    # Back up to the last word boundary. Under a locale that counts bytes the
    # slice can land inside a multi-byte character (the em dash every arm
    # carries is three), and GitHub rejects a description that is not valid
    # UTF-8; a cut at a space never splits one. A message with no space at
    # all keeps the plain slice.
    case "$message" in
      *" "*) message="${message% *}" ;;
    esac
  fi
  printf '%s%s' "$message" "$suffix"
}

# Post a commit status for STATUS_CONTEXT. Used for pending/failure on remote
# runs and the final success attestation.
#
# Retried with backoff: this call is the only place a verdict exists, and a
# transient response — a 5xx, a network blip, a 401 from a job that has outlived
# its token — would otherwise discard hours of runner time for good.
post_commit_status() {
  local repo="$1" sha="$2" state="$3" description="$4"
  description="${description:0:STATUS_DESC_MAX_CHARS}"
  debug "posting ${STATUS_CONTEXT}=${state} on ${repo}@${sha}: ${description}"

  local -a backoff=()
  read -r -a backoff <<<"$STATUS_POST_BACKOFF" || true
  local attempts=$((${#backoff[@]} + 1))

  local attempt=1 response
  while true; do
    if response=$(gh api --method POST "repos/${repo}/statuses/${sha}" \
      -f state="$state" \
      -f context="${STATUS_CONTEXT}" \
      -f "description=${description}" 2>&1); then
      if (( attempt > 1 )); then
        info "posted ${STATUS_CONTEXT}=${state} on ${sha:0:12} on attempt ${attempt}"
      fi
      return 0
    fi

    # Report the response, not just that the call failed: "Bad credentials" on a
    # job that has outlived its token reads differently from a 5xx, and only the
    # second is something retrying can fix. Which one it was decides whether the
    # answer here is more attempts or a fresh token.
    info "warning: posting ${STATUS_CONTEXT}=${state} on ${sha:0:12} failed (attempt ${attempt}/${attempts}): $(printf '%s' "$response" | tr '\n' ' ')"

    if (( attempt >= attempts )); then
      warn_status_not_recorded "$sha" "$state" "$attempts"
      return 1
    fi
    # Never fatal: a backoff this cannot honour must not abort the run before
    # the attempt that would have recorded the verdict.
    sleep "${backoff[attempt - 1]}" || true
    attempt=$((attempt + 1))
  done
}

# The STATUS_CONTEXT state currently on a commit: success/pending/failure/error,
# or "none" when it has none. Asks gh's own jq rather than the jq binary — the
# remote sign-off path is otherwise free of that dependency (see require_jq).
signoff_state() {
  local repo="$1" sha="$2"
  gh api "repos/${repo}/commits/${sha}/status" \
    --jq ".statuses // [] | map(select(.context == \"${STATUS_CONTEXT}\")) | .[0].state // \"none\""
}

# Post the in-progress status for a remote run — unless the commit is already
# signed off. A re-dispatch against an attested commit is routine
# (`cancel-in-progress` makes it the normal way to recover from an evicted run),
# and posting `pending` over the success discards an attestation a multi-hour run
# earned — leaving the commit worse off than before if this run never reaches a
# verdict of its own. Suppressing the post costs no
# progress reporting: `mine` takes its ⟳ from the in-flight run list, not from
# this status. A `failure` from the checks still overwrites, because that one is
# this run's own verdict; a stale `failure` or `error` is likewise overwritten,
# because a run that is retrying it has nothing to preserve.
#
# Read-then-write with no compare-and-set, same as cmd_clear_pending: a success
# posted by another run on this SHA in the gap between the two calls is still
# overwritten. Nothing closes that gap, so it stays narrow — one API round trip —
# rather than the whole length of a run, which is what it was before.
post_pending_status() {
  local repo="$1" sha="$2" user="$3"
  # Declared before it is assigned on purpose: `local state=$(…)` reports
  # `local`'s own exit status, so the read's failure would go unnoticed.
  local state

  if ! state=$(signoff_state "$repo" "$sha"); then
    info "warning: could not read the current sign-off status — not posting pending"
    return 0
  fi
  if [[ "$state" == "success" ]]; then
    info "${sha:0:12} is already signed off — leaving that status in place while this run re-verifies it"
    return 0
  fi

  post_commit_status "$repo" "$sha" pending \
    "Remote sign-off in progress (triggered by ${user})…" \
    || info "warning: could not post pending sign-off status"
}

# --- commands ----------------------------------------------------------------

# Paths that can change what cargo/clippy/fmt/nextest do — Rust sources, the
# Cargo/toolchain config, and the config files the gate itself reads. Keep in
# sync with `rustAffecting` in .github/workflows/pr.yml and covered by the
# check-code-changes filter; `scripts/check_rust_gate_paths.py` enforces both,
# and docs/dev/ci_signoff.md explains why each path is here.
RUST_AFFECTING_PATH_PATTERN='(^(crates|bin|tools|vendor)/|\.(rs|snap|proto)$|(^|/)Cargo\.(toml|lock)$|(^|/)rust-toolchain(\.toml)?$|(^|/)\.cargo/|(^|/)\.?(clippy|rustfmt)\.toml$|(^|/)nextest\.toml$|(^|/)layers\.toml$|^scripts/(test_)?check_(crate_layers|table_layers|rust_gate_paths|module_reachability|fork_patches|bench_mysql_load_nulls|cayenne_data_path_fs)\.py$|^scripts/cayenne_data_path_fs_allowlist\.json$|^scripts/(test_)?rust_guard_common\.py$|^scripts/(test_)?nextest_build_targets\.py$|^docs/dev/fork_patches\.md$|^(Makefile|version\.txt)$|^test/tpc-bench/(Makefile|mysql-null-spec\.awk)$|^test/tls/|^test/spicepods/tpch/sf1/accelerated/postgres\[catalog\]\[changes\]\.yaml$|^test/source_versions\.json$|^\.schema/spicepod\.schema\.json$)'

# True when the branch delta vs trunk can affect Rust lint/build/tests.
# Prints nothing. Exit 0 = has Rust-affecting changes (or unknown — run checks).
# Exit 1 = no such paths in the changed set → safe to skip.
# Unknown (diff unavailable) returns 0 so we never skip when we can't tell.
branch_has_rust_changes() {
  local revision="$1"
  local files

  if ! files=$(changed_files_vs_trunk "$revision"); then
    debug "could not list changed files — assuming Rust changes (will run checks)"
    return 0
  fi
  if ! has_content "$files"; then
    debug "no changed files vs ${LINT_BASE_BRANCH} — no Rust changes"
    return 1
  fi
  # Feed grep a here-string rather than a pipe: `grep -q` exits at the first
  # match, and once "$files" exceeds the 64 KB pipe buffer that closes the pipe
  # while the writer still has data, so the writer dies of SIGPIPE and
  # `set -o pipefail` reports the whole pipeline as failed (status 141). This
  # function would then answer "no Rust changes" for a branch that does change
  # .rs files, and sign-off would skip lint/build/tests and still post success —
  # it needs a large diff whose first matching path lands early, which is why it
  # survived on smaller branches. Same hazard as the `| head -n1` note below.
  if grep -qE "$RUST_AFFECTING_PATH_PATTERN" <<<"$files"; then
    debug "Rust-affecting files present — will run Rust checks"
    return 0
  fi
  debug "no Rust-affecting files in changed set — can skip Rust lint/build/tests"
  return 1
}

# --- disk guard ---------------------------------------------------------------
#
# A sign-off links every test binary in the workspace into a `target/` that the
# self-hosted pool shares across branches. When that volume fills, the run does
# not fail where the space ran out: nextest reports the whole suite green, and
# then the *linker* dies with `errno=28` thousands of lines later, on a crate
# the branch never touched. That failure has none of the tells of a real one —
# no `-->` source pointers, no clippy diagnostic, a passing test summary — so
# it reads as a defect in the branch, and the reader either hunts a
# nonexistent bug or re-dispatches onto the same full disk. What follows makes
# the run say which one it was: a floor it refuses to start below, a recorder
# that catches the build saying it ran out, and a free-space backstop.

# Refuse to *start* a run the volume cannot hold, rather than discovering it
# three hours in. This is headroom for linking, not an estimate of a cold
# build: `target/` is warm on the pool, so what a run actually needs is room
# for the binaries it relinks.
readonly DEFAULT_MIN_FREE_GIB=25
# At failure time, this little free space means the volume is what broke, not
# the branch. Deliberately far below the preflight floor: a genuine compile
# error on a tight-but-workable disk must not be relabelled "infrastructure",
# while the `errno=28` death this exists to catch leaves the volume at ~0.
readonly DISK_CRITICAL_GIB=2
# run_checks returns this when the preflight refuses to start.
readonly EXIT_DISK_EXHAUSTED=70
# run_checks returns this when the branch's Makefile has no rule for a target
# the gate invokes, so the checks could not be run at all — see
# preflight_make_targets.
readonly EXIT_MAKE_TARGET_MISSING=71
# run_checks returns this when Cargo.lock no longer describes the workspace
# manifests, so cargo would have to rewrite it before anything could be built —
# see preflight_lockfile.
readonly EXIT_LOCKFILE_STALE=72
# run_checks returns this when the checks themselves rewrote Cargo.lock, so the
# committed lockfile does not describe the tree they passed on — see
# postcheck_lockfile. Deliberately *not* EXIT_LOCKFILE_STALE: that status means
# the gate refused before compiling anything, and describe_check_failure says so
# in as many words. This one is the opposite shape — the checks ran and passed,
# and only the attestation is refused — so it needs its own kind to avoid
# publishing "the checks did not run" about a run whose whole suite is green.
readonly EXIT_LOCKFILE_REWRITTEN=73
# Bash reports a foreground child killed by signal N as 128+N, and run_make_step
# returns make's own status untouched. So a status at or above this means `make`
# never reached a verdict of its own — the process tree was signalled. That is
# how a `Sign off` step reads when its `timeout-minutes` budget expires (#12518)
# and how a cancelled job reads (#12424); a recipe that genuinely fails exits 2.
#
# It only reads that way when make dies *without* handling the signal. GNU make
# installs its own handler: it removes the target it was building, then kills
# itself with the signal — but a recipe line that traps and exits, or a
# sub-make, can return an ordinary small status instead, and that is what this
# script then observes. So this bound is a sufficient test for "signalled", not
# a necessary one; SIGNOFF_SIGNALLED below is what covers the rest.
readonly EXIT_SIGNAL_BASE=128
# How the linker's out-of-disk death actually reads in the run log:
# `ld: write() failed, errno=28 (No space left on device)`. Either spelling is
# enough; matching both survives a toolchain that words one of them differently.
readonly DISK_FULL_PATTERN='No space left on device|errno=28'

# --- compiler-cache guard -----------------------------------------------------
#
# The pool's runners set RUSTC_WRAPPER=sccache (see .github/actions/setup-sccache)
# against an S3-compatible endpoint on the host. When that endpoint stops
# answering, sccache's server cannot start, and *every* rustc invocation from
# that moment on dies before compiling anything:
#
#   sccache: error: Server startup failed: cache storage failed to read: …
#     error sending request for url (http://127.0.0.1:8333/sccache/…/.sccache_check):
#     tcp connect error: Connection refused (os error 61)
#   error: process didn't exit successfully: `sccache …/rustc -vV` (exit status: 2)
#
# The branch is not evaluated — nothing is compiled — but the run reads as
# `Sign-off checks failed after 5859s`, which is a statement about the diff. So
# the author hunts a nonexistent bug in a branch that was never built, and the
# commit carries a `signoff=failure` that disqualifies it outright. sccache is a
# cache: its backend going away says nothing about the code. Recognise it and say
# so, exactly as the disk guard above does for a volume that filled.
#
# Anchored on sccache's own `error:` channel, which rustc, clippy and nextest
# have no way to produce while reporting on the branch.
#
# The alternatives are taken from sccache's source rather than from the spellings
# we happen to have seen, so the set is an enumeration and not a running tally.
# `connect_or_start_server` is the whole of the path a `RUSTC_WRAPPER=sccache`
# call takes, and it has four outcomes: `Ok` compiles and `AddrInUse` retries,
# while `ServerStartup::Err` bails with `Server startup failed: {reason}` and
# `ServerStartup::TimedOut` bails with `Timed out waiting for server startup`.
# So those two are the ways an unusable cache reaches this channel, and the third
# alternative below is the storage self-check's own `cache storage failed to
# read: {…}`, for an invocation that reaches a live server and then cannot read
# through it. sccache prints the first line of the error as `sccache: error: {}`
# and every later cause as `sccache: caused by: {}`, so the anchor belongs on the
# first line only.
#
# The timeout is matched on the prefix its two bails share — sccache words it
# `Timed out waiting for server startup. Maybe the remote service is
# unreachable?` from the wrapper path and bare from `--start-server`. Keep it a
# prefix: this string is an awk ERE, so the `?` ending the longer wording is a
# quantifier, and spelling that sentence out here would match `unreachabl` plus
# an optional `e` while reading as though it were deliberate.
readonly CACHE_UNUSABLE_PATTERN='sccache: error: Server startup failed|sccache: error: cache storage failed|sccache: error: Timed out waiting for server startup'

# The loader's refusal to execute a test binary, in the two spellings the pool's
# runners produce: EBADMACHO (88) on the macOS boxes, ENOEXEC on the Linux ones.
# Both mean the file `nextest` was handed is not a loadable executable — a
# truncated or clobbered artifact on the shared `target/` volume, which is a
# statement about the runner and not about the branch.
readonly CORRUPT_ARTIFACT_PATTERN='Malformed Mach-o file|Exec format error'

# The line that says the loader error above came from `nextest` trying to run a
# build artifact, rather than from a test asserting on that wording. Both are
# required, because this repo's own suites do assert error strings, and excusing
# a genuine test failure as infrastructure is the more expensive mistake of the
# two. `nextest` prints this when a binary fails to execute during enumeration,
# which is where a corrupt artifact is met first (#13518).
readonly TEST_LIST_FAILURE_PATTERN='error: creating test list failed'

# The compiler driver reporting that a subprocess it ran died of a signal
# rather than returning a diagnostic — the linker on every run seen so far,
# but the driver words a crash in its own frontend identically (`clang: error:
# unable to execute command: Segmentation fault: 11`), so this names the class
# and not the tool. `clang` prints the first form with the signal's name and
# the second on its way out; both are its own words for its own crash, and it
# writes a crash snapshot beside them. GNU's driver says it through `collect2`, whose signal path is a
# `fatal error:` rather than an `error:`. `Killed: 9` is the same class from
# the other side: the kernel taking the linker for memory.
#
# Anchored on the driver's own `<driver>: error: ` prefix AT THE START of the
# line (after the indentation rustc gives linker output), not on the words
# alone: rustc quotes a build script's or `compile_error!`'s text verbatim under
# its own `error:` line — `error: clang: error: linker command failed …` — and
# a genuine defect worded like a crash, prefix included, must stay a verdict
# about the branch even once cargo prints its summary (#13614). The driver's
# own report is never preceded by anything but whitespace.
# `[+]` rather than `\+` because awk rewrites `\+` in a -v value to a plain `+`.
readonly TOOLCHAIN_CRASH_PATTERN='^[[:space:]]*(clang|clang[+][+]|cc|c[+][+]|gcc|g[+][+]|collect2): (fatal )?error: (unable to execute command: (Segmentation fault|Bus error|Illegal instruction|Abort trap|Killed: 9)|linker command failed due to signal|ld terminated with signal)'

# The line that says the crash above stopped a compilation, rather than being
# quoted by a test that ran to completion. cargo prints it once per crate whose
# build did not finish; a genuine test failure never reaches it, because a test
# only runs once its crate compiled. Both halves are required, for the same
# reason as the artifact pair above: this repo's own suites assert on error
# strings, and excusing a real failure as infrastructure is the costlier mistake.
readonly COMPILE_ABORTED_PATTERN='error: could not compile `[^`]+`.* due to '

# Set to 1 on remote runs, where run_make_step watches build output for the
# out-of-disk and unusable-cache signatures. Separates "watched, and it was
# neither" from "nothing watched at all", which failure_kind answers differently.
SIGNOFF_DISK_WATCH="${SIGNOFF_DISK_WATCH:-}"

# Set to 1 by run_make_step when the step it ran reported running out of disk.
#
# A shell variable rather than a file, because the signal has to survive the
# condition it reports. Recording the line by appending to a marker file needed
# an allocation at exactly the moment allocation is failing — and on macOS
# $TMPDIR and the workspace are usually the same APFS container, so there was
# nowhere to put that file that was reliably writable. An empty marker read as
# "not a disk failure", so the branch was blamed for the volume (#12427). The
# watcher's exit status needs no disk at all.
#
# Seeded from the environment so the unit tests can set up a classification
# without running a build; run_make_step resets it per step, so an inherited
# value cannot outlive a run that watched anything.
SIGNOFF_DISK_HIT="${SIGNOFF_DISK_HIT:-}"

# Set to 1 by run_make_step when the step it ran reported an unusable compiler
# cache. Same mechanism and the same reason for being a variable rather than a
# file as SIGNOFF_DISK_HIT above, and likewise seeded from the environment so a
# test can set up a classification without running a build.
SIGNOFF_CACHE_HIT="${SIGNOFF_CACHE_HIT:-}"

# Set to 1 by run_make_step when the step it ran could not execute a test binary
# it built. Same mechanism and the same reason for being a variable rather than
# a file as the two above, and likewise seeded from the environment so a test
# can set up a classification without running a build.
SIGNOFF_ARTIFACT_HIT="${SIGNOFF_ARTIFACT_HIT:-}"

# Set to 1 by run_make_step when the step it ran lost a compilation to a tool
# that crashed — the linker taking a signal — rather than to a diagnostic. Same
# mechanism and the same reason for being a variable rather than a file as the
# three above, and likewise seeded from the environment so a test can set up a
# classification without running a build.
SIGNOFF_TOOLCHAIN_HIT="${SIGNOFF_TOOLCHAIN_HIT:-}"

# The statuses the watcher exits with to report each signature. Deliberately
# not 1 or 2: awk uses those for its own errors, and a watcher that itself died
# must not be read as a volume that filled. Reserving distinct statuses is also
# what lets run_make_step tell "ran, saw nothing" (0) from "never reached a
# verdict" (anything else), which it must not conflate — see run_make_step.
readonly DISK_WATCH_HIT_STATUS=3
readonly CACHE_WATCH_HIT_STATUS=4
readonly ARTIFACT_WATCH_HIT_STATUS=5
readonly TOOLCHAIN_WATCH_HIT_STATUS=6

# The watcher itself, held in one place so the probe below runs exactly the
# program that will read the build output — a probe of anything else predicts
# nothing about the invocation that matters.
#
# awk rather than a captured log: it passes every line straight through and
# keeps two bits of state, so watching costs nothing on a volume that is already
# short of space. fflush keeps the output streaming to the Actions log line by
# line, as it does unwatched.
#
# Disk wins when both signatures appear: a volume at zero can break sccache's
# storage too, and reclaiming space is then the remedy that also fixes the
# cache. One exit status rather than a bitmask keeps the "watcher never reached
# a verdict" reading below unambiguous.
readonly DISK_WATCH_PROGRAM='
    $0 ~ pat { hit = 1 }
    $0 ~ cache_pat { cache_hit = 1 }
    $0 ~ artifact_pat { artifact_hit = 1 }
    $0 ~ list_pat { list_failed = 1 }
    $0 ~ crash_pat { crash_hit = 1 }
    $0 ~ compile_pat { compile_aborted = 1 }
    { print; fflush() }
    END {
      if (hit) exit (hit_status + 0)
      if (cache_hit) exit (cache_status + 0)
      if (artifact_hit && list_failed) exit (artifact_status + 0)
      if (crash_hit && compile_aborted) exit (crash_status + 0)
    }
  '

# Run the watcher over no input at all. A usable watcher reads the empty stream,
# matches nothing, and exits 0; one that cannot run — no awk on the runner, a
# variant that rejects the program — reports its own non-zero status here,
# while nothing is downstream of it.
disk_watch_probe() {
  awk -v pat="$DISK_FULL_PATTERN" -v hit_status="$DISK_WATCH_HIT_STATUS" \
    -v cache_pat="$CACHE_UNUSABLE_PATTERN" -v cache_status="$CACHE_WATCH_HIT_STATUS" \
    -v artifact_pat="$CORRUPT_ARTIFACT_PATTERN" -v list_pat="$TEST_LIST_FAILURE_PATTERN" \
    -v artifact_status="$ARTIFACT_WATCH_HIT_STATUS" \
    -v crash_pat="$TOOLCHAIN_CRASH_PATTERN" -v compile_pat="$COMPILE_ABORTED_PATTERN" \
    -v crash_status="$TOOLCHAIN_WATCH_HIT_STATUS" \
    "$DISK_WATCH_PROGRAM" </dev/null >/dev/null 2>&1
}

# Give up the reading and say so. Called from both places a watcher can fail to
# deliver one — before it runs, and part-way through — so the two cannot drift
# into describing the same outcome differently.
disarm_disk_watch() {
  info "warning: the build-output watcher exited ${1} rather than reporting a verdict — falling back to free-space classification"
  SIGNOFF_DISK_WATCH=""
}

# Every make invocation that selects or runs checks uses the same environment.
# Ambient filters and recursive make overrides cannot narrow an attestation or
# turn its checks into a dry run. Nextest's checked-in profile owns retries and
# the empty-suite verdict; thread-count and output preferences remain usable.
signoff_make() {
  env -u MAKEFLAGS -u GNUMAKEFLAGS -u MFLAGS -u MAKEOVERRIDES -u MAKEFILES \
    -u NEXTEST_FLAG -u NEXTEST_FILTER_EXTRA -u NEXTEST_PROFILE \
    -u NEXTEST_RETRIES -u NEXTEST_NO_TESTS make "$@"
}

# Run one `make` step, recording whether it died for want of disk or for want of
# a reachable compiler cache. Returns make's own status, never the watcher's.
# With the watch off, local output streams directly to the terminal.
run_make_step() {
  if [[ -z "$SIGNOFF_DISK_WATCH" ]]; then
    signoff_make "$@"
    return $?
  fi
  local status watch_status probe_status=0
  local -a pipe_status
  # Reset per step, so the verdict describes the step that actually failed. Left
  # to accumulate, a step that merely *mentioned* running out of disk and then
  # succeeded would still be blaming the volume for a genuine test failure two
  # steps later.
  SIGNOFF_DISK_HIT=""
  SIGNOFF_CACHE_HIT=""
  SIGNOFF_ARTIFACT_HIT=""
  SIGNOFF_TOOLCHAIN_HIT=""
  # Ask whether the watcher runs before make writes a byte to it, because the
  # only other place to find out is downstream of make — where a watcher that
  # exits at once closes the pipe under a still-writing make, make dies of
  # SIGPIPE, and the step reports 128+13 instead of its own status. A genuine
  # compile failure then reads as a run that was signalled rather than one that
  # was judged. Probing first keeps make's status make's own: an unusable
  # watcher costs the reading, which the free-space backstop already covers,
  # and nothing else. Regression test for #12734.
  disk_watch_probe || probe_status=$?
  if [[ "$probe_status" -ne 0 ]]; then
    disarm_disk_watch "$probe_status"
    signoff_make "$@"
    return $?
  fi
  signoff_make "$@" 2>&1 | awk \
      -v pat="$DISK_FULL_PATTERN" -v hit_status="$DISK_WATCH_HIT_STATUS" \
      -v cache_pat="$CACHE_UNUSABLE_PATTERN" -v cache_status="$CACHE_WATCH_HIT_STATUS" \
      -v artifact_pat="$CORRUPT_ARTIFACT_PATTERN" -v list_pat="$TEST_LIST_FAILURE_PATTERN" \
      -v artifact_status="$ARTIFACT_WATCH_HIT_STATUS" \
      -v crash_pat="$TOOLCHAIN_CRASH_PATTERN" -v compile_pat="$COMPILE_ABORTED_PATTERN" \
      -v crash_status="$TOOLCHAIN_WATCH_HIT_STATUS" \
      "$DISK_WATCH_PROGRAM"
  # Copy the whole array in one statement: reading PIPESTATUS is itself a command,
  # so a second `x="${PIPESTATUS[1]}"` would be reading the *assignment's* status
  # and, under `set -u`, abort on the now-absent index.
  pipe_status=("${PIPESTATUS[@]}")
  status="${pipe_status[0]:-0}"
  watch_status="${pipe_status[1]:-0}"
  if [[ "$watch_status" -eq "$DISK_WATCH_HIT_STATUS" ]]; then
    SIGNOFF_DISK_HIT=1
  elif [[ "$watch_status" -eq "$CACHE_WATCH_HIT_STATUS" ]]; then
    SIGNOFF_CACHE_HIT=1
  elif [[ "$watch_status" -eq "$ARTIFACT_WATCH_HIT_STATUS" ]]; then
    SIGNOFF_ARTIFACT_HIT=1
  elif [[ "$watch_status" -eq "$TOOLCHAIN_WATCH_HIT_STATUS" ]]; then
    SIGNOFF_TOOLCHAIN_HIT=1
  elif [[ "$watch_status" -ne 0 ]]; then
    # The watcher started, so the probe cleared it, and then died part-way
    # through: killed for memory, or a signal that reached the whole group. Its
    # silence is then neither "no out-of-disk line went past" nor "the cache was
    # reachable" — nothing reliably read the output to the end — so leaving the
    # watch armed would let failure_kind assert "not disk" on the authority of a
    # reading nobody finished, which is the same mislabelling in the other
    # direction from #12427. Disarm it so classification falls back to the
    # free-space backstop, exactly as on an unwatched local run.
    #
    # make can still have taken SIGPIPE on its way out here, and the probe
    # cannot prevent that: a watcher that dies mid-stream closes the pipe with
    # make still writing. What the probe removes is the whole class where the
    # watcher was never going to run at all, which is the one that costs
    # make's status on every step rather than on the step that raced.
    disarm_disk_watch "$watch_status"
  fi
  return "$status"
}

# True when this run watched its build output at all, i.e. the watch's verdict —
# including its "no ENOSPC line went past" — is worth something. run_make_step
# clears the flag if the watcher itself failed, so this stays false for a run
# whose watch was requested but never actually delivered a reading.
disk_watch_armed() {
  [[ -n "$SIGNOFF_DISK_WATCH" ]]
}

# True when this run's build actually reported running out of disk. This is the
# authoritative signal — unlike a free-space reading taken after the fact, it
# cannot be washed out by the partial artifacts cargo unlinks on its way out,
# and unlike a marker file it costs no allocation at the moment allocation is
# what is failing.
build_hit_disk_full() {
  [[ -n "$SIGNOFF_DISK_HIT" ]]
}

# True when this run's build reported that sccache could not reach its storage.
# Unlike disk there is no after-the-fact backstop for this: the endpoint is on
# the runner and may well be answering again by the time the run ends, so the
# only evidence is what the build said while it was failing. Without the watch
# there is no reading at all, and claiming infrastructure without one is the
# mislabelling that matters most to avoid.
build_hit_cache_unusable() {
  [[ -n "$SIGNOFF_CACHE_HIT" ]]
}

# True when the step that failed could not execute a test binary it built. Read
# in the same shell that ran the step, for the same reason as its two siblings.
build_hit_corrupt_artifact() {
  [[ -n "$SIGNOFF_ARTIFACT_HIT" ]]
}

# True when the step that failed lost a compilation to a crashing tool rather
# than to a diagnostic. Read in the same shell that ran the step, for the same
# reason as its three siblings.
build_hit_toolchain_crash() {
  [[ -n "$SIGNOFF_TOOLCHAIN_HIT" ]]
}

# Free space in GiB on the volume holding "$1" (default: the working tree).
# Prints an integer. Returns non-zero when df is absent or its output does not
# parse — every caller reads that as "unknown" and never as "full", so a runner
# whose df we cannot read still gets to run its sign-off.
free_disk_gib() {
  # The volume that actually holds the build output: `target/` is what fills,
  # and CARGO_TARGET_DIR can put it on a different filesystem than the checkout.
  local path="${1:-${CARGO_TARGET_DIR:-.}}" free
  command -v df >/dev/null 2>&1 || return 1
  # -P: POSIX one-line-per-filesystem output, so Available is reliably field 4
  # even when a long device name would wrap in df's default format.
  # -k: 1024-byte blocks on both macOS (whose df defaults to 512) and Linux.
  free=$(df -Pk "$path" 2>/dev/null | awk 'NR==2 { print int($4 / 1048576) }') || return 1
  [[ "$free" =~ ^[0-9]+$ ]] || return 1
  printf '%s\n' "$free"
}

# True when the work volume is so empty that a failure is the volume's fault
# rather than the branch's. Unknown free space answers false: without a reading
# we cannot claim infrastructure, and mislabelling a real failure is worse.
disk_is_critical() {
  local free
  free=$(free_disk_gib) || return 1
  (( free < DISK_CRITICAL_GIB ))
}

# Set to 1 by the handler armed in watch_for_signals when this process is
# signalled.
#
# Cancelling an Actions job signals the whole process group, so this script and
# the `make` it is waiting on both receive it. When make answers with a small
# status of its own rather than dying of the signal, the 128+signum reading
# above sees an ordinary failing status and classification falls through to
# "checks" — so a run that judged nothing published `signoff=failure` saying the
# branch's checks failed (#12710). Recording the signal where it is unambiguous,
# in the process that also receives it, is what separates the two.
#
# A shell variable rather than a file, for the same reason as SIGNOFF_DISK_HIT:
# a handler that has to allocate to report is a handler that fails in exactly
# the conditions worth reporting.
#
# Seeded from the environment so the unit tests can set up a classification
# without signalling anything.
SIGNOFF_SIGNALLED="${SIGNOFF_SIGNALLED:-}"

# The `Sign off` step's own budget, as signoff.yml declares it in
# `timeout-minutes`, and the grace below it within which a run is taken to have
# expired rather than failed.
#
# A budget expiry is never delivered to this script as a signal. The runner
# declares the step timed out, runs the post-job steps, and only then reaps
# the leftover process tree — `rustc` or `cargo-nextest` first and this script's
# own shell last — so `make` returns a small status that reads exactly like a
# failing recipe, the handler above never fires, and classification falls
# through to "checks": `signoff=failure` about a build that was still
# compiling, posted 6–27 s after the workflow's "Resolve an incomplete sign-off"
# step had already restated the honest `pending` (#13843). Knowing the deadline
# is what lets failure_kind see the expiry the runner never signalled.
#
# The grace absorbs two offsets, both measured on the pool: this script's clock
# starts a few seconds into the step, and the kill lands a few seconds past the
# budget, so the elapsed a dying run reports sits 10 s either side of the
# budget (21170–21225 s against 21180). A genuine failure inside the grace is
# classified as expired and publishes nothing — the `pending` the run posted on
# its way in stands, and the author signs off again — which is the cheap
# direction to be wrong in: that run was within two minutes of being killed
# regardless, while the other direction is a false `failure` that disqualifies
# the commit.
#
# Unset on a local run, where no budget applies, so the check is inert there.
SIGNOFF_STEP_BUDGET_MINUTES="${SIGNOFF_STEP_BUDGET_MINUTES:-}"
SIGNOFF_STEP_BUDGET_GRACE_SECONDS="${SIGNOFF_STEP_BUDGET_GRACE_SECONDS:-120}"

# True when `elapsed` seconds of checks reach the step budget less its grace.
# False, and inert, when no budget is configured; false, saying so on the debug
# channel the remote run keeps on, when the budget or the grace is not a whole
# number, because a malformed value must not turn every failure into an
# expiry. Each value is bounded to seven decimal
# digits and read in base 10: bash's arithmetic reads a leading zero as octal
# (`0353` is 235, a budget that expires two hours early) and wraps a value past
# 2^63 negative (every failure an expiry), and `^[0-9]+$` admits both.
budget_expired() {
  local elapsed="${1:-}"
  [[ -n "$SIGNOFF_STEP_BUDGET_MINUTES" ]] || return 1
  if [[ ! "$SIGNOFF_STEP_BUDGET_MINUTES" =~ ^[0-9]{1,7}$ ]] \
    || [[ ! "$SIGNOFF_STEP_BUDGET_GRACE_SECONDS" =~ ^[0-9]{1,7}$ ]]; then
    debug "ignoring SIGNOFF_STEP_BUDGET_MINUTES='${SIGNOFF_STEP_BUDGET_MINUTES}' and SIGNOFF_STEP_BUDGET_GRACE_SECONDS='${SIGNOFF_STEP_BUDGET_GRACE_SECONDS}' — each must be a whole number of at most seven digits, so a run that reaches its budget is classified by its exit status alone"
    return 1
  fi
  [[ "$elapsed" =~ ^[0-9]{1,7}$ ]] || return 1
  (( 10#$elapsed + 10#$SIGNOFF_STEP_BUDGET_GRACE_SECONDS >= 10#$SIGNOFF_STEP_BUDGET_MINUTES * 60 ))
}

# Record that this run was signalled, for failure_kind to read once the `make`
# it was waiting on returns.
#
# Deliberately does nothing else. The handler runs between commands, so the work
# of describing and publishing happens on the normal path with the exit status
# intact; re-raising here would instead kill the script before it could decline
# to publish, and leave the `pending` it posted on the way in unexplained.
note_signal() {
  SIGNOFF_SIGNALLED=1
}

# Arm the signal handler. Remote runs only, and called only from the verify
# path: trapping INT locally would swallow the Ctrl-C an interactive `make
# signoff` expects to stop it, and this script has nothing to gain from
# surviving one. Same remote-only shape, and same reason, as SIGNOFF_DISK_WATCH.
#
# HUP as well as INT and TERM: a runner tearing down can drop the controlling
# terminal before it signals anything else.
watch_for_signals() {
  # shellcheck disable=SC2064  # No expansion here; the handler is a function.
  trap note_signal INT TERM HUP
}

# Names what broke in a check run that did not pass, given run_checks' exit
# status: "signalled" when nothing judged the branch at all, "disk" when the work
# volume is the cause, "cache" when sccache could not reach its storage and so
# nothing was compiled, "corrupt-artifact" when the runner could not load a test
# binary it built, "toolchain-crash" when a tool the build ran died of a signal,
# "missing-target" and "stale-lockfile" when a preflight refused to start,
# "checks" for everything else, which is the branch. Three
# ways to reach "disk", in falling order of authority: the preflight refused to
# start, the build said so itself, or the volume is at ~0 now. The last is a
# backstop for a build whose output we did not record — a local run, or a remote
# one whose watcher died before it could read anything — which is why it is not
# the only signal.
failure_kind() {
  local check_status="$1" elapsed="${2:-}"

  # First, because it is the one kind that says the checks reached no verdict
  # rather than which verdict they reached. The two disk signals below both
  # describe a `make` that *returned*: the preflight refusing to start (70) and
  # a build that printed ENOSPC and died. Neither can coexist with a status that
  # says make itself was killed.
  #
  # Three readings, because any one alone misses a case. The status covers a
  # make that died of the signal, including on a local run with no handler
  # armed; the recorded signal covers a make that handled it and returned a
  # small status of its own, which is indistinguishable from a failing recipe by
  # status alone (#12710); the clock covers a step budget that expired, which
  # neither of the other two can see because the runner reaps `make` without
  # signalling this script (#13843, see budget_expired). Note the recorded
  # signal and the clock are checked even against EXIT_DISK_EXHAUSTED below: a
  # run signalled during the preflight reached no verdict either, and "no
  # verdict" outranks naming a cause.
  if [[ -n "$SIGNOFF_SIGNALLED" ]] || [[ "$check_status" -ge "$EXIT_SIGNAL_BASE" ]] \
    || budget_expired "$elapsed"; then
    echo "signalled"
    return
  fi

  # The preflight's own refusal needs no corroboration.
  if [[ "$check_status" -eq "$EXIT_DISK_EXHAUSTED" ]]; then
    echo "disk"
    return
  fi

  # Same authority, and for the same reason: this run stopped before it compiled
  # anything, so no later reading — a watched build's, a free-space sample's —
  # can describe it better than the preflight that refused to start.
  if [[ "$check_status" -eq "$EXIT_MAKE_TARGET_MISSING" ]]; then
    echo "missing-target"
    return
  fi

  # And the third preflight, for the same reason: this run stopped before it
  # compiled anything, so nothing a later reading could offer describes it better.
  if [[ "$check_status" -eq "$EXIT_LOCKFILE_STALE" ]]; then
    echo "stale-lockfile"
    return
  fi

  # Not a preflight at all, and the one kind here that follows a *passing* suite:
  # the post-check found that lint and nextest rewrote Cargo.lock on their way
  # past. Same absolute authority as the preflights above — the post-check read
  # the file itself — but the opposite story, so it must not share their status.
  if [[ "$check_status" -eq "$EXIT_LOCKFILE_REWRITTEN" ]]; then
    echo "rewritten-lockfile"
    return
  fi

  # If we watched the build, the watch decides — both ways. No ENOSPC line means
  # the build ran out of many things but not disk, and a free-space reading must
  # not overrule that: on a shared pool another run can drag the volume under any
  # threshold while *this* branch fails for its own reasons, and calling that
  # "infrastructure" tells the author to re-dispatch a branch that will fail
  # again. Free space is consulted only when nothing watched.
  if disk_watch_armed; then
    if build_hit_disk_full; then
      echo "disk"
    elif build_hit_cache_unusable; then
      echo "cache"
    elif build_hit_corrupt_artifact; then
      # Last of the three, because the other two are upstream of this one: a
      # volume that fills mid-link and a cache that cannot be reached both
      # produce short or missing artifacts, and naming the cause is what tells
      # the reader which remedy applies. Reached only when neither of those
      # signatures went past, i.e. the artifact is unloadable for a reason this
      # run cannot see.
      echo "corrupt-artifact"
    elif build_hit_toolchain_crash; then
      # Last, because the three above each name a cause with its own remedy,
      # while this one only names the symptom: a tool the build ran died of a
      # signal, and nothing here can say why. A volume that fills mid-link
      # kills the linker with ENOSPC rather than a signal, so disk and this do
      # not normally coincide — but when both signatures go past, reclaiming
      # space is the remedy that fixes both.
      echo "toolchain-crash"
    else
      echo "checks"
    fi
    return
  fi

  if disk_is_critical; then echo "disk"; else echo "checks"; fi
}

# What to publish about a check run that did not pass, given run_checks' exit
# status, how long it ran, and who dispatched it. Sets three globals rather than
# returning a packed string, the way run_make_step reports through
# SIGNOFF_DISK_HIT:
#
#   SIGNOFF_FAILURE_STATUS_DESC  the commit-status description, or "" to publish
#                                no verdict at all
#   SIGNOFF_FAILURE_SUMMARY      the step summary
#   SIGNOFF_FAILURE_MESSAGE      what `fail` says on the way out
#
# An empty description is the whole point of the "signalled" case and is not an
# error path: see below.
SIGNOFF_FAILURE_STATUS_DESC=""
SIGNOFF_FAILURE_SUMMARY=""
SIGNOFF_FAILURE_MESSAGE=""
describe_check_failure() {
  local check_status="$1" elapsed="$2" user="$3"

  case "$(failure_kind "$check_status" "$elapsed")" in
    signalled)
      # Publish nothing. Nothing judged this branch — the process tree was
      # signalled — so the status this run left on its way in is still the most
      # this run can honestly claim: the `pending` it posted before starting, or
      # an earlier `success` post_pending_status declined to overwrite. A leftover
      # `pending` is already what the workflow's "Resolve an incomplete sign-off"
      # step is there to describe.
      #
      # Any verdict written here would assert something nothing established:
      # "checks failed" about a suite the log shows still passing when the
      # 353-minute budget expired (#12518), on a commit that may already carry a
      # `signoff=success` an earlier run earned (#12520). Neither correction
      # handler can take it back — both are gated on `cancelled()`, and a budget
      # expiry is a *failed* step by #12343's design — so the only safe moment to
      # decline is here.
      SIGNOFF_FAILURE_STATUS_DESC=""
      SIGNOFF_FAILURE_SUMMARY="### Sign-off"$'\n'"**Did not complete** after ${elapsed}s — the run was signalled (its step budget expired, or the job was stopped), so **the checks reached no verdict** and no failure status is published. Nothing reported a failure; equally, nothing cleared the branch. The \`${STATUS_CONTEXT}\` status stands as this run left it — the \`pending\` posted at the start, or an earlier \`success\` this run declined to overwrite. Sign off again: a branch that repeatedly exhausts the budget is either contending for the pool or has lengthened the build itself."$'\n'
      SIGNOFF_FAILURE_MESSAGE="sign-off did not complete: the run was signalled after ${elapsed}s, so the checks reached no verdict — sign off again"
      ;;
    disk)
      # An out-of-disk run says nothing useful by default — the commit status is
      # all most readers see, so it has to carry the distinction itself.
      SIGNOFF_FAILURE_STATUS_DESC="$(failure_status_desc "Runner out of disk after ${elapsed}s — checks did not complete, re-dispatch" "$user")"
      SIGNOFF_FAILURE_SUMMARY="### Sign-off"$'\n'"**Infrastructure failure** after ${elapsed}s — the build ran out of disk on the runner work volume, so **the checks did not complete**. Re-dispatch once the runner has space. Only if this recurs for one branch alone is the diff worth suspecting: a build script or dependency change can consume the volume by itself."$'\n'
      SIGNOFF_FAILURE_MESSAGE="sign-off aborted: the runner ran out of disk (the checks did not complete)"
      ;;
    cache)
      # Same reasoning as disk: the reader sees the commit status, not the log,
      # so the status itself has to say the branch was never evaluated.
      SIGNOFF_FAILURE_STATUS_DESC="$(failure_status_desc "Compiler cache unreachable after ${elapsed}s — checks did not complete, re-dispatch" "$user")"
      SIGNOFF_FAILURE_SUMMARY="### Sign-off"$'\n'"**Infrastructure failure** after ${elapsed}s — \`sccache\` could not reach its storage endpoint on this runner, so every \`rustc\` invocation failed before compiling anything and **the checks did not complete**. Nothing here is a statement about the branch. Re-dispatch once the runner's cache endpoint is answering; if it stays down, the pool's \`sccache\` service is what needs attention (see \`.github/actions/setup-sccache\`)."$'\n'
      SIGNOFF_FAILURE_MESSAGE="sign-off aborted: sccache could not reach its storage (the checks did not complete)"
      ;;
    corrupt-artifact)
      # Neither a verdict on the code nor a threshold anyone can act on: the
      # runner handed `nextest` a file the loader will not execute, so
      # enumeration failed and no test ran. Worded like the other kinds that
      # reached no verdict, because the alternative — the generic "checks
      # failed" — sends the author to look for a defect in a diff nothing
      # judged (#13518, and #12813 before it).
      #
      # Hedged rather than asserted: this cannot tell whether the crate whose
      # binary would not load is one the branch touches. A recurrence on this
      # branch alone, or one naming a crate whose build script it changes, is
      # worth suspecting the diff for.
      SIGNOFF_FAILURE_STATUS_DESC="$(failure_status_desc "Test binary would not load after ${elapsed}s — checks did not complete, re-dispatch" "$user")"
      SIGNOFF_FAILURE_SUMMARY="### Sign-off"$'\n'"**Infrastructure failure** after ${elapsed}s — \`nextest\` could not execute a test binary while listing tests, because the runner's copy is not a loadable executable, so **the checks did not complete**. That is a truncated or clobbered artifact on the shared \`target/\` volume rather than a statement about the branch. Re-dispatch the sign-off. If it recurs on this branch alone, or names a crate whose build script this branch changes, the diff is worth suspecting."$'\n'
      SIGNOFF_FAILURE_MESSAGE="sign-off aborted: a test binary on the runner would not load, so nextest never ran the suite (the checks did not complete) — re-dispatch"
      ;;
    toolchain-crash)
      # The compiler driver reported that a subprocess it ran died of a signal,
      # and cargo stopped the build at that crate: the artifact it was producing
      # never appeared, so the step that needed it never ran. The wording says
      # "a compiler subprocess" rather than "the linker" because the driver's
      # `unable to execute command: <signal>` line covers a frontend crash too,
      # and naming the wrong tool sends the author looking in the wrong place. Whatever passed before
      # that point stands — run 33041791988 had already cleared lint — which is
      # why this says "did not complete" and not "nothing ran". Worded like the
      # other kinds that reached no verdict, because the generic "checks
      # failed" sends the author into a log several thousand lines long to
      # look for a defect in a diff nothing judged (#13614, and #12813 before
      # it).
      #
      # Hedged rather than asserted, like corrupt-artifact: a crash can be the
      # branch's own doing — a build script it changes, a dependency it adds
      # whose objects the linker cannot digest — and this cannot tell. A
      # recurrence on this branch alone, or on a crate whose build this branch
      # changes, is worth suspecting the diff for.
      #
      # Kept to the register of the sibling arms — cause first, then "checks
      # did not complete, re-dispatch" — so the verdict fits the cap with the
      # longest login GitHub issues and a six-digit elapsed, and the suite
      # holds every arm to that (assert_describe_fits).
      SIGNOFF_FAILURE_STATUS_DESC="$(failure_status_desc "Compiler subprocess crashed after ${elapsed}s — checks did not complete, re-dispatch" "$user")"
      SIGNOFF_FAILURE_SUMMARY="### Sign-off"$'\n'"**Infrastructure failure** after ${elapsed}s — the compiler driver reported that a subprocess it ran died of a signal (a crash or an out-of-memory kill, not a diagnostic) — the linker on every run seen so far, though the driver words a frontend crash the same way — and cargo stopped the build at that crate, so **the checks did not complete**: the binary being linked was never produced and nothing after it ran, while whatever passed before it stands. That is the runner's toolchain failing on its own, not a statement about the branch. Re-dispatch the sign-off. If it recurs on this branch alone, or names a crate whose build this branch changes, the diff is worth suspecting."$'\n'
      SIGNOFF_FAILURE_MESSAGE="sign-off aborted: a compiler subprocess crashed on the runner, so the build did not finish (the checks did not complete) — re-dispatch"
      ;;
    missing-target)
      # Neither of the two readings above: the runner is fine and the code was
      # never judged. Distinguishing that here is the point — a verdict worded
      # like a lint denial sends the author to read a 14k-line log to discover
      # that nothing was wrong with the diff (#12813). The remedy belongs in the
      # description itself, which is all most readers see.
      SIGNOFF_FAILURE_STATUS_DESC="$(failure_status_desc "Gate make target missing after ${elapsed}s — checks did not run, merge ${LINT_BASE_BRANCH} in" "$user")"
      SIGNOFF_FAILURE_SUMMARY="### Sign-off"$'\n'"**Could not run** after ${elapsed}s — this branch's \`Makefile\` has no rule for a target the gate invokes, so **the checks did not run and the branch was not evaluated**. Nothing here is a statement about the code. Merge \`${LINT_BASE_BRANCH}\` into the branch and sign off again."$'\n'
      SIGNOFF_FAILURE_MESSAGE="sign-off could not run: this branch's Makefile has no rule for a target the gate invokes (the checks did not run) — merge ${LINT_BASE_BRANCH} in and sign off again"
      ;;
    stale-lockfile)
      # Same shape as missing-target: the runner is fine, the code was never
      # judged, and the remedy is one command. Without its own case this reads as
      # "Sign-off checks failed", which sends the author looking for a lint denial
      # in a log that contains no compilation at all.
      #
      # "stale" covers both readings the preflight returns this kind for: an
      # absent Cargo.lock is a `--locked` violation in cargo's own terms, not an
      # absence of one, and the two share a remedy. Both halves of that remedy
      # are in the status — regenerating the lockfile is not enough on its own.
      SIGNOFF_FAILURE_STATUS_DESC="$(failure_status_desc "Cargo.lock stale after ${elapsed}s — checks not run; cargo update --workspace, commit" "$user")"
      SIGNOFF_FAILURE_SUMMARY="### Sign-off"$'\n'"**Could not run** after ${elapsed}s — \`Cargo.lock\` is missing, or cargo would have to rewrite it to build this branch, so **the checks did not run and the branch was not evaluated**. Nothing here is a statement about the code. Run \`cargo update --workspace\` on the branch, commit the regenerated \`Cargo.lock\`, and sign off again."$'\n'
      SIGNOFF_FAILURE_MESSAGE="sign-off could not run: Cargo.lock is missing or does not match the workspace manifests (the checks did not run) — run 'cargo update --workspace', commit it, then sign off again"
      ;;
    rewritten-lockfile)
      # The inverse of every case above: the checks *did* run, and they passed.
      # What is refused is the attestation, because cargo brought Cargo.lock up to
      # date while they ran, so the tree they passed on is not the tree the commit
      # describes. Saying "the checks did not run" here — which sharing
      # stale-lockfile's status would do — sends the author to look for a lint
      # denial in a log full of green, and understates the remedy: there is
      # nothing in the diff to fix, only a regenerated lockfile to commit.
      SIGNOFF_FAILURE_STATUS_DESC="$(failure_status_desc "Checks passed in ${elapsed}s but rewrote Cargo.lock — commit the regenerated Cargo.lock" "$user")"
      SIGNOFF_FAILURE_SUMMARY="### Sign-off"$'\n'"**Cannot attest** after ${elapsed}s — **the checks ran and passed**, but cargo brought \`Cargo.lock\` up to date while they ran, so the committed lockfile does not describe the tree they passed on and the merge queue would reject it. Nothing here is a statement about the code, and there is nothing in the diff to fix. Commit the regenerated \`Cargo.lock\` and sign off again."$'\n'
      SIGNOFF_FAILURE_MESSAGE="sign-off cannot attest this branch: the checks passed, but they rewrote Cargo.lock — commit the regenerated Cargo.lock and sign off again"
      ;;
    *)
      SIGNOFF_FAILURE_STATUS_DESC="$(failure_status_desc "Sign-off checks failed after ${elapsed}s" "$user")"
      SIGNOFF_FAILURE_SUMMARY="### Sign-off"$'\n'"**Failed** after ${elapsed}s."$'\n'
      SIGNOFF_FAILURE_MESSAGE="sign-off checks failed"
      ;;
  esac
}

# The make targets run_checks invokes on every run that gets past the
# Rust-changes skip. Kept beside the preflight that reads it: a target added to
# run_checks and not to this list reopens exactly the failure the preflight
# exists to catch.
#
# `nextest-packages` is deliberately absent — it is the one target run_checks
# invokes conditionally, so it lives in signoff_make_targets below.
readonly SIGNOFF_MAKE_TARGETS=(lint-rust nextest verify-cli)

# The targets *this* invocation will actually reach.
#
# Requiring a target the run will not invoke refuses a branch that could have
# completed every step selected for it. `nextest-packages` runs only inside
# run_targeted_tests, which this invocation reaches only when targeted work is
# enabled — and remote sign-off disables it by default
# (SIGNOFF_SKIP_TARGETED_{LINT,TESTS} in .github/workflows/signoff.yml), so on
# the default remote run that target is never invoked at all.
#
# Errs toward asking: targeted tests can still end up skipped after this point
# when no changed workspace package is found, and the probe costs ten
# milliseconds. Over-probing a target the branch has costs nothing; the
# direction that matters is never *under*-probing one the run will invoke.
signoff_make_targets() {
  printf '%s\n' "${SIGNOFF_MAKE_TARGETS[@]}"
  if [[ -z "${SIGNOFF_SKIP_TARGETED_LINT:-}" && -z "${SIGNOFF_SKIP_TARGETED_TESTS:-}" ]]; then
    printf '%s\n' nextest-packages
  fi
}

# True when `make` can resolve TARGET in this branch's Makefile.
#
# `make -n` rather than a grep for `^target:`: a target can arrive through the
# `-include Makefile.local` the root Makefile already has, and make's own answer
# covers that. `-n` prints recipes instead of running them, and nothing in this
# Makefile is `+`-prefixed or recursive, so the probe executes no build work —
# it costs about ten milliseconds per target.
#
# Answers only what it can answer honestly. The one positive signal is make's
# own "No rule to make target" for the single goal we asked for — which a
# checkout with no Makefile at all also produces, and rightly so, since the gate
# cannot run a single target there either.
#
# Anything else reports "present", so a reading we cannot trust never blocks a
# sign-off: a Makefile make cannot parse says `missing separator`, and a runner
# with no make at all says `command not found`. Both are real problems, but
# neither is this one, and the step that hits them reports them in its own
# words. That is the same direction free_disk_gib errs in, and for the same
# reason: refusing to evaluate a branch on the strength of a broken probe is
# worse than running checks that will report the problem themselves.
make_target_exists() {
  local target="$1" output
  # LC_ALL=C so a localized make cannot word the message out of recognition and
  # read as a target that is present.
  output=$(LC_ALL=C signoff_make -n "$target" 2>&1) && return 0

  # A missing *prerequisite* reports the same phrase, with a "needed by" clause
  # naming who wanted it — a different condition, since the target itself does
  # exist. Fall through to "present" there and let the real run report it in its
  # own words. With a single goal on the command line, a miss without that
  # clause can only be the goal we named.
  if [[ "$output" == *"No rule to make target"* && "$output" != *"needed by"* ]]; then
    return 1
  fi
  debug "make -n ${target} failed without naming a missing target — treating it as present"
  return 0
}

# Stop before the Rust checks when this branch's Makefile has no rule for a
# target *this invocation* will invoke — see signoff_make_targets for why the
# set is not fixed.
#
# `make lint-rust`/`nextest`/`verify-cli` run out of the *branch's* Makefile, so
# a branch based before a target was added builds the entire workspace and then
# dies on the last line — every test green, then `No rule to make target
# 'verify-cli'` and a `signoff=failure` that reddens Attestation (#12813). That
# cost a full pool slot, ~2.6h, to learn something a probe answers in
# milliseconds before anything is compiled.
#
# Fatal on local runs too, unlike the disk floor: a missing target is not a
# threshold someone may reasonably run under, it is a step that is certain to
# fail. Saying so now, naming the remedy, is strictly better than saying it
# after the build.
preflight_make_targets() {
  local target
  local -a missing=()

  while IFS= read -r target; do
    make_target_exists "$target" || missing+=("$target")
  done < <(signoff_make_targets)

  if (( ${#missing[@]} == 0 )); then
    debug "every sign-off make target resolves in this branch's Makefile"
    return 0
  fi

  local list="${missing[*]}"
  local remedy="Merge ${LINT_BASE_BRANCH} into the branch to pick the target up, then sign off again."
  info "${NO} This branch's Makefile has no rule for: ${list}"
  info "  The sign-off gate runs these targets out of the branch's own Makefile, so the run would"
  info "  build for hours and then die on the first missing one. The branch was not evaluated."
  info "  ${remedy}"
  if is_remote_run; then
    # The step summary is not shown on the run page when the step itself failed,
    # so the annotation is what an operator actually reads — same reasoning as
    # the disk preflight's.
    echo "::error title=Sign-off cannot run on this branch::This branch's Makefile has no rule for: ${list}. The branch was not evaluated. ${remedy}"
  fi
  append_step_summary "### Preflight: the branch cannot run the gate"$'\n'"This branch's \`Makefile\` has no rule for: \`${list}\`. The sign-off gate invokes these targets out of the branch's own \`Makefile\`, so **the checks did not run and the branch was not evaluated** — this is not a statement about the code. ${remedy}"$'\n'
  return "$EXIT_MAKE_TARGET_MISSING"
}

# Stop before the Rust checks when the work volume cannot hold them. Fatal only
# on a remote run — that shared pool is where this happens, and it is where a
# wasted run costs hours. A local run just warns: a developer's own disk is
# theirs to manage, and blocking their sign-off on a floor tuned for the pool
# would be wrong.
preflight_disk() {
  local free min="${SIGNOFF_MIN_FREE_GIB:-$DEFAULT_MIN_FREE_GIB}"

  if [[ ! "$min" =~ ^[0-9]+$ ]]; then
    info "warning: SIGNOFF_MIN_FREE_GIB='${min}' is not an integer — using ${DEFAULT_MIN_FREE_GIB}"
    min="$DEFAULT_MIN_FREE_GIB"
  fi
  # Force base 10: bash arithmetic reads a leading zero as octal, so a
  # well-meaning `SIGNOFF_MIN_FREE_GIB=08` is an arithmetic error, not 8.
  min=$((10#$min))

  if ! free=$(free_disk_gib); then
    debug "could not measure free disk space — skipping the preflight check"
    return 0
  fi

  debug "free space on the work volume: ${free} GiB (floor ${min} GiB)"
  if (( free >= min )); then
    return 0
  fi

  if ! is_remote_run; then
    info "warning: only ${free} GiB free here and sign-off wants ${min} GiB — the build may die at the linker"
    return 0
  fi

  info "${NO} Only ${free} GiB free on the work volume; a sign-off needs ${min} GiB."
  info "  The branch was not evaluated. Reclaim space on this runner and re-dispatch."
  # An Actions annotation as well as the step summary. Reached from the standalone
  # `preflight-disk` step there is no commit status yet to carry the distinction —
  # the pending status is posted later, inside the sign-off run — so the run page
  # is the only place an operator can learn this was the volume and not the diff.
  echo "::error title=Runner out of disk::Only ${free} GiB free on the work volume, below the ${min} GiB floor. The branch was not evaluated: reclaim space on this runner and re-dispatch."
  append_step_summary "### Preflight: not enough disk"$'\n'"Only **${free} GiB** free on the runner work volume, below the **${min} GiB** floor, so the Rust checks did not run and **the branch was not evaluated**. This is an infrastructure failure, not a code failure: reclaim space on this runner (\`target/\` is shared across branches) and re-dispatch. Adjust the floor with \`SIGNOFF_MIN_FREE_GIB\`."$'\n'
  return "$EXIT_DISK_EXHAUSTED"
}

# Stop before the Rust checks when Cargo.lock does not describe the manifests —
# including when it is not there at all.
#
# `pr.yml` asks this question twice now: once early in `Build and Test` (cheap and
# named) and once at the bottom of that job as a backstop. Neither runs on a pull
# request, though — there `Attestation` is the only job — so the merge queue is
# where a stale lockfile is first seen, and the queue is also where this shape is
# born: one PR changes a manifest version while another adds or renames a member,
# git merges both cleanly because they touch different regions, and nothing
# regenerates the lock for the combination. On 2026-08-26 that ejected 13 queue
# branches, each after the better part of an hour (#13598).
#
# The sign-off gate is therefore the first place the *author* can be told, and
# asking cargo to resolve without permission to rewrite the lock answers it in
# seconds.
#
# `--locked` rather than a hand-rolled version comparison, because the comparison
# is cargo's resolution: members inherit versions from `[workspace.package]`,
# dependencies resolve through `[patch]` tables, and reimplementing that would be
# a second resolver to keep in step with the first. It also means a *missing*
# lockfile is covered without a special case — cargo calls that a `--locked`
# violation too, in the same words ("cannot create the lock file … because
# --locked was passed"), which matters because the pr.yml backstop cannot see one:
# `git diff` ignores untracked files, so a branch that deletes Cargo.lock and lets
# the first cargo command recreate it would otherwise pass everything.
#
# Fatal on local runs too, for preflight_make_targets' reason: this is not a
# threshold someone may reasonably run under, it is a step certain to fail later.
preflight_lockfile() {
  local out rc=0

  # No manifest here means nothing to resolve. Not keyed on Cargo.lock: its
  # absence is the condition above, not an exemption from it. Running from a
  # member directory is fine — cargo walks up to the workspace root and reads the
  # root lockfile, so this asks the same question wherever it is invoked.
  [[ -f Cargo.toml ]] || { debug "no Cargo.toml here — nothing to check"; return 0; }

  if ! command -v cargo >/dev/null 2>&1; then
    info "cargo not found — skipping the Cargo.lock check"
    return 0
  fi

  # Captured with `|| rc=$?` rather than read from $? on the next line: this
  # script runs under `set -e`, and a bare failing assignment would abort the
  # run on cargo's status before the guard could decide what it meant.
  # `--color never` so escape sequences cannot land inside the phrase matched
  # below.
  out="$(cargo metadata --locked --color never --format-version 1 2>&1 >/dev/null)" || rc=$?
  if (( rc == 0 )); then
    debug "Cargo.lock still describes the workspace manifests"
    return 0
  fi

  # Only cargo's own refusal to write the lock is a verdict about the branch.
  # Every other failure — an unreachable registry, a manifest cargo cannot read
  # at all, a missing rustc — is either infrastructure or something the gate
  # itself reports with far better context a few minutes later, and calling it a
  # lockfile problem here would send the reader to the wrong fix.
  #
  # The wording has changed across cargo releases, and differs between the stale
  # and missing cases ("cannot update the lock file … because --locked was
  # passed", "cannot create the lock file … because --locked was passed", "the
  # lock file … needs to be updated but --locked was passed"); all of them name
  # the flag, so match on that rather than on a whole phrase. If it changes again
  # this guard stops guarding rather than misfiring — and
  # scripts/test_signoff_disk_guard.sh drives the *installed* cargo against real
  # stale and missing fixtures, so drift surfaces as a failing test instead of as
  # a check that quietly stopped working.
  if [[ "$out" != *"--locked was passed"* ]]; then
    info "warning: could not check whether Cargo.lock is current (cargo metadata exited ${rc} for another reason) — skipping that check"
    debug "cargo metadata --locked said: ${out}"
    return 0
  fi

  # Caller-neutral wording on purpose: this function now runs from two places
  # with different stakes — the sign-off gate, where it decides whether a branch
  # is evaluated at all, and pr.yml's `Build and Test`, where it is the first step
  # of a merge-queue build. Saying "the branch was not evaluated" or "sign off
  # again" would be false in one of them. The sign-off-specific framing lives
  # where it belongs, in describe_check_failure's `stale-lockfile` case.
  #
  # Not "run any cargo command" either: `cargo fmt` and `cargo --version` resolve
  # nothing, and anything run under `--locked` is refused for this very reason.
  # Name one that regenerates the lockfile.
  local remedy="Run 'cargo update --workspace', commit the regenerated Cargo.lock, and push."
  info "${NO} Cargo.lock does not describe the workspace manifests. Cargo says:"
  printf '%s\n' "$out" | bullet "    " >&2
  info "  Cargo has to write the lockfile before anything here can build, so every job that"
  info "  checks it fails — in the merge queue, only after the whole suite has run."
  info "  ${remedy}"
  if is_remote_run || in_actions; then
    # Same reasoning as the other two preflights': a failed step does not show
    # its summary on the run page, so the annotation is what an operator reads.
    echo "::error title=Cargo.lock does not match the manifests::Cargo has to write Cargo.lock before this branch can build. ${remedy}"
  fi
  append_step_summary "### Cargo.lock does not match the manifests"$'\n'"Cargo has to write \`Cargo.lock\` before this branch can build — it is missing, or it no longer describes these manifests. Nothing here is a statement about the code. ${remedy}"$'\n'
  return "$EXIT_LOCKFILE_STALE"
}

# What `git` says about Cargo.lock right now, or the empty string when git cannot
# answer (a JJ workspace, no repository, no git). `--untracked-files=all` because
# the state a reader most needs named is one `git diff` cannot see: a lockfile
# deleted in the commit and recreated by cargo is *untracked*, not modified.
#
# Diagnostic only. postcheck_lockfile decides on a lockfile_fingerprint, so an
# empty answer here costs the operator a sentence, not the guard its verdict.
lockfile_status() {
  # Asked of git directly rather than through $VCS: this runs before detect_vcs on
  # some paths, and an uninitialised $VCS would answer "no lockfile news" for a tree
  # that has some. A colocated JJ workspace has a .git and is answered correctly; a
  # non-colocated one has none and skips.
  command -v git >/dev/null 2>&1 || return 0
  git rev-parse --git-dir >/dev/null 2>&1 || return 0
  git status --porcelain --untracked-files=all -- Cargo.lock 2>/dev/null || true
}

# What Cargo.lock *is* right now: `absent`, or a digest of its bytes. Read off the
# filesystem rather than out of `git status`, for two reasons the post-check below
# depends on:
#
#   - Git cannot always answer. In a non-colocated JJ workspace there is no `.git`,
#     so lockfile_status is empty both before and after the checks, and comparing
#     two empty strings retires the guard silently in exactly the setup that has no
#     other backstop.
#   - Porcelain state is coarser than content. Under `scripts/signoff -f` a tree
#     already carrying lockfile edits reads ` M Cargo.lock`, and it still reads
#     ` M Cargo.lock` after cargo has rewritten it further — the same string for two
#     different files. A digest separates "the run inherited this edit" from "the
#     run made another one", which is the distinction the post-check is for.
lockfile_fingerprint() {
  [[ -f Cargo.lock ]] || { printf 'absent\n'; return 0; }

  local digest=""
  if command -v shasum >/dev/null 2>&1; then
    digest="$(shasum -a 256 Cargo.lock 2>/dev/null | awk 'NR==1{print $1}')"
  fi
  if [[ -z "$digest" ]] && command -v sha256sum >/dev/null 2>&1; then
    digest="$(sha256sum Cargo.lock 2>/dev/null | awk 'NR==1{print $1}')"
  fi
  if [[ -z "$digest" ]]; then
    # POSIX, so this is the floor rather than another maybe. CRC and size both, to
    # keep it a content check and not a length check.
    digest="$(cksum Cargo.lock 2>/dev/null | awk 'NR==1{print $1 "-" $2}')"
  fi

  # Never answer with the empty string. Two of those compare equal, so an empty
  # answer does not degrade the guard, it retires it — the same failure mode as
  # the git-less case above. Size alone is weaker, and says so.
  printf '%s\n' "${digest:-size-$(wc -c <Cargo.lock 2>/dev/null | tr -d ' ')}"
}

# Refuse a sign-off whose own checks rewrote Cargo.lock.
#
# preflight_lockfile fails open on a cargo error it does not recognise — an
# unreachable registry, or a reworded `--locked` diagnostic after a toolchain bump
# — because reporting infrastructure as a stale lockfile sends the reader to the
# wrong fix. But failing open means the gate then runs `lint-rust` and `nextest`,
# which invoke cargo *without* `--locked`, and cargo will quietly bring the
# lockfile up to date on its way past. Without this the run would pass and post
# `signoff=success` for a HEAD whose committed lockfile does not describe it, and
# the merge queue would be the first to notice — which is the whole failure this
# change exists to move earlier.
#
# Compared against a snapshot taken before the checks rather than against "clean",
# so `scripts/signoff -f` on a tree that was already carrying lockfile edits is
# judged on what *this run* changed. The snapshot is a lockfile_fingerprint, not a
# `git status` line — see that function for why the porcelain state cannot carry
# this comparison.
postcheck_lockfile() {
  local before="$1" after
  after="$(lockfile_fingerprint)"
  [[ "$after" != "$before" ]] || return 0

  # Git for the diagnostic only, never for the verdict: it names the state a reader
  # can go look at, and it is allowed to have nothing to say.
  local git_state
  git_state="$(lockfile_status)"
  local remedy="Commit the regenerated Cargo.lock and sign off again."
  info "${NO} The checks rewrote Cargo.lock${git_state:+ (git status: ${git_state})}."
  info "  Cargo brought the lockfile up to date while the gate ran, so the committed one does not"
  info "  describe the tree these checks passed on, and the merge queue would reject it."
  info "  ${remedy}"
  if is_remote_run || in_actions; then
    echo "::error title=Sign-off cannot attest this branch::The checks rewrote Cargo.lock, so the committed lockfile does not describe the tree they passed on. ${remedy}"
  fi
  append_step_summary "### Cargo.lock was rewritten by the checks"$'\n'"Cargo brought \`Cargo.lock\` up to date while the gate ran, so the committed one does not describe the tree these checks passed on and **the merge queue would reject it**. ${remedy}"$'\n'
  # Not EXIT_LOCKFILE_STALE: these checks completed and passed. See that constant.
  return "$EXIT_LOCKFILE_REWRITTEN"
}

# Unit tests for the packages a branch touched, run before the full workspace
# lint. A broken test in the crate you just edited is the likeliest failure, and
# it would otherwise surface only after the longest step in the gate.
# Bin-only packages are dropped (see packages_with_lib_targets); everything the
# targeted run skips is still covered by the full `nextest` run later.
run_targeted_tests() {
  local packages="$1"
  local features="${2:-}"
  local test_packages

  if [[ -n "${SIGNOFF_SKIP_TARGETED_TESTS:-}" ]]; then
    info "SIGNOFF_SKIP_TARGETED_TESTS set — skipping targeted unit tests"
    return 0
  fi

  test_packages=$(packages_with_lib_targets "$packages" || true)
  if ! has_content "$test_packages"; then
    debug "no changed packages with a library target — skipping targeted unit tests"
    append_step_summary "### Targeted unit tests"$'\n'"Skipped (no changed packages with a library target)."$'\n'
    return 0
  fi

  # The features were resolved for the full changed set, which can name crates
  # dropped just above. Naming a feature for a package outside the `-p`
  # selection is a hard cargo error ("the package 'x' does not contain this
  # feature: y/z"), so a branch touching a library crate and a bin-only one
  # (runtime + testoperator) would fail the run outright.
  features=$(features_for_packages "$features" "$test_packages")

  info "Targeted unit tests for changed packages: ${test_packages}"
  info "  (make nextest-packages PACKAGES=\"${test_packages}\")"
  append_step_summary "### Targeted unit tests"$'\n'"Packages: \`${test_packages}\`"$'\n'
  # Explicit `|| return` so failures short-circuit even when the caller has
  # temporarily disabled `set -e` (see cmd_signoff).
  run_make_step nextest-packages PACKAGES="$test_packages" FEATURES="$features" || return $?
  info "Targeted unit tests passed."
}

# Run the same fast checks the old PR build ran: lint + build + unit tests.
# The heavier suite (release build, integration, e2e, ...) runs in the merge
# queue, so it deliberately isn't part of the local sign-off.
#
# Fail-fast order:
#   0. Skip all Rust work when the branch has no Rust-affecting files vs trunk
#   0b. Refuse a branch whose Makefile has no rule for a target the gate invokes
#   1. Targeted lint on packages touched by the branch (fast feedback)
#   2. Targeted unit tests for those packages (fast feedback)
#   3. Full workspace lint (the real gate)
#   4. CLI build + unit tests
#
# Steps 1-2 cover the crate you actually edited before step 3, the longest step,
# so its likeliest failures surface in minutes instead of at the end. They build
# it with the features the workspace resolves for it, so they exercise the same
# code the gate will rather than a scoped-only configuration;
# SIGNOFF_SKIP_TARGETED_LINT and SIGNOFF_SKIP_TARGETED_TESTS opt out.
#
# Sets SIGNOFF_CHECK_SUMMARY (short phrase for the commit-status description).
# Output streams straight to the terminal — call this bare, never `$(run_checks)`,
# which would capture make's stdout.
run_checks() {
  local revision="${1:-}"
  local packages=""
  local features=""

  # Non-Rust-only changes (docs, YAML, scripts, …): still attest, but skip the
  # expensive lint/build/test gate. Unknown diffs fall through and run checks.
  if [[ -n "$revision" ]] && ! branch_has_rust_changes "$revision"; then
    info "No Rust-affecting files changed vs ${LINT_BASE_BRANCH} — skipping Rust lint, build, and unit tests"
    # Name the pattern rather than a subset of what it matches: the two drift apart
    # every time a path is added to the gate.
    append_step_summary "### Rust checks"$'\n'"Skipped (nothing in the branch diff vs \`${LINT_BASE_BRANCH}\` matches \`RUST_AFFECTING_PATH_PATTERN\` in \`scripts/signoff\`)."$'\n'
    SIGNOFF_CHECK_SUMMARY="no Rust changes (lint/test skipped)"
    return 0
  fi

  # The preflights all sit after the Rust-changes skip for the same reason: a
  # docs-only sign-off invokes no make target and compiles nothing, so neither a
  # full volume nor a Makefile predating one of them is a reason to refuse it.
  #
  # Targets first. It needs no disk, costs milliseconds, and answers a question
  # the disk floor cannot: whether this branch can run the gate at all.
  preflight_make_targets || return $?
  preflight_disk || return $?
  # Last of the three: it is the only one that costs a cargo resolution pass
  # (~10s warm), so the two that answer in milliseconds get to refuse first.
  preflight_lockfile || return $?
  # Snapshot the lockfile now, while the preflight has just vouched for it, so the
  # post-check below can tell what the checks changed from what the tree already
  # carried under a forced run.
  local lock_before
  lock_before="$(lockfile_fingerprint)"

  if [[ -z "${SIGNOFF_SKIP_TARGETED_LINT:-}" && -n "$revision" ]]; then
    packages=$(changed_workspace_packages "$revision" || true)
  fi

  if [[ -n "$packages" ]]; then
    # Build these crates the way the workspace builds them, not the way they
    # build alone — see workspace_features_for_packages. An empty result (no
    # python3, cargo metadata unavailable) falls back to package defaults, which
    # is the old behavior rather than a hard failure.
    features=$(workspace_features_for_packages "$packages" || true)
    info "Targeted pre-lint for changed packages: ${packages}"
    if [[ -n "$features" ]]; then
      info "  (workspace-resolved features: $(printf '%s' "$features" | tr ',' '\n' | wc -l | tr -d ' '))"
      debug "targeted features: ${features}"
    else
      info "  (no resolved features available — falling back to package defaults)"
    fi
    append_step_summary "### Targeted pre-lint"$'\n'"Packages: \`${packages}\`"$'\n'
    # FEATURES is set explicitly so a user-exported value cannot reintroduce a
    # workspace-only set. Explicit `|| return` so failures short-circuit even
    # when the caller has temporarily disabled `set -e` (see cmd_signoff).
    run_make_step lint-rust PACKAGES="$packages" FEATURES="$features" || return $?
    info "Targeted pre-lint passed."
    run_targeted_tests "$packages" "$features" || return $?
    info "Running full workspace lint…"
  else
    info "No changed workspace packages detected (or targeted lint skipped) — running full workspace lint…"
    append_step_summary "### Targeted pre-lint"$'\n'"Skipped (no changed workspace packages, or unavailable base/diff)."$'\n'
  fi

  info "Running Rust lint (make lint-rust)…"
  # Clear PACKAGES/FEATURES so a user-exported env cannot scope or re-feature
  # the full gate; empty values leave the Makefile on its workspace defaults.
  run_make_step lint-rust PACKAGES= FEATURES= || return $?

  # No separate CLI build: `nextest`'s build already emits the `spice`
  # binary, because cargo builds a package's bins alongside that package's
  # integration tests. A `cargo build -p spice` on top of that only re-resolved
  # the graph at a selection no other phase shares, to relink a binary that was
  # already there. `verify-cli` asserts it exists and runs, so the day cargo stops
  # producing it the gate says so instead of quietly dropping CLI coverage.
  # The merge queue's required `Build (release profile)` job builds the CLI,
  # spiced, and the release install for real, so release-only breakage — and the
  # `-p spice` resolution this no longer exercises — is still caught before trunk.
  info "Running unit tests and verifying the CLI (make nextest verify-cli)…"
  # Lighter Cayenne fuzz/race depth for the PR gate (see
  # crates/cayenne/tests/mutation_property_test.rs and common::env_scale); both
  # knobs default to 1.0 (full depth) when unset, so this only affects this gate.
  CAYENNE_PROPTEST_SCALE=0.25 CAYENNE_PROPTEST_OPS_SCALE=0.25 \
    run_make_step nextest verify-cli || return $?

  # The other half of the preflight: it fails open on a cargo error it cannot
  # read, and the make steps above run cargo unlocked, so this is what stops a
  # rewritten lockfile from being attested as if it were the committed one.
  postcheck_lockfile "$lock_before" || return $?

  SIGNOFF_CHECK_SUMMARY="lint+test passed"
}

# The PR's `Attestation` job (pr.yml) only re-reads the `signoff` commit status
# when its workflow run executes: pr.yml triggers on `pull_request`,
# `merge_group` and `workflow_dispatch`, never on a status change. So a run that
# already completed keeps whatever verdict it reached, however the status has
# moved since. Re-run that job instead of making the developer open or refresh
# the PR by hand. `gh` is already required by require_tools() before cmd_signoff
# can reach this point, but the check stays here so this function remains
# correct if it's ever called on its own.
#
# A run that concluded `success` needs no refresh when this sign-off also
# succeeded — but it needs one precisely when the sign-off failed, or the gate
# keeps reporting an attestation this run just overturned. Pass a non-empty
# third argument to force the re-run past that short-circuit.
refresh_attestation_check() {
  local sha="$1" repo="$2" force="${3:-}"
  # pr.yml runs on `pull_request`/`merge_group`/`workflow_dispatch`, so viewing
  # the PR page does not start one — say what actually re-reads the status.
  local fallback="Re-run the PR's 'Attestation' check from the Checks tab once it has reported — reloading the PR page does not re-read the sign-off status."
  local run run_id run_status run_conclusion pr_heads head heads_short=""
  local -a head_list=()

  if ! command -v gh >/dev/null 2>&1; then
    info "  Install the GitHub CLI (https://cli.github.com) so signoff can auto-refresh the 'Attestation' check."
    info "  ${fallback}"
    return 0
  fi

  # Only refresh while $sha is still a PR head. A remote sign-off can run for
  # hours (the job budget is 358 minutes), so the branch may have advanced
  # underneath it — and re-running the *stale* commit's pr.yml run then cancels
  # the current head's in-flight one: pr.yml's concurrency group is
  # `pr-<ref_name>-<ref_name == 'trunk' && sha || 'any-sha'>`, and on a
  # pull_request event ref_name is `<number>/merge` while the SHA term collapses
  # to the literal `any-sha`, so every attempt for a PR shares one group whatever
  # its commit. The re-run also keeps its original event payload, so the verdict
  # it publishes is computed for the stale commit.
  #
  # Fixing it here rather than by making that group SHA-specific: the shared group
  # is deliberate — it is what lets a new push cancel the run for the commit it
  # superseded. A stale sign-off has nothing to propagate anyway (its status sits
  # on a commit no longer under review), so skipping is the whole fix. See #12360.
  #
  # `gh --jq` (gh's built-in filter), not the jq binary: this path runs from
  # cmd_signoff, which requires gh but not jq.
  pr_heads=$(gh api "repos/${repo}/commits/${sha}/pulls" \
    --jq '[.[] | select(.state == "open") | .head.sha] | join(" ")' 2>/dev/null) || pr_heads=""
  # Empty means "no open PR yet" or "the lookup failed"; both fall through to the
  # original behaviour, since signing off before the PR exists is ordinary and a
  # blipped lookup is no reason to skip a refresh that would have worked. The
  # membership test is space-delimited so a short SHA cannot partially match.
  if [[ -n "$pr_heads" && " ${pr_heads} " != *" ${sha} "* ]]; then
    # "not the head of any open PR", not "no longer the head of its PR": a commit
    # can belong to several open PRs, so name every current head rather than
    # implying there is one. `read -ra` rather than an unquoted `for` so the split
    # cannot glob, regardless of what the API returned.
    read -ra head_list <<<"$pr_heads"
    for head in "${head_list[@]}"; do
      heads_short="${heads_short:+${heads_short}, }${head:0:12}"
    done
    info "  ${sha:0:12} is not the head of any open PR that contains it (PR heads: ${heads_short}) — not refreshing 'Attestation'."
    info "  Re-running this commit's check would cancel the current head's, and would report a verdict for the wrong commit."
    info "  Sign off on the current head instead."
    return 0
  fi

  run=$(gh run list --repo "$repo" --commit "$sha" --workflow pr.yml --event pull_request \
    --json databaseId,status,conclusion --jq 'first(.[]) | "\(.databaseId) \(.status) \(.conclusion)"' 2>/dev/null) \
    || { debug "could not list 'pr' workflow runs for ${sha} on ${repo}"; info "  ${fallback}"; return 0; }

  read -r run_id run_status run_conclusion <<<"$run"
  # A missing run renders as an empty string, but an empty `--jq` match can
  # also render as the literal word "null" for each field — check run_id
  # looks like a real numeric database id rather than trusting non-emptiness.
  if [[ ! "$run_id" =~ ^[0-9]+$ ]]; then
    debug "no 'pr' workflow run found yet for ${sha} — nothing to refresh"
    info "  ${fallback}"
    return 0
  fi
  if [[ "$run_status" != "completed" ]]; then
    # A run that is still going may already have read the status — the read is
    # the first thing its job does, and validating an inherited sign-off keeps
    # it busy long after. So "it will evaluate the sign-off once it finishes"
    # holds only when the status it is about to report is the one we want; on
    # the failure path an in-flight run can still land green on what it read
    # before this verdict existed, and there is nothing to re-run yet.
    if [[ -n "$force" ]]; then
      info "  The 'Attestation' check (run ${run_id}) is still ${run_status} and may have read the previous sign-off already."
      info "  Re-run it once it finishes if it lands green — this sign-off failed."
    else
      info "  The 'Attestation' check (run ${run_id}) is still ${run_status} — it will evaluate the sign-off once it finishes."
    fi
    return 0
  fi
  if [[ "$run_conclusion" == "success" && -z "$force" ]]; then
    debug "run ${run_id} already succeeded — nothing to refresh"
    return 0
  fi

  # Not `--failed`: that only reruns jobs with conclusion=failure and no-ops
  # on cancelled/skipped runs. Rerunning the whole run is fine here — on a
  # `pull_request` event, pr.yml executes nothing but the Attestation job.
  local outcome="it will turn green shortly"
  [[ -z "$force" ]] || outcome="it will pick up the failed sign-off"
  if gh run rerun "$run_id" --repo "$repo" >/dev/null 2>&1; then
    echo "  Re-ran the 'Attestation' check (run ${run_id}) — ${outcome}."
  else
    info "  Could not auto-refresh the 'Attestation' check — ${fallback}"
  fi
}

# Post this run's failing verdict, then make the gate reflect it.
#
# The raw `signoff` status is not itself a required check — `Attestation` is,
# and it only re-reads the status when its pr.yml run executes. A commit that
# was already attested therefore keeps a green `Attestation` after a later run
# overturns it, and the branch can still enter the merge queue on an attestation
# this run contradicted. The merge queue re-runs the full suite, so that cannot
# put broken code on trunk; it spends a queue slot learning what the sign-off
# already knew. Hence the forced refresh — the inverse of the success path,
# which is right to skip a run that already passed.
#
# When the post itself fails the commit still carries whatever it had before, so
# there is nothing new for a re-run to read: warn and leave the check alone. The
# caller aborts either way, with the more useful message.
# `description` rather than user+elapsed: the caller already decides what the
# failure was — an out-of-disk runner reads differently from a failing branch —
# and the commit status is all most readers see, so that wording has to reach
# them intact.
post_failure_status() {
  local repo="$1" sha="$2" description="$3"

  if ! post_commit_status "$repo" "$sha" failure "$description"; then
    info "warning: could not post the failed sign-off status — the 'Attestation' check still reflects the previous sign-off"
    return 0
  fi
  refresh_attestation_check "$sha" "$repo" force
}

cmd_signoff() {
  local force=false verify=true note=""
  while [[ $# -gt 0 ]]; do
    case "$1" in
      -f|--force)     force=true;  shift ;;
      --no-verify)    verify=false; shift ;;
      --note)
        [[ $# -ge 2 ]] || fail "--note needs a value"
        note="$2"; shift 2 ;;
      # The two targeted phases are one decision in practice — they are the
      # fail-fast pass, and skipping one while keeping the other rarely makes
      # sense. Setting both is also the only combination that means what it
      # says: SIGNOFF_SKIP_TARGETED_TESTS alone does skip only the tests, but
      # SIGNOFF_SKIP_TARGETED_LINT alone skips both, because package discovery
      # is gated on it and the tests phase has nothing to run against. This flag
      # asks for both explicitly rather than relying on that side effect.
      --skip-targeted)
        export SIGNOFF_SKIP_TARGETED_LINT=1 SIGNOFF_SKIP_TARGETED_TESTS=1
        shift ;;
      -h|--help)      cmd_help; exit 0 ;;
      *)              fail "unknown option: $1 (see: scripts/signoff --help)" ;;
    esac
  done

  require_tools

  local revision sha user repo description start via elapsed
  revision=$(current_revision "$force")
  $force || ensure_clean_and_pushed "$revision"
  sha=$(revision_sha "$revision") || fail "could not resolve ${revision}"
  # Remote workflow passes the human who dispatched the run (SIGNOFF_ACTOR).
  # Otherwise: `gh api user` needs a user-scoped token; under a CI GITHUB_TOKEN
  # it 403s and can echo the error body to stdout, so accept its result only if
  # it looks like a GitHub login. Then fall back to the CI actor (set in
  # Actions) or the VCS-configured name (which may contain spaces — fine for a
  # description).
  user="${SIGNOFF_ACTOR:-}"
  if [[ -z "$user" ]]; then
    user=$(gh api user --jq .login 2>/dev/null || true)
    if [[ ! "$user" =~ ^[A-Za-z0-9-]{1,39}$ ]]; then
      user="${GITHUB_ACTOR:-$(local_user_name 2>/dev/null || true)}"
    fi
  fi
  [[ -n "$user" ]] || user="unknown"
  repo=$(repo_slug)
  via=""
  is_remote_run && via=" via remote"

  if $verify; then
    local check_status=0
    # Default summary; run_checks overwrites on success (incl. Rust-skip path).
    SIGNOFF_CHECK_SUMMARY="lint+test passed"
    start=$(date +%s)
    if is_remote_run; then
      post_pending_status "$repo" "$sha" "$user"
      # Watch for out-of-disk and unusable-cache lines from here on, so a failure
      # can say whether the runner or the branch was at fault. Remote only: a
      # local run's output then stays byte-for-byte what it is today, and neither
      # signature belongs to a developer's own machine — the shared `target/` and
      # the pool's sccache endpoint are both pool-only. Arming cannot fail —
      # there is no file to create and so nothing to clean up on exit.
      SIGNOFF_DISK_WATCH=1
      # From here on there is a `pending` on the commit and a verdict to decide,
      # so a signal from here on has to be told apart from a failing recipe.
      # Armed after the post, so a signal arriving before there is anything to
      # publish still stops the script outright.
      watch_for_signals
    fi
    # Capture status without wrapping in `if`/`||` (those also disable set -e
    # for the LHS). run_checks uses explicit `|| return` so make failures still
    # short-circuit under the temporary `set +e` used for status capture.
    set +e
    run_checks "$revision"
    check_status=$?
    set -e
    # A recorded signal takes this branch even on status 0. `make` returning 0
    # says the commands that ran succeeded, not that all of them ran: a recipe
    # line that traps the cancellation and exits 0, or a sub-make that swallows
    # it, ends the checks early with nothing to distinguish the result from a
    # clean pass. Falling through would post `signoff=success` — a run that
    # judged nothing certifying the commit, which is the same mistake as #12710's
    # false `failure` and the more costly direction of it, since it clears a
    # branch to merge. The signalled case publishes no verdict either way, so
    # what stands is the `pending` this run posted on its way in.
    if [[ "$check_status" -ne 0 || -n "$SIGNOFF_SIGNALLED" ]]; then
      elapsed=$(( $(date +%s) - start ))
      describe_check_failure "$check_status" "$elapsed" "$user"
      # A completed failure invalidates prior success from either execution
      # path. Interrupted checks have no verdict and leave the status alone.
      if [[ -n "$SIGNOFF_FAILURE_STATUS_DESC" ]]; then
        post_failure_status "$repo" "$sha" "$SIGNOFF_FAILURE_STATUS_DESC"
      fi
      if is_remote_run; then
        append_step_summary "$SIGNOFF_FAILURE_SUMMARY"
      fi
      fail "$SIGNOFF_FAILURE_MESSAGE"
    fi
    elapsed=$(( $(date +%s) - start ))
    description="Signed off by ${user}${via} — ${SIGNOFF_CHECK_SUMMARY} in ${elapsed}s"
    [[ -n "$note" ]] && description+=" — ${note}"
  elif [[ -n "$note" ]]; then
    # The note says where the checks ran instead, e.g. scripts/signoff-batch.
    description="Signed off by ${user}${via} — ${note}"
  else
    description="Signed off by ${user}${via} (checks not verified locally)"
  fi

  post_commit_status "$repo" "$sha" success "$description" \
    || fail "failed to post the sign-off status (do you have write access to ${repo}?)"

  append_step_summary "### Sign-off"$'\n'"**Success** on \`${sha:0:12}\` — ${description}"$'\n'

  echo "${OK} Signed off on ${sha:0:12} — ${description}"
  refresh_attestation_check "$sha" "$repo"
}

# Run the sign-off checks on HEAD and report the verdict, but post no status.
# HEAD need not be pushed: scripts/signoff-batch runs this on a local merge of
# several PRs, and then attests each PR head itself.
cmd_verify() {
  while [[ $# -gt 0 ]]; do
    case "$1" in
      --skip-targeted)
        export SIGNOFF_SKIP_TARGETED_LINT=1 SIGNOFF_SKIP_TARGETED_TESTS=1
        shift ;;
      -h|--help)      cmd_help; exit 0 ;;
      *)              fail "unknown option: $1 (see: scripts/signoff --help)" ;;
    esac
  done
  is_remote_run && fail "verify posts no status, so it has no place in a remote sign-off run"

  detect_vcs
  local revision sha start elapsed check_status=0
  revision=$(current_revision true)
  sha=$(revision_sha "$revision") || fail "could not resolve ${revision}"
  SIGNOFF_CHECK_SUMMARY="lint+test passed"
  start=$(date +%s)
  # Same status capture as cmd_signoff: no `if`/`||`, so set -e stays on inside.
  set +e
  run_checks "$revision"
  check_status=$?
  set -e
  elapsed=$(( $(date +%s) - start ))
  if [[ "$check_status" -ne 0 || -n "$SIGNOFF_SIGNALLED" ]]; then
    describe_check_failure "$check_status" "$elapsed" "$(local_user_name || true)"
    fail "${SIGNOFF_FAILURE_MESSAGE} (no status posted)"
  fi
  echo "${OK} Verified ${sha:0:12} — ${SIGNOFF_CHECK_SUMMARY} in ${elapsed}s (no status posted)"
}

# Pick the current STATUS_CONTEXT state out of a combined-status payload. The
# combined endpoint collapses each context to its latest status, so the first
# matching entry is the current one. Prints "" when the context is unset.
# Every reader of the sign-off status goes through this so they cannot disagree
# about what "the current state" means (see cmd_correct_cancelled).
combined_status_state() {
  jq -r "first(.statuses[]? | select(.context==\"${STATUS_CONTEXT}\") | .state) // \"\"" <<<"${1}"
}

# Run the disk preflight on its own, for the workflow to call *before* the
# toolchain setup steps.
#
# The guard reached through `run_checks` sits behind Rust, Nextest, sccache,
# protoc, cc and spiceio setup, so a volume that was already below the floor
# spent all of that first, and a volume that filled during those steps produced
# an ordinary red job with none of the labelling (#12427). Running the same floor
# check as the first step after checkout stops the already-full case immediately
# and says why. It cannot catch a volume that fills mid-setup — that would need
# the setup actions to report it — so this narrows the gap rather than closing it.
#
# Same floor, same `SIGNOFF_MIN_FREE_GIB` override, same remote-only fatality as
# the in-run preflight, because it is the same function.
cmd_preflight_disk() {
  preflight_disk
}

# The lockfile preflight as a subcommand, so pr.yml can run the same code the
# sign-off gate runs instead of carrying a second copy of it in YAML. Two copies
# of a guard drift, and the one that drifts is the one nobody notices has stopped
# guarding. Called from the Build and Test job right after the toolchain setup —
# see .github/workflows/pr.yml.
cmd_preflight_lockfile() {
  preflight_lockfile
}

cmd_status() {
  require_tools
  require_jq
  local revision sha repo combined state desc
  revision=$(current_revision)
  sha=$(revision_sha "$revision")
  repo=$(repo_slug)
  # Fetch the combined status once, then pick the first matching entry with jq.
  # (Piping `gh --jq ... | head -n1` would SIGPIPE the writer under pipefail.)
  # Fail on a real API error rather than falling back to {} → "not signed off".
  combined=$(gh api "repos/${repo}/commits/${sha}/status") \
    || fail "failed to read commit status for ${sha} on ${repo} (auth/rate-limit/network?)"
  state=$(combined_status_state "$combined")
  if [[ "$state" == "success" ]]; then
    desc=$(jq -r "first(.statuses[]? | select(.context==\"${STATUS_CONTEXT}\") | .description) // \"\"" <<<"$combined")
    echo "${OK} ${sha:0:12} is signed off — ${desc}"
  else
    echo "${NO} ${sha:0:12} is not signed off — run: make signoff"
    exit 1
  fi
}

# How long cmd_correct_cancelled waits for a dying run's last status post to
# land before reading the commit as settled.
#
# The `if: cancelled()` step that calls it starts as soon as the `Sign off` step
# is marked cancelled, which is not the same moment that step's process stops
# writing: on run 31144830314 the handler read `pending` at 05:16:20Z and the
# `failure` it existed to withdraw was posted at 05:16:24Z, four seconds later
# (#12710). Reading once therefore samples a commit still being written to.
#
# ~15s covers that margin with room to spare and costs nothing anyone waits on —
# the job is already cancelled and this step is the last thing in it. It is not
# a correctness boundary in either direction: overshooting the window leaves the
# same false `failure` as reading once does, and the run that wrote it is gone,
# so no wait can be long enough to be *required*.
#
# Overridable from the environment so the unit tests can exercise the polling
# without spending the window on every case that never reaches it.
readonly DEFAULT_CANCELLED_SETTLE_ATTEMPTS=5
readonly DEFAULT_CANCELLED_SETTLE_SLEEP_SECONDS=3

# One of the two settle knobs, as a base-10 integer: $1 the environment variable
# to read, $2 the default to fall back to when it is unset or unusable.
#
# Validated for the same reason preflight_disk validates its floor, and it
# matters more here: an unvalidated value reaches an arithmetic context, where a
# non-integer is a `set -e` abort — and aborting in *this* command would leave
# the false `failure` it exists to withdraw standing on the commit. A bad value
# falls back rather than failing.
settle_knob() {
  local name="$1" fallback="$2" value="${!1:-$2}"
  if [[ ! "$value" =~ ^[0-9]+$ ]]; then
    info "warning: ${name}='${value}' is not an integer — using ${fallback}"
    value="$fallback"
  fi
  # Force base 10: bash arithmetic reads a leading zero as octal, so a
  # well-meaning `05` is an arithmetic error rather than 5.
  printf '%s\n' "$((10#$value))"
}

# The STATUS_CONTEXT state on a commit, once a dying run has had a chance to
# finish writing it. Prints the state ("" when the context is unset) and returns
# 0; returns non-zero only when the status could not be read at all, which every
# caller must keep distinct from "unset" — see cmd_correct_cancelled.
#
# Only `pending` is waited on. It is the state a run posts on its way in and so
# the one a late verdict overwrites; `failure`/`error` is already the verdict
# being withdrawn, a `success` is settled and must not be second-guessed, and an
# unset context means no run got as far as posting anything. Returning
# immediately on all three keeps the wait off every path that cannot benefit
# from it.
settled_signoff_state() {
  local repo="$1" sha="$2" combined state attempt attempts sleep_seconds
  attempts=$(settle_knob CANCELLED_SETTLE_ATTEMPTS "$DEFAULT_CANCELLED_SETTLE_ATTEMPTS")
  sleep_seconds=$(settle_knob CANCELLED_SETTLE_SLEEP_SECONDS "$DEFAULT_CANCELLED_SETTLE_SLEEP_SECONDS")
  # Zero attempts would read nothing at all and report the commit as unset,
  # which is the one answer that is never true — the loop must run at least once.
  (( attempts >= 1 )) || attempts=1

  for (( attempt = 1; attempt <= attempts; attempt++ )); do
    combined=$(gh api "repos/${repo}/commits/${sha}/status" 2>/dev/null) || return 1
    state=$(combined_status_state "$combined" 2>/dev/null) || state=""
    [[ "$state" == "pending" ]] || { printf '%s\n' "$state"; return 0; }
    (( attempt < attempts )) || break
    sleep "$sleep_seconds"
  done

  # Still `pending` after the wait: either the run reached no verdict and
  # declined to publish one — which is what a cancelled run is now supposed to
  # leave behind (#12710) — or it died before it could. Both are `pending`, and
  # `pending` is the state this command would write anyway.
  printf '%s\n' "$state"
  return 0
}

# Repair the sign-off status a *cancelled* Remote Sign-off run left behind.
#
# Usage: cmd_correct_cancelled [<sha>] [<owner/repo>]
# Both default from the environment: the SHA from HEAD (what the cancelled run had
# checked out, and so what it posted against), the repo from GITHUB_REPOSITORY —
# authoritative inside Actions — falling back to the gh context for local use.
#
# A cancelled job is killed by signal, so `run_checks` returns non-zero under its
# `set +e` and the script posts `signoff=failure` — "checks failed" about a branch
# nothing actually judged. Attestation then reports a code failure that never
# happened (#12424). `cancel-in-progress` makes that routine: every re-dispatch for
# a branch cancels the one before it.
#
# But cancellation does not always mean that, so this must not write blindly
# (#12428). Two ways a cancelled run can find a *legitimate* `success` on the SHA:
#
#   1. Its own `Sign off` step completed and posted success, and the cancel signal
#      landed in the window before this correction runs.
#   2. Another run signed the same commit off. `concurrency: signoff-<pr|branch>`
#      keys on the dispatch input, so a `-f branch=x` run and a `-f pr_number=N`
#      run for that same branch are in *different* groups: they do not cancel each
#      other, and either can be cancelled after the other has succeeded.
#
# Overwriting either one throws away checks that genuinely passed and pushes the
# branch back through a 1-4 hour re-dispatch. So: rewrite `failure`/`error` — the
# only states a dying run posts — and leave everything else exactly as found.
#
# Best-effort by construction. This runs while a cancelled job is being torn down,
# where the API may be unreachable and the exit status is not worth anything: it
# must never mask the cancellation itself, so every path exits 0.
cmd_correct_cancelled() {
  local sha="${1:-}" repo="${2:-${GITHUB_REPOSITORY:-}}" state

  # `|| true` on each fallback: a resolver that fails leaves the value empty, and
  # the emptiness check below is what reports it. Splitting those into separate
  # failure branches just duplicates the message.
  [[ -n "$sha" ]] || sha=$(git rev-parse HEAD 2>/dev/null) || true
  [[ -n "$sha" ]] || { info "no SHA given and HEAD is unreadable — nothing to correct."; return 0; }

  command -v gh >/dev/null 2>&1 || { info "gh unavailable — leaving the ${STATUS_CONTEXT} status on ${sha} alone."; return 0; }
  command -v jq >/dev/null 2>&1 || { info "jq unavailable — leaving the ${STATUS_CONTEXT} status on ${sha} alone."; return 0; }

  [[ -n "$repo" ]] || repo=$(repo_slug 2>/dev/null) || true
  [[ -n "$repo" ]] || { info "could not resolve the repo — leaving the ${STATUS_CONTEXT} status on ${sha} alone."; return 0; }

  # A read failure must not be treated as "unset" — that would license a write over
  # a status we simply could not see, which is the bug this command exists to fix.
  if ! state=$(settled_signoff_state "$repo" "$sha"); then
    info "could not read the ${STATUS_CONTEXT} status on ${sha} — leaving it alone."
    return 0
  fi

  case "$state" in
    failure | error)
      # `pending` rather than `error`: pr.yml rejects failure/error but treats
      # pending as "not signed off yet", which is exactly the state a cancelled
      # run leaves behind. Attestation stays red — HEAD really is not signed off —
      # but points at re-running sign-off instead of at a phantom defect.
      if post_commit_status "$repo" "$sha" pending \
        "Remote sign-off was cancelled (superseded or stopped) — no checks failed. HEAD is not signed off; re-dispatch." \
        2>/dev/null; then
        echo "${OK} Reset ${STATUS_CONTEXT}=${state} on ${sha:0:12} to pending — this run was cancelled, not failed."
      else
        info "could not reset the ${STATUS_CONTEXT} status on ${sha} — leaving it as ${state}."
      fi
      ;;
    *)
      echo "${STATUS_CONTEXT} on ${sha:0:12} is '${state:-unset}', not a failure this run posted — leaving it alone."
      ;;
  esac
  return 0
}

# Restate a left-behind `pending` sign-off status as a run that reached no verdict.
#
# A remote run posts `pending` before it starts the checks, so a run that never
# reaches a verdict — the job is terminated at its budget, the runner goes away —
# leaves that `pending` on the commit carrying its "in progress" wording, which
# is the one thing the run is not.
#
# The state stays `pending`; only the description changes. Nothing judged the diff,
# so `failure` would assert what no check established — pr.yml reads it as a code
# failure, Attestation rejects it on the head commit (#12362), and a red `signoff`
# never self-clears, leaving the commit disqualified until someone re-dispatches by
# hand. `pending` is what this run's own signalled path already leaves standing (see
# `describe_check_failure`), and pr.yml does not reject it: a pending is not a
# verdict. Attestation then decides on its own terms — red for an ordinary head,
# which really is not signed off, and pointing at re-running sign-off rather than at
# a phantom defect; green only where pr.yml already allows it, on a fast-tracked head
# or a verified inheritance chain, which a dead run is no reason to block.
#
# `correct-cancelled` reaches the same end state from the other direction: it repairs
# a `failure`/`error` into `pending` and leaves an existing `pending` alone. Neither
# handler ever writes a verdict, because neither ending is evidence about the diff.
#
# A dormant `pending` stays distinguishable from a live one: `mine` takes its ⟳ from
# the in-flight run list, not from this status, and `status` reports any non-success
# as "not signed off". The description carries the rest.
#
# Only `pending` is rewritten. A run that finished has already posted its own
# success or failure, and overwriting that would discard the real verdict; the
# same guard makes this safe to run unconditionally at the end of a job.
#
# Read-then-write, and commit statuses have no compare-and-set, so a verdict
# posted in the gap between the two calls is overwritten. Nothing closes that
# gap — an ownership token in the status would still be read before the write —
# so keep it narrow instead: this is one API round trip, and the caller runs it
# once, at the end of a run that has already stopped working.
cmd_clear_pending() {
  local reason="${1:-Sign-off run ended before the checks completed — sign off again}"

  # In a remote run this is a cleanup handler, and a handler that cannot run has
  # learned nothing about the branch. `require_tools` would `fail` here, so on a
  # runner whose PATH has no `gh` the `Resolve an incomplete sign-off` step exits
  # 1 with "GitHub CLI (gh) not found" — a second red step on a job that already
  # died in setup, and the one message in the step list is about this handler
  # rather than about the host that is actually broken (#14234). `correct-cancelled`,
  # the other half of the pair that handles a run which reached no verdict, already
  # treats its own missing tooling that way; this is the same rule for the same
  # reason. Run by hand, the command still refuses: a person asking for the status
  # to be restated needs to be told it was not.
  if is_remote_run && ! command -v gh >/dev/null 2>&1; then
    info "gh unavailable on this runner — leaving the ${STATUS_CONTEXT} status alone."
    return 0
  fi
  require_tools

  local revision sha repo state
  revision=$(current_revision true)
  sha=$(revision_sha "$revision") || fail "could not resolve ${revision}"
  repo=$(repo_slug)
  state=$(signoff_state "$repo" "$sha") \
    || fail "failed to read commit status for ${sha} on ${repo} (auth/rate-limit/network?)"

  if [[ "$state" != "pending" ]]; then
    info "${STATUS_CONTEXT} on ${sha:0:12} is '${state}' — leaving it alone"
    return 0
  fi

  post_commit_status "$repo" "$sha" pending "$reason" \
    || fail "failed to post the sign-off status (do you have write access to ${repo}?)"
  append_step_summary "### Sign-off"$'\n'"**Incomplete** on \`${sha:0:12}\` — ${reason}"$'\n'
  echo "${NO} ${sha:0:12} — ${reason}"
}

# Truncate to at most `n` display columns, adding an ellipsis when cut.
truncate_str() {
  local s="$1" n="$2"
  if (( ${#s} > n )); then
    printf '%s…' "${s:0:$((n - 1))}"
  else
    printf '%s' "$s"
  fi
}

# One line per PR: colored icon, PR number, a Remote Sign-off run id when one
# is relevant (blank-padded when there isn't one, so the title column stays
# aligned), and the title (truncated to the terminal width). `running`=1
# means a run is currently queued/in_progress on this branch (necessarily for
# its current tip, since the workflow checks out the ref live); otherwise
# `run_id`, if set, is the most recent *failed* run for a `failure`/`error`
# state, so you can jump straight to its logs instead of re-triggering blind.
# `in_queue`=1 means GitHub's merge queue already holds an entry for this PR —
# surfaced as a "in merge queue" label rather than a distinct checkmark color,
# so it lives alongside "needs review"/"ready to merge" in the same column.
# `has_conflicts`=1 means GitHub's `mergeable` field is `CONFLICTING` (not
# `MERGEABLE`/`UNKNOWN` — the latter is a transient "still computing" state,
# so it's treated as no conflict rather than guessed at).
# `review_decision`/`is_draft` drive that review-status column: "draft" (not
# reviewable yet), "changes" (CHANGES_REQUESTED), "conflicts" (base has
# diverged — takes priority over queue/review state, since a conflicted PR
# can't merge regardless of approval), "in merge queue" (PR is queued — takes
# priority over the remaining states, since queued implies approved and
# attested), "needs review" (no approval yet), or "ready to merge" (approved,
# attested, and not already queued).
print_pr_row() {
  local number="$1" title="$2" state="$3" run_id="$4" running="$5" width="$6" \
    in_queue="$7" review_decision="$8" is_draft="$9" has_conflicts="${10}"
  local icon room run_col run_color review_col

  if [[ "$running" == "1" ]]; then
    icon="${C_YELLOW}⟳${C_RESET}"
    run_color="$C_YELLOW"
  else
    case "$state" in
      success)       icon="${C_GREEN}${OK}${C_RESET}" ;;
      pending)       icon="${C_YELLOW}…${C_RESET}" ;;
      failure|error) icon="${C_RED}${NO}${C_RESET}" ;;   # a sign-off attempt ran and failed
      *)             icon="${C_DIM}○${C_RESET}" ;;       # none: never attempted
    esac
    run_color="$C_RED"
  fi

  if [[ -n "$run_id" ]]; then
    run_col="${run_color}$(printf '%-12s' "$run_id")${C_RESET}"
  else
    run_col="$(printf '%-12s' '')"
  fi

  if [[ "$is_draft" == "1" ]]; then
    review_col="${C_DIM}$(printf '%-14s' 'draft')${C_RESET}"
  elif [[ "$review_decision" == "CHANGES_REQUESTED" ]]; then
    review_col="${C_RED}$(printf '%-14s' 'changes')${C_RESET}"
  elif [[ "$has_conflicts" == "1" ]]; then
    review_col="${C_RED}$(printf '%-14s' 'conflicts')${C_RESET}"
  elif [[ "$in_queue" == "1" ]]; then
    review_col="${C_CYAN}$(printf '%-14s' 'in merge queue')${C_RESET}"
  elif [[ "$review_decision" != "APPROVED" ]]; then
    review_col="${C_YELLOW}$(printf '%-14s' 'needs review')${C_RESET}"
  elif [[ "$state" == "success" ]]; then
    review_col="${C_GREEN}${C_BOLD}$(printf '%-14s' 'ready to merge')${C_RESET}"
  else
    review_col="$(printf '%-14s' '')"
  fi

  room=$(( width - 37 ))  # icon(1) + space + "#NNNNN"(6) + space + run id(12) + review(14) + 3 spaces
  (( room < 20 )) && room=20
  printf '%s %-6s %s %s %s\n' "$icon" "#${number}" "$run_col" "$review_col" "$(truncate_str "$title" "$room")"
}

# Batched GraphQL lookup of merge-queue membership, review status, and
# mergeability for a set of PR numbers, one round trip for all of them via
# aliases (a REST call per PR would be N+1). `reviewDecision` reflects the
# trunk ruleset's required approving review (currently 1, see
# docs/dev/ci_signoff.md) — null/empty when GitHub hasn't computed a decision
# yet, which we treat like REVIEW_REQUIRED. `mergeable` is `MERGEABLE`,
# `CONFLICTING`, or `UNKNOWN` (GitHub computes it asynchronously; UNKNOWN just
# means "not yet", not "no conflict", but there's no cheap way to force or
# await the computation from here, so a fresh PR may show one blank cycle
# before conflicts appear).
# Returns `{}` on any failure so callers degrade to "not queued, needs review".
fetch_merge_queue_status() {
  local repo="$1" numbers="$2"
  local owner name fields query
  owner="${repo%%/*}"
  name="${repo#*/}"
  fields=$(jq -r '[.[] | "pr\(.): pullRequest(number: \(.)) { isInMergeQueue reviewDecision isDraft mergeable }"] | join("\n")' <<<"$numbers")
  [[ -n "$fields" ]] || { echo '{}'; return; }
  query="query(\$owner:String!,\$name:String!){repository(owner:\$owner,name:\$name){${fields}}}"
  gh api graphql -f query="$query" -f owner="$owner" -f name="$name" 2>/dev/null || echo '{}'
}

# List the sign-off/attestation status of every open PR authored by the
# authenticated user, one row per PR, including whether a Remote Sign-off run
# is currently in flight for that PR's branch.
cmd_mine() {
  require_tools
  require_jq

  local repo prs count
  repo=$(repo_slug)

  prs=$(gh pr list --repo "$repo" --author @me --state open \
    --json number,title,headRefName,headRefOid) \
    || fail "failed to list your open PRs on ${repo} (auth/rate-limit/network?)"
  count=$(jq 'length' <<<"$prs")
  if [[ "$count" -eq 0 ]]; then
    echo "${C_DIM}No open PRs authored by you on ${repo}.${C_RESET}"
    return 0
  fi

  # Everything below is independent of everything else, so it all runs
  # concurrently instead of one round trip after another: `mine`'s wall-clock
  # time is network-bound, and this turns N+2 sequential round trips into
  # roughly the slowest one. Each PR's combined commit status is the one
  # remaining per-PR REST call (statuses aren't a GraphQL field for an
  # arbitrary sha, so they can't join the batched query below); capped at
  # $max_parallel concurrent `gh api` processes to stay polite to the rate
  # limit, by draining the batch every $max_parallel jobs rather than
  # `wait -n`, since that needs bash 4.3+ and this script runs under macOS's
  # bash 3.2 (see has_content() above).
  local status_dir
  status_dir=$(mktemp -d "${TMPDIR:-/tmp}/spice-signoff-mine.XXXXXX") \
    || fail "failed to create a temp directory for concurrent status lookups"
  # A RETURN trap isn't function-scoped — left set, it fires again when this
  # function's *caller* (main's case statement) returns too, by which point
  # $status_dir (a local of this function) no longer exists, aborting under
  # `set -u`. Clear it as part of firing so it only ever runs once.
  trap 'rm -rf "$status_dir"; trap - RETURN' RETURN

  # Match on displayTitle, not headBranch: a workflow_dispatch run's headBranch
  # is the ref it was dispatched *against* (always trunk here — cmd_remote
  # doesn't pass --ref), not the `branch` input. signoff.yml's `run-name:
  # Remote Sign-off (${{ inputs.branch }})` puts the actual branch in the
  # title instead, so we match on that exact string.
  ( gh run list --repo "$repo" --workflow signoff.yml \
      --json displayTitle,status,conclusion,databaseId --limit 50 \
      > "${status_dir}/remote_runs" 2>/dev/null ) &

  ( fetch_merge_queue_status "$repo" "$(jq '[.[].number]' <<<"$prs")" \
      > "${status_dir}/mq_status" ) &

  local max_parallel=8 launched=2 i number sha
  for ((i = 0; i < count; i++)); do
    number=$(jq -r ".[$i].number" <<<"$prs")
    sha=$(jq -r ".[$i].headRefOid" <<<"$prs")
    ( gh api "repos/${repo}/commits/${sha}/status" 2>/dev/null \
        > "${status_dir}/status_${number}" ) &
    launched=$((launched + 1))
    (( launched % max_parallel == 0 )) && wait
  done
  wait

  local remote_runs mq_status
  remote_runs=$(cat "${status_dir}/remote_runs" 2>/dev/null)
  [[ -n "$remote_runs" ]] || remote_runs="[]"
  mq_status=$(cat "${status_dir}/mq_status" 2>/dev/null)
  [[ -n "$mq_status" ]] || mq_status="{}"

  local width
  width=$(tput cols 2>/dev/null) || width=100

  echo "${C_BOLD}${repo}${C_RESET} — ${count} open PR(s)"
  echo

  local pr title branch combined state run_id running in_queue review_decision is_draft has_conflicts
  for ((i = 0; i < count; i++)); do
    pr=$(jq -c ".[$i]" <<<"$prs")
    number=$(jq -r '.number' <<<"$pr")
    title=$(jq -r '.title' <<<"$pr")
    branch=$(jq -r '.headRefName' <<<"$pr")
    sha=$(jq -r '.headRefOid' <<<"$pr")

    combined=$(cat "${status_dir}/status_${number}" 2>/dev/null)
    [[ -n "$combined" ]] || combined='{}'
    state=$(combined_status_state "$combined")
    state="${state:-none}"

    running=0
    run_id=$(jq -r --arg title "Remote Sign-off (${branch})" \
      '[.[] | select(.displayTitle == $title and (.status == "in_progress" or .status == "queued"))][0].databaseId // empty' \
      <<<"$remote_runs")
    if [[ -n "$run_id" ]]; then
      running=1
    elif [[ "$state" == "failure" || "$state" == "error" ]]; then
      # Most recent completed+failed run for this branch, so a failed
      # attestation links straight to its logs instead of a bare icon.
      run_id=$(jq -r --arg title "Remote Sign-off (${branch})" \
        '[.[] | select(.displayTitle == $title and .status == "completed" and .conclusion == "failure")][0].databaseId // empty' \
        <<<"$remote_runs")
    fi

    in_queue=0
    [[ "$(jq -r ".data.repository.pr${number}.isInMergeQueue // false" <<<"$mq_status")" == "true" ]] && in_queue=1
    review_decision=$(jq -r ".data.repository.pr${number}.reviewDecision // \"\"" <<<"$mq_status")
    is_draft=0
    [[ "$(jq -r ".data.repository.pr${number}.isDraft // false" <<<"$mq_status")" == "true" ]] && is_draft=1
    has_conflicts=0
    [[ "$(jq -r ".data.repository.pr${number}.mergeable // \"\"" <<<"$mq_status")" == "CONFLICTING" ]] && has_conflicts=1

    print_pr_row "$number" "$title" "$state" "$run_id" "$running" "$width" \
      "$in_queue" "$review_decision" "$is_draft" "$has_conflicts"
  done

  echo
  echo "${C_DIM}○ not attested   ${NO} attestation failed   … pending   ⟳ remote sign-off running   ${OK} attested${C_RESET}"
  echo "${C_DIM}draft   ${C_RED}changes${C_DIM} requested   ${C_RED}conflicts${C_DIM}   ${C_CYAN}in merge queue${C_DIM}   ${C_YELLOW}needs review${C_DIM}   ${C_GREEN}${C_BOLD}ready to merge${C_RESET}"
  echo "${C_DIM}Sign off with: make signoff  (or: scripts/signoff remote)${C_RESET}"
}

# Resolve the ruleset id for TARGET_BRANCH by name. `first(...)` returns a single
# id inside jq — avoids `head`, which SIGPIPEs the writer under pipefail.
ruleset_id() {
  local repo="$1" rulesets
  rulesets=$(gh api "repos/${repo}/rulesets") \
    || fail "failed to list rulesets on ${repo} (auth/rate-limit/network?)"
  jq -r "first(.[] | select(.name==\"${TARGET_BRANCH}\") | .id) // empty" <<<"$rulesets"
}

cmd_check() {
  require_tools
  require_jq
  local repo id ruleset checks
  repo=$(repo_slug)
  id=$(ruleset_id "$repo")
  [[ -n "$id" ]] || fail "no ruleset named '${TARGET_BRANCH}' on ${repo}"
  # Fail loudly on an API error instead of reporting "not required" — a swallowed
  # auth/rate-limit/network error would otherwise look like a missing sign-off gate.
  ruleset=$(gh api "repos/${repo}/rulesets/${id}") \
    || fail "failed to read ruleset ${id} on ${repo} (auth/rate-limit/network?)"
  checks=$(jq -r '.rules[]? | select(.type=="required_status_checks") | .parameters.required_status_checks[]?.context' <<<"$ruleset")
  if grep -qx "Attestation" <<<"$checks"; then
    echo "${OK} '${TARGET_BRANCH}' requires developer sign-off (Attestation). Required checks:"
  else
    echo "${NO} '${TARGET_BRANCH}' does not yet require sign-off. Run: scripts/signoff install --yes"
  fi
  # `|| true`: bullet returns non-zero on an empty list, which under pipefail
  # would otherwise make this (last) statement exit the command non-zero.
  echo "$checks" | bullet "  - " || true
}

cmd_install() {
  local apply=false
  while [[ $# -gt 0 ]]; do
    case "$1" in
      --yes|-y) apply=true; shift ;;
      -h|--help) cmd_help; exit 0 ;;
      *) fail "unknown option: $1" ;;
    esac
  done

  require_tools
  require_jq
  local repo id ruleset
  repo=$(repo_slug)
  id=$(ruleset_id "$repo")
  [[ -n "$id" ]] || fail "no ruleset named '${TARGET_BRANCH}' on ${repo} (create it in the repo settings first)"
  # Fetch the ruleset once; both the preview and the PUT body derive from it.
  ruleset=$(gh api "repos/${repo}/rulesets/${id}") \
    || fail "failed to read ruleset ${id} on ${repo}"

  info "Ruleset '${TARGET_BRANCH}' (id ${id}) on ${repo}"
  info ""
  info "Current required checks:"
  jq -r '.rules[]? | select(.type=="required_status_checks") | .parameters.required_status_checks[]?.context' <<<"$ruleset" \
    | bullet "  - " >&2 || info "  (none)"
  info ""
  info "New required checks:"
  printf '%s\n' "${REQUIRED_CHECKS[@]}" | bullet "  + " >&2

  if ! $apply; then
    info ""
    info "Dry run. Re-run with --yes to apply:  scripts/signoff install --yes"
    return 0
  fi

  # Swap only the required_status_checks array, preserving every other rule
  # (pull_request approvals, merge_queue, etc.).
  local desired body
  desired=$(jq -n --argjson iid "$ACTIONS_INTEGRATION_ID" \
    '$ARGS.positional | map({context: ., integration_id: $iid})' --args "${REQUIRED_CHECKS[@]}")
  body=$(jq --argjson checks "$desired" '
    {
      name,
      target,
      enforcement,
      conditions,
      bypass_actors: (.bypass_actors // []),
      rules: (
        if any((.rules // [])[]; .type == "required_status_checks")
        then (.rules | map(
          if .type == "required_status_checks"
          then (.parameters.required_status_checks = $checks)
          else . end
        ))
        else ((.rules // []) + [{
          type: "required_status_checks",
          parameters: {
            strict_required_status_checks_policy: false,
            do_not_enforce_on_create: false,
            required_status_checks: $checks
          }
        }])
        end
      )
    }' <<<"$ruleset")

  echo "$body" | gh api --method PUT "repos/${repo}/rulesets/${id}" --input - >/dev/null \
    || fail "failed to update ruleset ${id} (need admin on ${repo})"
  echo "${OK} '${TARGET_BRANCH}' now requires developer sign-off + the full merge-queue suite."
}

# Dispatch remote sign-off for the current branch (Git or JJ) on the GitHub
# Actions Remote Sign-off workflow. Deliberately never SSH: ad-hoc hosts run
# unaccountable checks, and the LAN lab boxes double as benchmark machines —
# a workspace build there mid-run silently corrupts the measurement.
# Branch names are validated to a safe charset so they cannot break shell
# quoting or the workflow input parser.
cmd_remote() {
  require_tools

  local branch
  if [[ "$VCS" == "jj" ]]; then
    # Prefer a local bookmark on @, then on the selected remote tip revision.
    # Take the first line without `head` (SIGPIPE under pipefail).
    local bookmarks
    bookmarks=$(jj --color=never --no-pager log -r '@ & bookmarks()' --no-graph \
      -T 'local_bookmarks.map(|b| b.name()).join("\n")' 2>/dev/null || true)
    branch="${bookmarks%%$'\n'*}"
    if [[ -z "$branch" ]]; then
      local revision
      revision=$(current_revision false)
      bookmarks=$(jj --color=never --no-pager log -r "${revision} & bookmarks()" --no-graph \
        -T 'local_bookmarks.map(|b| b.name()).join("\n")' 2>/dev/null || true)
      branch="${bookmarks%%$'\n'*}"
    fi
    [[ -n "$branch" ]] \
      || fail "no JJ bookmark on the working-copy tip — bookmark the change, or: gh workflow run signoff.yml -f branch=<name>"
  else
    branch=$(git rev-parse --abbrev-ref HEAD 2>/dev/null || true)
    [[ -n "$branch" && "$branch" != "HEAD" ]] \
      || fail "not on a named Git branch — check out a branch, or: gh workflow run signoff.yml -f branch=<name>"
  fi

  # Mirror the workflow input validation: allow feature/foo, reject whitespace,
  # quotes, and path tricks so -f branch=… cannot be broken by the name.
  if [[ "$branch" =~ [[:space:]] || "$branch" == -* || "$branch" == /* || "$branch" == *..* \
      || "$branch" == *\"* || "$branch" == *\'* || "$branch" == *\$* || "$branch" == *\`* ]]; then
    fail "refusing to dispatch Remote Sign-off for unsafe branch name: '${branch}'"
  fi
  if [[ ! "$branch" =~ ^[A-Za-z0-9._/-]+$ ]]; then
    fail "refusing to dispatch Remote Sign-off for invalid branch name: '${branch}'"
  fi

  local repo
  repo=$(repo_slug) || fail "could not resolve GitHub repo for workflow dispatch"

  info "Dispatching GitHub Actions Remote Sign-off for ${branch} on ${repo}…"
  # --repo so non-colocated JJ workspaces (no .git) still resolve the remote;
  # --raw-field avoids shell re-quoting pitfalls; the branch was validated above.
  gh workflow run signoff.yml --repo "$repo" --ref "${branch}" --raw-field "branch=${branch}" \
    || fail "failed to dispatch signoff.yml"
  echo "${OK} Dispatched. Watch with: gh run watch --repo ${repo} --workflow signoff.yml"
}

cmd_help() {
  cat >&2 <<EOF
scripts/signoff ${VERSION} — local CI attestation for Spice.ai

Developers:
  make signoff                 Run lint + unit tests, then sign off on HEAD
  make signoff-remote          Dispatch GHA Remote Sign-off for the current branch
  scripts/signoff remote       Same as make signoff-remote (Git + JJ)
  scripts/signoff -f           Sign off even with a dirty/unpushed tree
  scripts/signoff --no-verify  Sign off without running checks (honor system)
  scripts/signoff --note TEXT  Add TEXT to the sign-off description; with
                               --no-verify it replaces "(checks not verified
                               locally)", so say where the checks ran
  scripts/signoff verify [--skip-targeted]
                               Run the checks on HEAD, post no status. HEAD need
                               not be pushed (see scripts/signoff-batch)
  scripts/signoff --skip-targeted
                               Skip the branch-scoped pre-lint and unit tests
                               (steps 1-2); the full gate still runs
  scripts/signoff status       Show the sign-off status of HEAD
  scripts/signoff mine         Show attestation status for all your open PRs
  scripts/signoff clear-pending [reason]
                               Restate a left-behind '${STATUS_CONTEXT}' pending status
                               on HEAD as a run that reached no verdict: it stays
                               pending, with [reason] as its description (no-op for
                               any other state)

CI (.github/workflows/signoff.yml):
  scripts/signoff correct-cancelled [<sha>] [<owner/repo>]
                               Repair the status a cancelled run left behind:
                               rewrite '${STATUS_CONTEXT}=failure'/'error' to pending,
                               and leave any other state (notably success) alone

  scripts/signoff preflight-disk
                               Check the work volume against the ${DEFAULT_MIN_FREE_GIB} GiB floor
                               before the toolchain setup steps run; fatal only
                               on a remote run (override: SIGNOFF_MIN_FREE_GIB)

  scripts/signoff preflight-lockfile
                               Ask cargo whether Cargo.lock still describes the
                               manifests, before anything is built. Also run by
                               pr.yml Build and Test, so both gates use one copy

Maintainers:
  scripts/signoff check        Show whether '${TARGET_BRANCH}' requires sign-off
  scripts/signoff install      Preview the required-checks change (dry run)
  scripts/signoff install --yes  Apply it (needs admin on the repo)

Checks (when verify is on):
  0. If the branch has no Rust-affecting files vs trunk (.rs, Cargo.toml/lock,
     rust-toolchain*, .cargo/*, clippy/rustfmt/nextest/layers config, the lint
     guards, the root Makefile) → skip Rust lint/build/tests (still posts
     status)
  0b. Refuse the run when this branch's Makefile has no rule for a target the
     gate invokes — a branch based before the target was added would otherwise
     build for hours and then die on it
  1. Targeted lint of crates touched by this branch vs trunk
     (make lint-rust PACKAGES="…") — fail-fast feedback
  2. Targeted unit tests for those crates (make nextest-packages PACKAGES="…")
  3. Full workspace lint (make lint-rust)
  4. Unit tests, then assert the CLI binary exists (make nextest verify-cli)

  Steps 1-2 pass the features each crate resolves to in a workspace build, not
  the crate's own defaults — a scoped build of a crate that declares no
  'default' (runtime) would otherwise compile with no features at all.

  --skip-targeted skips both of steps 1-2, which trade an extra compile of those
  crates for early failure. SIGNOFF_SKIP_TARGETED_TESTS=1 skips step 2 alone;
  SIGNOFF_SKIP_TARGETED_LINT=1 skips both, because step 2 runs against the
  packages step 1 discovers.
  Remote runs (.github/workflows/signoff.yml) set SIGNOFF_REMOTE_RUN and use
  the GitHub compare API when the clone is too shallow for merge-base.

  make signoff-remote dispatches signoff.yml on GitHub Actions (self-hosted
  runner) for the current branch. Sign-off runs only where it is accountable:
  this machine, or the runner — never ad-hoc SSH hosts.

The sign-off is a '${STATUS_CONTEXT}' commit status bound to the exact commit you
pushed. Sign off again after any code change or manual conflict resolution. The
Attestation check can carry a sign-off across a first-parent chain of unmodified,
conflict-free base merges. The full test suite runs in the merge queue.
EOF
}

main() {
  case "${1:-}" in
    ""|signoff) shift || true; cmd_signoff "$@" ;;
    -f|--force|--no-verify|--skip-targeted|--note) cmd_signoff "$@" ;;
    verify)   shift; cmd_verify "$@" ;;
    remote)   shift; cmd_remote "$@" ;;
    status)   shift; cmd_status "$@" ;;
    mine)     shift; cmd_mine "$@" ;;
    correct-cancelled) shift; cmd_correct_cancelled "$@" ;;
    clear-pending) shift; cmd_clear_pending "$@" ;;
    preflight-disk) shift; cmd_preflight_disk "$@" ;;
    preflight-lockfile) shift; cmd_preflight_lockfile "$@" ;;
    check)    shift; cmd_check "$@" ;;
    install)  shift; cmd_install "$@" ;;
    version|--version) echo "signoff ${VERSION}" ;;
    -h|--help) cmd_help ;;
    *) fail "unknown command: $1 (see: scripts/signoff --help)" ;;
  esac
}

# Only dispatch when executed. The unit tests source this file to call
# individual functions, and sourcing must not run a command. BASH_SOURCE is unset
# when the script's *contents* are fed to bash (`bash -c "$(cat …)"`, a piped
# download), which `set -u` would abort on — default it to $0, which dispatches,
# since that invocation means to run the thing.
if [[ "${BASH_SOURCE[0]:-$0}" == "${0}" ]]; then
  main "$@"
fi
