#!/bin/bash
# SPDX-FileCopyrightText: 2025 OmniNode.ai Inc.
# SPDX-License-Identifier: MIT
#
# ONEX_GH_USER_SHIM (OMN-19479) -- a `gh` shim installed ahead of the real
# binary on this host's PATH (scripts/user-bin/install-gh-shim.sh).
#
# CI pass-through (OMN-19856): a CI job is not a lane. When GITHUB_ACTIONS is
# exactly true, exec the real gh unchanged before any guard, cache or log.
#
# Why: the Claude Code harness looks up the current branch's PR link with
# `gh pr view [<branch>] --json url` every few seconds per session, and every
# lookup spends the operator's shared GitHub quota (2026-09-24 plan M4: at
# least 355 GraphQL requests an hour from two sessions). This shim answers
# exactly two read shapes from a 600 s per-(repository, branch) cache and
# hands every other command to the real `gh` unchanged:
#
#   gh pr view [<branch>] --json url
#   gh pr view [<branch>] --json number,url,state
#
# Before it reads that cache the shim asks the PR watcher's state file (OMN-19479): a fresh
# state naming exactly one open PR whose head branch is the one asked about answers the
# lookup with no GitHub call, logged cache=watcher; anything else (no state, a stale
# tick, no jq, a branch with no open PR) runs the real gh as before.
#
# Nothing else is cached. A PR mutation that can change those answers
# (create, ready, close, reopen, merge) purges the cache before it runs.
# A cached "no pull requests found" answer is kept like a positive one; any
# other failure (network, quota, auth) is never cached.
#
# Read routing (OMN-19587): with ONEX_GH_READ_ROUTING=1, the read shapes
# `gh api` GET/HEAD, `pr view|list|checks|diff`, `run view|list`, `repo view`,
# `issue view|list` and `search` are candidates handed to gh_route.py
# (installed next to this file by install-gh-shim.sh; override with
# ONEX_GH_ROUTER); gh_route.py's own classify() is the authority on whether a
# given call actually reads (a viewer-resolving query or a non-OmniNode-ai
# owner still runs on the operator there). `api graphql` is never a
# candidate here: this shim cannot tell a mutation from a read without
# parsing the query the way gh_route.py does, so no graphql call reaches the
# router process at all -- every graphql call, mutation or read, runs on the
# operator unchanged, cleanly. It runs an actual read on the read-only App
# token from
# GH_READ_TOKEN_CMD and falls back to the operator credential when there is
# none. Every other call, and every write, runs on the operator unchanged and
# never reaches the router. With the flag unset or anything but 1 the shim
# runs the real gh exactly as it did before routing existed. Both variables
# default from ~/.config/omni/gh-read-routing.env when unset (OMN-19852).
#
# Search guard (OMN-19852): GitHub's secondary-rate-limited search bucket is
# reserved for the launchd PR watcher. `gh api search/...` and `gh search ...`
# are refused unless ONEX_PR_WATCHER=1; readers use the watcher's local state
# and the canonical clones instead.
#
# PR-state read guard (OMN-19856): `gh pr view|checks`, `gh run view` and the `gh api`
# GET/HEAD reads of pulls, check-runs, check-suites, commit statuses, actions/runs and
# actions/jobs are refused unless the caller is the PR watcher or the landing controller's
# own process, or the call is a declared exact-head check (RULING 2026-09-27T18:05:21Z).
# Full contract at the guard, below the search guard.
#
# Lane read guard (OMN-20911): from a lane context (an agent environment marker, or a
# Claude Code / Codex / ChatGPT ancestor process) every other GitHub read falls back to the
# cached read gateway and its per-hour budget, logged `fallback`, until its verb is set
# strict in gh-gateway.env; a strict verb is refused with the local reader named. Writes
# stay allowed. Failing-job logs, one check run's detail and one commit object by full sha
# (OMN-20960) go through the same gateway (RULING 2026-10-10T18:17:36Z; fallback per the
# 2026-10-12T05:03:28Z ruling). Full contract at the guard, below the PR-state guard.
#
# Lane write guard (OMN-20914): from a lane, a gh write that `onex scm` serves (read from
# the operations table of node_github_repo_write_effect's contract in the omnimarket the
# `onex` command runs) is refused, naming the `onex scm` verb that replaces it. A write with
# no onex scm operation stays allowed. Full contract at the guard, below the PR-state guard.
#
# Logged fallback (OMN-20911, RULING 2026-10-12T05:03:28Z): a few named consumers whose
# replacement path does not work yet keep their old call through both lane guards, and
# every such use appends one FRICTION row. List and contract at _fb_match.
#
# Shared call log (OMN-19852): every allowed or refused call appends one
# tab-separated line to ONEX_GH_CALLS_LOG, else ONEX_STATE_DIR/gh-calls.log
# (no log is written when neither is set).
# It contains only timestamp, resolved lane/source, class, method, endpoint,
# exit code and action -- never argv, environment values or tokens.
# ONEX_GH_USAGE_LOG=0 turns both usage logs off for one call.
#
# Usage log (OMN-19585): every invocation appends one JSON line to
# ${XDG_CACHE_HOME:-$HOME/.cache}/omni/gh-usage/<UTC date>.jsonl with the
# timestamp, lane (ONEX_LANE; else ONEX_LANE_ID, ONEX_AGENT_NAME,
# CLAUDE_AGENT_NAME or CLAUDE_SUBAGENT_NAME; else the lane registered for the
# omni_worktrees/<ticket>/<dir> worktree the call is made from; else the Claude
# Code session id; else script:<name> when the parent is an interpreter running
# a .py/.sh/.js/.mjs script (lane_source=script); else the parent command, with
# lane_source saying which),
# command class, HTTP method, repository, endpoint path (gh api only,
# query string dropped), exit code and whether the cache answered. With routing
# on it adds identity (app, operator, operator-fallback) and route_reason. Argv, stdin,
# output and environment values are never written, so no token can reach it.
# Every line also carries parent (ONEX_PARENT_LANE, the dispatching lane) and
# host (ONEX_LANE_HOST, else the short $HOSTNAME), "" when unknown (OMN-20420);
# the gh-calls.log TSV stays at 8 columns.
# scripts/user-bin/gh_usage_report.py turns the log into requests per lane.
# ONEX_GH_USAGE_LOG=0 turns the log off for one call.
#
# Gateway read marking (OMN-17427, phase a): JSON usage lines mark reads as
# gateway (ONEX_GH_GATEWAY=1) or bypass, and non-reads as "". Bypass reads warn
# before execution for attributed sessions/lanes or a terminal, unless
# ONEX_GH_WARN=0; ONEX_GH_WARN=1 opts programs in. The two cached harness
# PR-link shapes never warn, hit or miss: the harness asks every few seconds
# and phase (c) answers them from the PR-state projection.
# Last-resort attribution names known caller roles through up to six ancestors,
# then the direct parent's script, module or command. Roles never grant access.
#
# This file must stay bash 3.2 compatible: /bin/bash on macOS is 3.2.

ONEX_GH_SHIM_TTL="${ONEX_GH_SHIM_TTL:-600}"

# --- find the real gh: walk PATH past this file and any other shim copy -----
self="${BASH_SOURCE[0]}"
real=""
# PATH is split by parameter expansion, not `read <<< "$PATH"`: under Homebrew
# bash 5.3.9 a here-string read of this host's 1.6 kB PATH hung twice at
# 2026-09-25T14:52Z (load average 72) and did not reproduce at 15:05Z. The
# shim must never be able to hang a gh call, and this form has no temp file.
_rest="$PATH:"
while [ -n "$_rest" ]; do
  _d="${_rest%%:*}"
  _rest="${_rest#*:}"
  [ -n "$_d" ] || continue
  _c="$_d/gh"
  [ -f "$_c" ] && [ -x "$_c" ] || continue
  [ "$_c" -ef "$self" ] && continue
  # Another copy of this shim (a second install, or the source tree on PATH)
  # would recurse forever; skip anything carrying the marker.
  if head -c 512 "$_c" 2>/dev/null | grep -q 'ONEX_GH_USER_SHIM'; then
    continue
  fi
  real="$_c"
  break
done
if [ -z "$real" ]; then
  echo "gh shim (OMN-19479): no real gh found on PATH after $self" >&2
  exit 127
fi

if [ "${GITHUB_ACTIONS:-}" = "true" ]; then
  exec "$real" "$@"
fi

# --- read-routing defaults (OMN-19852) -----------------------------------------
# A session, a launchd job and a Codex lane each start with their own environment,
# so an exported flag reaches only the shells that happened to inherit it. When
# ONEX_GH_READ_ROUTING or GH_READ_TOKEN_CMD is unset, take it from the one host
# file ${XDG_CONFIG_HOME:-$HOME/.config}/omni/gh-read-routing.env (KEY=VALUE
# lines; only these two keys are read, nothing is evaluated). The environment
# wins, so ONEX_GH_READ_ROUTING=0 still turns routing off for one call.
#
# A trailing " # note" on the same line as the value (an operator's own
# disable annotation is the observed case, OMN-19852) is stripped, comment and
# the whitespace before it: without this, "ONEX_GH_READ_ROUTING=1  # re-enabled"
# would compare unequal to "1" and silently run every read on the operator
# while the file reads enabled.
_conf_strip_comment_into() {
  local v="$2"
  case "$v" in *[[:space:]]'#'*) v="${v%%[[:space:]]\#*}" ;; esac
  while :; do
    case "$v" in
      *[[:space:]]) v="${v%[[:space:]]}" ;;
      *) break ;;
    esac
  done
  printf -v "$1" '%s' "$v"
}
_conf_v=""
_routing_conf="${ONEX_GH_READ_ROUTING_CONF:-${XDG_CONFIG_HOME:-$HOME/.config}/omni/gh-read-routing.env}"
if [ -f "$_routing_conf" ] && { [ -z "${ONEX_GH_READ_ROUTING+x}" ] || [ -z "${GH_READ_TOKEN_CMD+x}" ]; }; then
  while IFS= read -r _line || [ -n "$_line" ]; do
    case "$_line" in
      ONEX_GH_READ_ROUTING=*)
        if [ -z "${ONEX_GH_READ_ROUTING+x}" ]; then
          _conf_strip_comment_into _conf_v "${_line#*=}"
          export ONEX_GH_READ_ROUTING="$_conf_v"
        fi ;;
      GH_READ_TOKEN_CMD=*)
        if [ -z "${GH_READ_TOKEN_CMD+x}" ]; then
          _conf_strip_comment_into _conf_v "${_line#*=}"
          export GH_READ_TOKEN_CMD="$_conf_v"
        fi ;;
    esac
  done < "$_routing_conf"
fi

_cache_root="${XDG_CACHE_HOME:-$HOME/.cache}/omni/gh-shim/prview"

# These reads describe this invocation. Reuse them across guards and logs rather
# than starting git or date again for the same working directory and call.
_origin_done=0
_origin_url=""
_origin=""
_read_origin() {
  [ "$_origin_done" -eq 1 ] && return 0
  _origin_done=1
  _origin_url="$(git config --get remote.origin.url 2>/dev/null)"
  _origin="${_origin_url%.git}"
  _origin="${_origin##*:}"
  case "$_origin" in */*/*) _origin="${_origin#"${_origin%/*/*}"/}" ;; esac
}

_call_timestamp=""
_read_timestamp() {
  [ -n "$_call_timestamp" ] || _call_timestamp="$(date -u +%Y-%m-%dT%H:%M:%SZ)"
}

# Bash 3.2 has no ${value^^}. The strict-config key is ASCII, so translate in
# this shell instead of starting a pipeline for every guarded read.
_ascii_upper_into() {
  local value="$2" lower=abcdefghijklmnopqrstuvwxyz upper=ABCDEFGHIJKLMNOPQRSTUVWXYZ i
  for ((i=0; i<26; i++)); do
    value="${value//${lower:i:1}/${upper:i:1}}"
  done
  printf -v "$1" '%s' "$value"
}

# --- usage log (OMN-19585) -----------------------------------------------------

# Keep only characters that are safe inside a log value and meaningful in a
# repo, endpoint or lane name, and blank anything shaped like a GitHub token.
_clean_into() {
  local v="$2"
  v="${v//[^A-Za-z0-9._\/:@+=, -]/}"
  case "$v" in
    *ghp_*|*gho_*|*ghu_*|*ghs_*|*ghr_*|*github_pat_*) v="REDACTED" ;;
  esac
  printf -v "$1" '%s' "${v:0:200}"
}

_clean() {
  local cleaned=""
  _clean_into cleaned "$1"
  printf '%s' "$cleaned"
}

# Optional launcher context from the remote-lane runner (OMN-20420): the
# orchestrator lane that dispatched this one and the host it runs on. Both are
# usage-log (JSONL) fields only; the call-log TSV keeps its 8 columns.
_parent_lane=""; _lane_host=""
_resolve_parent_host() {
  _clean_into _parent_lane "${ONEX_PARENT_LANE:-}"
  if [ -n "${ONEX_LANE_HOST:-}" ]; then
    _clean_into _lane_host "$ONEX_LANE_HOST"
  else
    _clean_into _lane_host "${HOSTNAME%%.*}"
  fi
}

# Resolve attribution once for both the usage line and the read router.
_lane_done=0
_resolve_lane() {
  [ "$_lane_done" -eq 1 ] && return 0
  _lane_done=1
  _lane=""; _lane_src=""
  local agent="" cwd="" suffix="" ticket="" repo_dir="" worktree=""
  local registry_dir="" record="" hash="" registered="" parent="" pargs="" script="" w=""
  local pid="$PPID" steps=0 next="" info="" direct_args="" role="" job=0 module="" rest=""
  if [ -n "${ONEX_LANE:-}" ]; then
    _clean_into _lane "$ONEX_LANE"; _lane_src="env"
    return
  fi
  if [ -n "${ONEX_LANE_ID:-}" ]; then agent="$ONEX_LANE_ID"
  elif [ -n "${ONEX_AGENT_NAME:-}" ]; then agent="$ONEX_AGENT_NAME"
  elif [ -n "${CLAUDE_AGENT_NAME:-}" ]; then agent="$CLAUDE_AGENT_NAME"
  elif [ -n "${CLAUDE_SUBAGENT_NAME:-}" ]; then agent="$CLAUDE_SUBAGENT_NAME"
  fi
  if [ -n "$agent" ]; then
    _clean_into _lane "$agent"; _lane_src="agent-env"
    return
  fi
  cwd="$(pwd -P 2>/dev/null)"
  case "$cwd" in
    */omni_worktrees/*/*)
      suffix="${cwd#*/omni_worktrees/}"
      ticket="${suffix%%/*}"
      suffix="${suffix#*/}"
      repo_dir="${suffix%%/*}"
      worktree="${cwd%%/omni_worktrees/*}/omni_worktrees/$ticket/$repo_dir"
      if [ -n "${ONEX_LANE_REGISTRY_ROOT:-}" ]; then
        registry_dir="$ONEX_LANE_REGISTRY_ROOT/lane_identity"
      elif [ -n "${OMNI_HOME:-}" ]; then
        registry_dir="$OMNI_HOME/.onex_state/lane_identity"
      fi
      if [ -n "$registry_dir" ]; then
        hash="$(_sha "$worktree" | cut -c1-32)"
        record="$registry_dir/$hash.json"
        if [ -n "$hash" ] && [ -r "$record" ]; then
          registered="$(sed -n 's/.*"lane"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$record" 2>/dev/null | head -n 1)"
          if [ -n "$registered" ]; then
            _lane="$(_clean "$registered")"; _lane_src="registry"
            return
          fi
        fi
      fi
      ;;
  esac
  if [ -n "${CLAUDE_CODE_SESSION_ID:-}" ]; then
    _lane="session:$(_clean "$CLAUDE_CODE_SESSION_ID")"; _lane_src="session"
    return
  fi
  # Phase (a) of the GitHub gateway plan (OMN-17427): roles are attribution
  # only and never grant anything. The PR-state guard's allow decision stays
  # direct-parent-only (see _prs_caller_allowed). This walk runs only when no
  # env/registry/session attribution exists.
  while [ "$steps" -lt 6 ]; do
    case "$pid" in ""|*[!0-9]*) break ;; esac
    [ "$pid" -gt 1 ] || break
    # "<ppid> <args...>", split by parameter expansion like PATH above: no word
    # splitting and no glob expansion of the ancestor's command line.
    info="$(ps -ww -o ppid= -o args= -p "$pid" 2>/dev/null)"
    info="${info#"${info%%[![:space:]]*}"}"
    [ -n "$info" ] || break
    next="${info%%[[:space:]]*}"
    pargs="${info#"$next"}"
    pargs="${pargs#"${pargs%%[![:space:]]*}"}"
    # A role is named by the interpreter and script at the head of the command line. An
    # ancestor such as a headless `claude -p` carries its whole prompt in argv (150 kB
    # measured, OMN-20911), and the word loop below over that never finished within 30 s,
    # so only the head is read: the shim must never be able to hang a gh call.
    pargs="${pargs:0:4096}"
    [ "$steps" -eq 0 ] && direct_args="$pargs"
    role=""; job=0
    case "$pargs" in *omnibase_internal.pr_watcher*) role="pr-watcher" ;; esac
    rest="$pargs "
    while [ -z "$role" ] && [ -n "$rest" ]; do
      w="${rest%% *}"
      rest="${rest#* }"
      [ -n "$w" ] || continue
      if [ "$job" -eq 1 ]; then role="$w"; break; fi
      case "${w##*/}" in
        landing_controller.py) role="landing-controller" ;;
        landing_worker_run.py) role="landing-worker" ;;
        landing_lab_prover.py) role="landing-lab-prover" ;;
        onex_remote_lane.py) role="remote-lane-runner" ;;
        morning_workflows_tick.sh) job=1 ;;
      esac
    done
    if [ -n "$role" ]; then
      _lane="role:$(_clean "$role")"; _lane_src="role"
      return
    fi
    pid="$next"
    steps=$((steps + 1))
  done
  # No known role: the direct parent's script, module or command, as before.
  rest="$direct_args "
  w="${rest%% *}"
  rest="${rest#* }"
  parent="$(basename "$w" 2>/dev/null)"
  case "$parent" in
    python|Python|python3*|bash|sh|zsh|node|uv|ruby)
      # Only the first non-option word can be the script; `-m <module>` runs a
      # module, so a later .py word (`python -m pytest tests/x.py`) is an argument.
      while [ -n "$rest" ]; do
        w="${rest%% *}"
        rest="${rest#* }"
        [ -n "$w" ] || continue
        case "$w" in
          -m) rest="${rest#"${rest%%[![:space:]]*}"}"; module="${rest%% *}"; break ;;
          -*) continue ;;
          *.py|*.sh|*.js|*.mjs) script="$(basename "$w" 2>/dev/null)" ;;
        esac
        break
      done
      ;;
  esac
  if [ -n "$module" ]; then
    _lane="module:$(_clean "$module")"; _lane_src="module"
    return
  fi
  if [ -n "$script" ]; then
    _lane="script:$(_clean "$script")"; _lane_src="script"
    return
  fi
  _lane="parent:$(_clean "$parent")"; _lane_src="parent"
}

# Sets _cls, _method and _repo, _endpoint for the argv in "$@".
_classify() {
  _cls=""; _method=""; _repo=""; _endpoint=""
  local group="${1:-}" sub="${2:-}" a prev="" repo_flag="" has_field=0 is_mutation=0
  for a in "$@"; do
    case "$prev" in
      -R|--repo) repo_flag="$a" ;;
      -X|--method) _method="$a" ;;
    esac
    case "$a" in
      --repo=*) repo_flag="${a#--repo=}" ;;
      --method=*) _method="${a#--method=}" ;;
      -f|-F|--field|--raw-field|--input|--field=*|--raw-field=*|--input=*) has_field=1 ;;
    esac
    case "$a" in *mutation*) is_mutation=1 ;; esac
    prev="$a"
  done
  if [ "$group" = "api" ]; then
    # First positional after `api` that is not the value of an option.
    local skip=0
    shift
    for a in "$@"; do
      if [ "$skip" -eq 1 ]; then skip=0; continue; fi
      case "$a" in
        -X|--method|-H|--header|-f|--raw-field|-F|--field|--input|-q|--jq|-t|--template|--cache|--hostname|-p|--preview) skip=1 ;;
        -*) ;;
        *) _endpoint="${a%%\?*}"; break ;;
      esac
    done
    _endpoint="${_endpoint#/}"
    if [ "$_endpoint" = "graphql" ]; then
      _cls="api graphql"
      if [ "$is_mutation" -eq 1 ]; then _method="MUTATION"; else _method="POST"; fi
    else
      _cls="api"
      if [ -z "$_method" ]; then
        if [ "$has_field" -eq 1 ]; then _method="POST"; else _method="GET"; fi
      fi
      case "$_endpoint" in
        repos/*/*) _repo="${_endpoint#repos/}"; _repo="${_repo#*/}"; _repo="${_repo%%/*}" ;;
      esac
    fi
    _method="$(printf '%s' "$_method" | tr '[:lower:]' '[:upper:]')"
  else
    case "$sub" in
      ""|-*) _cls="$group" ;;
      *) _cls="$group $sub" ;;
    esac
    case "$group" in
      ""|-*|auth|config|alias|extension|help|completion|version|status) _method="LOCAL" ;;
      search|browse) _method="GET" ;;
      *)
        case "$sub" in
          view|list|checks|diff|status|download|watch|ls) _method="GET" ;;
          *) _method="WRITE" ;;
        esac
        ;;
    esac
    [ "$group" = "status" ] && _method="GET"
    if [ -n "$repo_flag" ]; then
      _repo="${repo_flag##*/}"
    else
      case "$group" in
        pr|issue|run|workflow|release|label|repo|cache|ruleset)
          _read_origin
          _repo="$_origin_url"
          _repo="${_repo%.git}"; _repo="${_repo##*/}"; _repo="${_repo##*:}"
          ;;
      esac
    fi
  fi
}

# _call_log <exit code> <action: allowed|refused|fallback>
_call_log() {
  [ "${ONEX_GH_USAGE_LOG:-1}" = "0" ] && return 0
  local file="" dir="" ts="" oversized="" value="" cleaned=""
  local log_fields=()
  if [ -n "${ONEX_GH_CALLS_LOG:-}" ]; then
    file="$ONEX_GH_CALLS_LOG"
  elif [ -n "${ONEX_STATE_DIR:-}" ]; then
    file="$ONEX_STATE_DIR/gh-calls.log"
  else
    return 0
  fi
  case "$file" in
    */*) dir="${file%/*}" ;;
    *) dir="." ;;
  esac
  mkdir -p "$dir" 2>/dev/null || return 0
  if [ $(( $$ % 50 )) -eq 0 ] && [ -f "$file" ]; then
    oversized="$(find "$file" -prune -type f -size +20480k -print 2>/dev/null)"
    if [ -n "$oversized" ]; then
      mv -f "$file" "$file.1" 2>/dev/null || true
    fi
  fi
  _resolve_lane
  _read_timestamp
  ts="$_call_timestamp"
  # Sanitize in this shell: command substitution would fork once per field.
  for value in "$ts" "$_lane" "$_lane_src" "$_cls" "$_method" "$_endpoint" "$1" "$2"; do
    _clean_into cleaned "$value"
    log_fields+=("$cleaned")
  done
  printf '%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n' "${log_fields[@]}" >> "$file" 2>/dev/null || true
}

# _refusal_row <guard> <reason class> <detail>   (OMN-21020)
# Writes one class=refusal row for a refusal through the refusal recorder's shell entry
# (plugins/onex/hooks/lib/hook_refusal.sh), the same seam every hook guard records through:
# the recorder resolves the lane, redacts, dedupes and carries the suppressed count. Only the
# two gates the call log alone used to hold call this: the lane read (OMN-20911) and the
# covered write (OMN-20914). The seam is the canonical clone's, or ONEX_HOOK_REFUSAL_SEAM.
# Fail-open by construction: a seam that cannot be found or run never changes the refusal,
# which the caller has already decided.
_refusal_row() {
  local seam="${ONEX_HOOK_REFUSAL_SEAM:-}"
  if [ -z "$seam" ] && [ -n "${OMNI_HOME:-}" ]; then
    seam="$OMNI_HOME/omniclaude/plugins/onex/hooks/lib/hook_refusal.sh"
  fi
  [ -n "$seam" ] && [ -r "$seam" ] || return 0
  (
    _OMNICLAUDE_HOOK_NAME="$1"
    _OMNICLAUDE_HOOK_PAYLOAD='{}'
    ONEX_REGISTRY_ROOT="${ONEX_REGISTRY_ROOT:-${OMNI_HOME:-}}"
    # shellcheck source=/dev/null
    source "$seam" || exit 0
    hook_record_refusal "$2" "$3"
  ) || true
  return 0
}

# _log <exit code> <cache: hit|miss|none> [call-log action, default allowed]
_log() {
  [ "${ONEX_GH_USAGE_LOG:-1}" = "0" ] && return 0
  _call_log "$1" "${3:-allowed}"
  local dir="${XDG_CACHE_HOME:-$HOME/.cache}/omni/gh-usage"
  local ts session ticket="" identity="" route_reason=""
  local cls="" method="" repo="" endpoint=""
  _read_timestamp
  ts="$_call_timestamp"
  _clean_into session "${CLAUDE_CODE_SESSION_ID:-}"
  case "$PWD" in
    */omni_worktrees/OMN-*) ticket="${PWD#*/omni_worktrees/}"; ticket="${ticket%%/*}" ;;
  esac
  mkdir -p "$dir" 2>/dev/null || return 0
  _resolve_lane
  _resolve_parent_host
  _clean_into ticket "$ticket"
  _clean_into cls "$_cls"
  _clean_into method "$_method"
  _clean_into repo "$_repo"
  _clean_into endpoint "$_endpoint"
  if [ -n "$_route" ]; then
    identity="${_route%% *}"
    case "$_route" in *\ *) route_reason="${_route#* }" ;; esac
    _clean_into identity "$identity"
    _clean_into route_reason "$route_reason"
    printf '{"ts":"%s","lane":"%s","lane_source":"%s","session":"%s","ticket":"%s","cls":"%s","method":"%s","repo":"%s","endpoint":"%s","exit":%s,"cache":"%s","identity":"%s","route_reason":"%s","parent":"%s","host":"%s","pid":%s,"gateway":"%s"}\n' \
      "$ts" "$_lane" "$_lane_src" "$session" "$ticket" "$cls" "$method" \
      "$repo" "$endpoint" "$1" "$2" "$identity" "$route_reason" "$_parent_lane" "$_lane_host" "$$" "$_gateway" \
      >> "$dir/${ts%%T*}.jsonl" 2>/dev/null || true
  else
    printf '{"ts":"%s","lane":"%s","lane_source":"%s","session":"%s","ticket":"%s","cls":"%s","method":"%s","repo":"%s","endpoint":"%s","exit":%s,"cache":"%s","parent":"%s","host":"%s","pid":%s,"gateway":"%s"}\n' \
      "$ts" "$_lane" "$_lane_src" "$session" "$ticket" "$cls" "$method" \
      "$repo" "$endpoint" "$1" "$2" "$_parent_lane" "$_lane_host" "$$" "$_gateway" \
      >> "$dir/${ts%%T*}.jsonl" 2>/dev/null || true
  fi
}

# --- is this one of the two cacheable read shapes? ---------------------------
# Returns 0 and sets _branch_arg and _fields when it is.
_cacheable() {
  [ "${1:-}" = "pr" ] && [ "${2:-}" = "view" ] || return 1
  _branch_arg=""
  _fields=""
  case "$#" in
    4) [ "$3" = "--json" ] || return 1; _fields="$4" ;;
    5)
      case "$3" in -*|"") return 1 ;; esac
      [ "$4" = "--json" ] || return 1
      _branch_arg="$3"; _fields="$5" ;;
    *) return 1 ;;
  esac
  case "$_fields" in url|number,url,state) return 0 ;; esac
  return 1
}

_sha() {
  # Prefer the native utility to starting Perl for every gateway cache key.
  # macOS installations without sha256sum retain the shasum fallback.
  if command -v sha256sum >/dev/null 2>&1; then
    printf '%s' "$1" | sha256sum | cut -c1-40
  else
    printf '%s' "$1" | shasum -a 256 | cut -c1-40
  fi
}

_classify "$@"
_route=""
# This env marker is attribution only in phase (a); the later boundary is
# that only the gateway holds a credential.
_gateway=""
if [ "$_method" = "GET" ] || [ "$_method" = "HEAD" ] || \
   { [ "$_cls" = "api graphql" ] && [ "$_method" = "POST" ]; }; then
  if [ "${ONEX_GH_GATEWAY:-}" = "1" ]; then _gateway="gateway"; else _gateway="bypass"; fi
fi

_warn_gateway_read() {
  [ "$_gateway" = "bypass" ] && [ "${ONEX_GH_WARN:-}" != "0" ] || return 0
  # The harness link shapes never warn, even when no branch resolves (a
  # detached HEAD) and the call falls through the cache to the pass-through.
  _cacheable "$@" && return 0
  _resolve_lane
  if [ "${ONEX_GH_WARN:-}" != "1" ] && [ ! -t 2 ]; then
    case "$_lane_src" in env|agent-env|registry|session) ;; *) return 0 ;; esac
  fi
  printf 'gh shim (OMN-17427): direct GitHub read by %s (%s %s %s); reads are moving to the GitHub gateway on the event bus. Set ONEX_GH_WARN=0 to silence this line.\n' \
    "$_lane" "$_cls" "$_method" "${_endpoint:--}" >&2
}

# --- secondary-rate-limited search guard (OMN-19852) -------------------------
_search_call=0
if [ "$_cls" = "api" ]; then
  case "$_endpoint" in search/*|http://*/search/*|https://*/search/*) _search_call=1 ;; esac
else
  case "$_cls" in search|search\ *) _search_call=1 ;; esac
fi
if [ "$_search_call" -eq 1 ] && [ "${ONEX_PR_WATCHER:-}" != "1" ]; then
  printf '%s\n' \
    'REFUSED (OMN-19852): GitHub search is the secondary-rate-limited bucket that took queue-status down at 21:5xZ on 2026-09-28.' \
    'Read PR state from state.json under the .claude_scratch/pr-watcher directory of the workspace root; use merge-drain pr_state_local.py: python3 pr_state_local.py --pr OmniNode-ai/<repo>#<n>, or python3 pr_state_local.py --status.' \
    'For merge counts, use git -C <canonical clone> log origin/dev on the clone that canonical-clone-sync keeps fetched.' >&2
  _call_log 1 refused
  exit 1
fi
unset _search_call

# --- PR-state read guard (OMN-19856) -------------------------------------------
# RULING 2026-09-27T18:05:21Z: every PR-state read comes from the PR watcher's state
# file; GitHub is for mutations and the exact-head check right before one. Between
# 2026-10-03 18:49Z and 21:49Z one operator host logged 3,606 gh calls, 2,331 of them
# PR-state reads (api pulls 826, api actions/runs 408, pr view 351, api check-runs
# 304, api actions/jobs 199, run view 117, api check-suites 89, pr checks 37): the
# ruling stood as prose in prompts and every lane kept reading GitHub, so this is
# the refusal that holds whatever a prompt says. No off switch, no warning mode.
#
# Guarded (refused with the local alternatives, exit 1):
#   gh pr view      except the two harness link shapes the cache below serves
#                   (_cacheable) and the declared exact-head check
#   gh pr checks, gh run view
#   gh api, method GET or HEAD, endpoint (leading "/" and an
#   https://api.github.com/ prefix stripped) repos/<o>/<r>/pulls or under it, or
#   containing /check-runs, /check-suites, /commits/<ref>/status, /statuses,
#   /actions/runs or /actions/jobs
# Never guarded: a failing-job log read (`gh run view ... --log-failed|--log` with no
# --json/--jq/--template, and `gh api repos/<o>/<r>/actions/jobs/<id>/logs`; OMN-20436),
# any write (a non-GET api method, pr merge|ready|create|edit|
# comment|close, run rerun|cancel, workflow run) and `api graphql` (a residual: it
# cannot be told from a mutation here, and pr-land's pr_snapshot.py uses it).
#
# Allowed callers, decided only for a guarded shape (ps is never run for any other):
#   (a) ONEX_PR_WATCHER=1, the marker the search guard above already uses;
#   (b) the shim's DIRECT parent process runs landing_controller.py,
#       landing_lab_prover.py or landing_worker_run.py from
#       ${ONEX_LANDING_CONTROLLER_ROOT:-$HOME/.omninode/landing-controller}/skills/merge-drain/scripts/;
#   (c) the direct parent's argv contains omnibase_internal.pr_watcher.
# Direct parent only: never an ancestor walk and never an env marker for the
# controller, because the workers it spawns inherit its environment and run under
# its process tree, and they must stay refused.
#
# Declared exact-head check, the one narrow escape the ruling names: the call sets
# ONEX_GH_EXACT_HEAD=<owner>/<repo>#<n> and is exactly
#   gh pr view <n> --repo|-R <owner>/<repo> --json <fields>
# with <n> and the repository matching the declaration, every field in {headRefOid,
# headRefName, baseRefName, state, isDraft, mergedAt, mergeStateStatus, number,
# isCrossRepository}, and
# no --jq, --template, --web or --comments. A declaration of any other shape is
# refused with a message naming the part that failed.

# Direct parent's argv, only on demand. -ww: a BSD ps would otherwise cut the line.
_parent_args_done=0
_parent_args=""
_read_parent_args() {
  [ "$_parent_args_done" -eq 1 ] && return 0
  _parent_args_done=1
  # The same direct parent is checked by several guards during one invocation.
  _parent_args="$(ps -ww -o args= -p "$PPID" 2>/dev/null)"
}

_prs_caller_allowed() {
  [ "${ONEX_PR_WATCHER:-}" = "1" ] && return 0
  local args root scripts
  _read_parent_args
  args="$_parent_args"
  [ -n "$args" ] || return 1
  case "$args" in *omnibase_internal.pr_watcher*) return 0 ;; esac
  root="${ONEX_LANDING_CONTROLLER_ROOT:-$HOME/.omninode/landing-controller}"
  scripts="${root%/}/skills/merge-drain/scripts"
  case " $args " in
    *" $scripts/landing_controller.py "*) return 0 ;;
    *" $scripts/landing_lab_prover.py "*) return 0 ;;
    *" $scripts/landing_worker_run.py "*) return 0 ;;
  esac
  return 1
}

# Declared exact-head check over the argv in "$@". Returns 0 when allowed; otherwise
# 1 with _prs_why naming the part that failed ("" when no declaration was made).
_prs_exact_head() {
  _prs_why=""
  local decl="${ONEX_GH_EXACT_HEAD:-}" d_repo="" d_n="" a n="" repo="" fields="" f
  local have_repo=0 have_json=0 bad=""
  [ -n "$decl" ] || return 1
  case "$decl" in
    *#*) d_repo="${decl%%#*}"; d_n="${decl#*#}" ;;
  esac
  case "$d_repo" in ""|*/*/*|/*|*/|*[!A-Za-z0-9._/-]*) d_repo="" ;; */*) ;; *) d_repo="" ;; esac
  case "$d_n" in ""|*[!0-9]*) d_n="" ;; esac
  if [ -z "$d_repo" ] || [ -z "$d_n" ]; then
    _prs_why="ONEX_GH_EXACT_HEAD is not <owner>/<repo>#<n> (got a differently shaped value)"
    return 1
  fi
  if [ "${1:-}" != "pr" ] || [ "${2:-}" != "view" ]; then
    _prs_why="ONEX_GH_EXACT_HEAD covers only: gh pr view <n> --repo <owner>/<repo> --json <fields>; this call is a different command, not a pr view"
    return 1
  fi
  shift 2
  while [ $# -gt 0 ]; do
    a="$1"; shift
    case "$a" in
      --repo|-R)
        if [ $# -eq 0 ]; then _prs_why="ONEX_GH_EXACT_HEAD: $a has no value"; return 1; fi
        repo="$1"; have_repo=1; shift ;;
      --repo=*) repo="${a#--repo=}"; have_repo=1 ;;
      --json)
        if [ $# -eq 0 ]; then _prs_why="ONEX_GH_EXACT_HEAD: --json has no value"; return 1; fi
        fields="$1"; have_json=1; shift ;;
      --json=*) fields="${a#--json=}"; have_json=1 ;;
      --jq|--jq=*|-q|--template|--template=*|-t|--web|-w|--comments|-c)
        _prs_why="ONEX_GH_EXACT_HEAD: ${a%%=*} is not allowed in an exact-head check (the fields are read whole)"
        return 1 ;;
      -*)
        _prs_why="ONEX_GH_EXACT_HEAD: flag ${a%%=*} is not part of the exact-head shape"
        return 1 ;;
      *)
        if [ -n "$n" ]; then
          _prs_why="ONEX_GH_EXACT_HEAD: more than one PR number in the call"
          return 1
        fi
        n="$a" ;;
    esac
  done
  if [ -z "$n" ]; then
    _prs_why="ONEX_GH_EXACT_HEAD: the PR number is missing; declared #$d_n"
    return 1
  fi
  if [ "$n" != "$d_n" ]; then
    _prs_why="ONEX_GH_EXACT_HEAD: PR number $n does not match the declared #$d_n"
    return 1
  fi
  if [ "$have_repo" -ne 1 ]; then
    _prs_why="ONEX_GH_EXACT_HEAD: --repo is missing; declared $d_repo"
    return 1
  fi
  if [ "$repo" != "$d_repo" ]; then
    _prs_why="ONEX_GH_EXACT_HEAD: repo $repo does not match the declared $d_repo"
    return 1
  fi
  if [ "$have_json" -ne 1 ]; then
    _prs_why="ONEX_GH_EXACT_HEAD: --json is missing; an exact-head check names its fields"
    return 1
  fi
  if [ -z "$fields" ]; then
    _prs_why="ONEX_GH_EXACT_HEAD: --json names no fields"
    return 1
  fi
  set -f
  local old_ifs="$IFS"
  IFS=,
  for f in $fields; do
    case "$f" in
      headRefOid|headRefName|baseRefName|state|isDraft|mergedAt|mergeStateStatus|number|isCrossRepository) ;;
      *) bad="$f"; break ;;
    esac
  done
  IFS="$old_ifs"
  set +f
  if [ -n "$bad" ]; then
    _prs_why="ONEX_GH_EXACT_HEAD: field '$bad' is not allowed (allowed: headRefOid, headRefName, baseRefName, state, isDraft, mergedAt, mergeStateStatus, number, isCrossRepository)"
    return 1
  fi
  return 0
}

# Resolve the owner, repository and PR number a refused argv names, for the
# alternatives text. Sets _rs_owner, _rs_repo, _rs_n; each is "" when unresolved.
_prs_resolve() {
  _rs_owner=""; _rs_repo=""; _rs_n=""
  local a prev="" v="" u="" rest="" seen_pos=0 slot_n="" ep
  for a in "$@"; do
    case "$prev" in -R|--repo) v="$a" ;; esac
    case "$a" in --repo=*) v="${a#--repo=}" ;; esac
    prev="$a"
  done
  if [ -n "$v" ]; then
    _rs_repo="${v##*/}"
    case "$v" in */*) rest="${v%/*}"; _rs_owner="${rest##*/}" ;; esac
  fi
  if [ "${1:-}" = "api" ]; then
    ep="${_endpoint#https://api.github.com/}"; ep="${ep#/}"
    case "$ep" in
      repos/*/*)
        rest="${ep#repos/}"
        _rs_owner="${rest%%/*}"; rest="${rest#*/}"; _rs_repo="${rest%%/*}"
        case "$rest" in
          */pulls/[0-9]*) slot_n="${rest#*/pulls/}"; _rs_n="${slot_n%%[!0-9]*}" ;;
        esac ;;
    esac
  elif [ "${1:-}" = "pr" ]; then
    shift 2
    for a in "$@"; do
      case "$a" in
        http://*/pull/*|https://*/pull/*)
          u="${a#*://}"; u="${u#*/}"
          _rs_owner="${u%%/*}"; rest="${u#*/}"; _rs_repo="${rest%%/*}"; rest="${rest#*/}"
          slot_n="${rest#pull/}"; _rs_n="${slot_n%%[!0-9]*}"
          break ;;
        -*) ;;
        *[!0-9]*|"") ;;
        *) [ "$seen_pos" -eq 0 ] && { _rs_n="$a"; seen_pos=1; } ;;
      esac
    done
  fi
  if [ -z "$_rs_repo" ]; then
    _read_origin
    v="$_origin"
    case "$v" in */*) _rs_owner="${v%%/*}"; _rs_repo="${v#*/}" ;; esac
  fi
}

# Failing-job logs are not PR state: the watcher does not hold them and a lane that
# classifies a red has to read one (OMN-20436). Two shapes pass, and only these:
#   gh run view ... --log-failed|--log   with no --json, --jq or --template
#   gh api repos/<o>/<r>/actions/jobs/<digits>/logs   (the endpoint ends there, no "..")
_prs_job_log() {
  local a log=0
  shift 2
  for a in "$@"; do
    case "$a" in
      --log|--log-failed) log=1 ;;
      --json|--json=*|--jq|--jq=*|-q|--template|--template=*|-t) return 1 ;;
    esac
  done
  [ "$log" -eq 1 ]
}

_prs_job_log_endpoint() {
  local rest id
  case "$1" in
    *..*|*\?*|*#*) return 1 ;;
    repos/[!/]*/[!/]*/actions/jobs/*/logs)
      rest="${1#*/actions/jobs/}"
      id="${rest%/logs}"
      case "$id" in ""|*[!0-9]*) return 1 ;; esac
      return 0 ;;
  esac
  return 1
}

# One check run's or job's detail (OMN-20911): repos/<o>/<r>/check-runs/<digits>,
# optionally /annotations, and repos/<o>/<r>/actions/jobs/<digits> (the job's run id,
# steps and conclusion). The watcher holds each check's name, id and conclusion, not its
# output text, annotations or owning run, so these shapes go through the cached read
# gateway below, never raw.
_gw_check_run_endpoint() {
  local rest id
  case "$1" in *..*|*\?*|*#*) return 1 ;; repos/*) ;; *) return 1 ;; esac
  rest="${1#repos/}"
  [ -n "${rest%%/*}" ] || return 1
  rest="${rest#*/}"
  [ -n "${rest%%/*}" ] || return 1
  rest="${rest#*/}"
  case "$rest" in
    check-runs/*) id="${rest#check-runs/}"; id="${id%/annotations}" ;;
    actions/jobs/*) id="${rest#actions/jobs/}" ;;
    *) return 1 ;;
  esac
  case "$id" in ""|*[!0-9]*) return 1 ;; esac
  return 0
}

# One commit object (OMN-20960): repos/OmniNode-ai/<r>/commits/<40 lowercase hex>, nothing
# after the sha. onex_change_control's receipt-hardening hook resolves every receipt
# commit_sha with `gh api --include repos/<o>/<r>/commits/<sha>` and parses the status line,
# headers and body. A commit addressed by its full sha is immutable and carries no PR state.
# A short sha, a ref or branch, a listing, a query string or field, and /status, /check-runs,
# /pulls and every other sub-path are not this shape. $1 is the endpoint; the rest is argv,
# read again because _classify drops the query string from _endpoint.
_gw_commit_endpoint() {
  local ep="$1" rest name sha a raw=0
  shift
  case "$ep" in *..*|*\?*|*#*) return 1 ;; repos/OmniNode-ai/*/commits/*) ;; *) return 1 ;; esac
  rest="${ep#repos/OmniNode-ai/}"
  name="${rest%%/*}"
  sha="${rest#"$name"/commits/}"
  case "$name" in ""|*[!A-Za-z0-9._-]*) return 1 ;; esac
  [ "${#sha}" -eq 40 ] || return 1
  case "$sha" in *[!0-9a-f]*) return 1 ;; esac
  for a in "$@"; do
    case "$a" in
      -f|-F|--field|--raw-field|--input|--field=*|--raw-field=*|--input=*) return 1 ;;
      "$ep"|"/$ep"|"https://api.github.com/$ep") raw=1 ;;
    esac
  done
  [ "$raw" -eq 1 ]
}

# The published-board reader reads two shapes no local source holds: the publish-beta-board
# workflow's run list and one run's jobs, in the one repository named by ONEX_GH_BOARD_REPO
# (<owner>/<repo>) in ${XDG_CONFIG_HOME:-$HOME/.config}/omni/gh-gateway.env. The repository
# comes only from that file, never from the environment, so a lane cannot widen it; unset,
# the board shapes are refused like any other read. They are gateway shapes of the "board"
# kind: a short TTL and their own hourly budget, so the board read neither starves nor is
# starved by failing-job log reads. Any other workflow or repo stays refused (OMN-20911
# follow-up).
_gw_board_repo() {
  local conf="${XDG_CONFIG_HOME:-$HOME/.config}/omni/gh-gateway.env" line v repo=""
  [ -f "$conf" ] || return 1
  while IFS= read -r line || [ -n "$line" ]; do
    case "$line" in
      ONEX_GH_BOARD_REPO=*) _conf_strip_comment_into repo "${line#*=}" ;;
    esac
  done < "$conf"
  case "$repo" in
    ""|*[!A-Za-z0-9._/-]*|*/*/*|/*|*/|*..*) return 1 ;;
    */*) printf '%s' "$repo" ;;
    *) return 1 ;;
  esac
}
_gw_board_endpoint() {
  local p="$1" id repo
  case "$p" in *..*|*\?*|*#*) return 1 ;; esac
  repo="$(_gw_board_repo)" || return 1
  case "$p" in
    "repos/$repo/actions/workflows/publish-beta-board.yml/runs") return 0 ;;
    "repos/$repo/actions/runs/"*/jobs)
      id="${p#"repos/$repo/actions/runs/"}"; id="${id%/jobs}"
      case "$id" in ""|*[!0-9]*) return 1 ;; esac
      return 0 ;;
  esac
  return 1
}
# Is the argv in "$@" a gateway shape (a failing-job log, one job's or check run's detail,
# one commit object by its full sha, or one of the two published-board reads)? Every gateway shape names its owner and
# repository literally: a {owner}/{repo} placeholder resolves from GH_REPO or the working
# directory, which the cache key cannot see, so one cached answer could be served for
# another repository. A placeholder endpoint is therefore not a gateway shape.
_gw_kind=""
_gw_shape() {
  local ep
  if [ "$_cls" = "api" ]; then
    # GET only: a HEAD answer has no body, so it must never share a cache entry with a GET
    # (and no gateway consumer sends one).
    [ "$_method" = "GET" ] || return 1
    ep="${_endpoint#https://api.github.com/}"
    ep="${ep#/}"
    case "$ep" in *\{*|*\}*) return 1 ;; esac
    _prs_job_log_endpoint "$ep" && return 0
    _gw_check_run_endpoint "$ep" && return 0
    _gw_commit_endpoint "$ep" "$@" && return 0
    _gw_board_endpoint "$ep" && { _gw_kind=board; return 0; }
    return 1
  fi
  [ "$_cls" = "run view" ] && _prs_job_log "$@" && return 0
  return 1
}

_prs_guarded=0
_prs_ep=""
if [ "$_cls" = "api" ]; then
  if [ "$_method" = "GET" ] || [ "$_method" = "HEAD" ]; then
    _prs_ep="${_endpoint#https://api.github.com/}"
    _prs_ep="${_prs_ep#/}"
    case "$_prs_ep" in
      repos/*/*/pulls|repos/*/*/pulls/*) _prs_guarded=1 ;;
      */check-runs/*) _gw_check_run_endpoint "$_prs_ep" || _prs_guarded=1 ;;
      */check-runs*|*/check-suites*|*/commits/*/status|*/statuses*) _prs_guarded=1 ;;
      */actions/runs*|*/actions/jobs*)
        _prs_job_log_endpoint "$_prs_ep" || _gw_check_run_endpoint "$_prs_ep" \
          || _gw_board_endpoint "$_prs_ep" || _prs_guarded=1 ;;
    esac
  fi
else
  case "$_cls" in
    "pr view") _cacheable "$@" || _prs_guarded=1 ;;
    "pr checks") _prs_guarded=1 ;;
    "run view") _prs_job_log "$@" || _prs_guarded=1 ;;
  esac
fi
if [ "$_prs_guarded" -eq 1 ] && ! _prs_caller_allowed && ! _prs_exact_head "$@"; then
  if [ "$_cls" = "api" ]; then _prs_class="gh api $_method $_prs_ep"; else _prs_class="gh $_cls"; fi
  _prs_resolve "$@"
  _prs_o="${_rs_owner:-OmniNode-ai}"; _prs_r="${_rs_repo:-<repo>}"; _prs_n="${_rs_n:-<n>}"
  printf '%s\n' \
    "REFUSED (OMN-19856): $_prs_class is a PR-state read; GitHub is for mutations and the declared exact-head check only (RULING 2026-09-27T18:05:21Z)." >&2
  [ -n "$_prs_why" ] && printf '%s\n' "Declared exact-head check failed: $_prs_why" >&2
  printf '%s\n' \
    'Read it locally instead:' \
    "  python3 <omni plugin>/skills/merge-drain/scripts/pr_state_local.py --pr $_prs_o/$_prs_r#$_prs_n   (--json for the whole record, --status for the state file's age)" \
    "  git -C \$OMNI_HOME/$_prs_r log|diff origin/dev...   (files, diffs and history from the canonical clone)" \
    'The one GitHub read allowed is the exact-head check right before a mutation:' \
    '  ONEX_GH_EXACT_HEAD=<owner>/<repo>#<n> gh pr view <n> --repo <owner>/<repo> --json headRefOid,state,mergeStateStatus,isCrossRepository' >&2
  if [ -n "$_rs_repo" ] && [ -n "$_rs_n" ]; then
    printf '%s\n' \
      "  e.g. ONEX_GH_EXACT_HEAD=$_prs_o/$_prs_r#$_prs_n gh pr view $_prs_n --repo $_prs_o/$_prs_r --json headRefOid,state,mergeStateStatus,isCrossRepository" >&2
  fi
  _call_log 1 refused
  exit 1
fi
unset _prs_guarded _prs_ep _prs_class _prs_o _prs_r _prs_n _prs_why _rs_owner _rs_repo _rs_n

# --- lane read guard (OMN-20911) -------------------------------------------------
# RULING 2026-10-10T18:17:36Z, re-affirming RULING 2026-09-25T14:34:28Z: lanes read the
# canonical clones and the PR watcher, never GitHub; gh is for writes. The PR-state guard
# above covers PR, check and run state for every caller. This one covers every other read
# a lane can make: `gh api` GET/HEAD of any endpoint (contents, artifacts, commits, user,
# releases, ...), `gh api graphql` without a mutation, and every read verb (pr list|diff|
# status, run list|download|watch, repo view, issue view|list, release list|view, workflow
# list|view, pr checkout, variable get, gh status, ...).
#
# Fallback until the bus read path works end to end (ruling 2026-10-12T05:03:28Z: a gate
# whose replacement path does not work today falls back to the old path, logged, until
# the replacement proves out, then goes strict). Such a lane read is not refused: it goes
# through the cached read gateway below as the "fallback" kind (a 300 s cache, then one
# unit of the same hourly ONEX_GH_GATEWAY_BUDGET the other gateway shapes spend, so the
# landing controller's quota stays protected), and every such call is one call-log row
# with action `fallback` (lane, verb, endpoint). Only a spent budget refuses it, naming
# the budget. Strict mode returns per verb, read only from
# ${XDG_CONFIG_HOME:-$HOME/.config}/omni/gh-gateway.env, never from the environment:
#   ONEX_GH_LANE_READ_STRICT_<VERB>=1
# where <VERB> is the call's class upper-cased with spaces as "_" (API, API_GRAPHQL,
# PR_LIST, PR_DIFF, RUN_LIST, REPO_VIEW, ISSUE_VIEW, STATUS, ...). Unset, or any value but
# 1, is fallback. A strict verb is refused with the local readers named, as before.
# The read-strict switch (unenforced-rulings plan, unit W8): the same file's
#   ONEX_GH_LANE_READ_STRICT=1
# makes every lane read verb strict at once. It is OFF unless that line says 1, and it is
# flipped in its own change, only on a recorded replacement-success window (every lane read
# verb answered locally, zero fallback events). It does not reach the named consumers
# below, the gateway shapes, the sanctioned scripts, or any write.
#
# A lane context is a call made by an agent, decided by either, in this order:
#   (a) an ancestor process (up to 12 up) that is Claude Code, the Claude desktop app,
#       the Codex CLI or the ChatGPT/Codex app, or a process table ps cannot read; or
#   (b) an agent environment marker: CLAUDECODE, CLAUDE_CODE_SESSION_ID,
#       CLAUDE_CODE_ENTRYPOINT, ONEX_LANE, ONEX_LANE_ID, ONEX_AGENT_NAME, CLAUDE_AGENT_NAME,
#       CLAUDE_SUBAGENT_NAME, CODEX_THREAD_ID, CODEX_SANDBOX, CODEX_SANDBOX_NETWORK_DISABLED
#       or CODEX_MANAGED_BY_NPM (a marker only adds lane context; unsetting one removes none).
# Not a lane: launchd/cron automation and an operator terminal with neither.
#
# Still allowed in a lane context:
#   - every write (api POST/PATCH/PUT/DELETE, graphql mutation, pr create|edit|comment|
#     review|ready|merge|close, workflow run, run rerun|cancel, ...);
#   - the two cached harness PR-link shapes (_cacheable) and the declared exact-head check;
#   - `gh api rate_limit`, which GitHub does not count against any bucket;
#   - the gateway shapes (failing-job logs, one check run's detail, one commit object by its
#     full sha), served by the cached, per-hour-budgeted read gateway below;
#   - the allowed callers of the PR-state guard (the PR watcher, the landing controller's
#     own scripts), and a DIRECT parent that is one of the sanctioned read scripts:
#     pr-handoff/scripts/handoff.sh and handoff_row.sh (the handoff's PR-text read),
#     release-cut/scripts/cut_facts.sh, lab-rebuild-triage/scripts/read_receipt.sh and
#     trigger_for_sha.sh (lab-pass receipts live only in Actions artifacts), and the
#     advisory-job-gate pre-commit hook's scripts/advisory_job_gate.py (it reads the
#     repository's branch protection, which no clone holds, and runs only when a commit
#     touches a workflow file).
# The canonical clone sync uses git, not the API, and `gh auth git-credential` is local.
_lane_ctx_why=""
_lane_context() {
  _lane_ctx_why=""
  local v pid="$PPID" steps=0 info next comm
  # The process ancestry decides first, and the environment cannot change it: an agent
  # that unsets or blanks every marker below is still refused here, because the walk reads
  # the process table, not the environment (PPID is read-only in bash). The markers only
  # ever ADD lane context afterwards; no value of any variable removes it. The walk is
  # only as good as ps, so a process table this process cannot read about itself (a
  # sandbox that hides it, a missing or broken ps) counts as a lane: an unverifiable caller
  # fails closed. Threat model: this routes cooperative agents off the shared GitHub read
  # quota. A local process that bypasses the shim entirely (real gh by absolute path, a
  # token in its environment) is out of its reach and is tracked as OMN-20916.
  info="$(ps -o ppid= -o comm= -p "$$" 2>/dev/null)"
  if [ -z "${info//[[:space:]]/}" ]; then
    _lane_ctx_why="unreadable process ancestry"
    return 0
  fi
  while [ "$steps" -lt 12 ]; do
    case "$pid" in ""|*[!0-9]*) break ;; esac
    [ "$pid" -gt 1 ] || break
    info="$(ps -o ppid= -o comm= -p "$pid" 2>/dev/null)"
    info="${info#"${info%%[![:space:]]*}"}"
    [ -n "$info" ] || break
    next="${info%%[[:space:]]*}"
    comm="${info#"$next"}"
    comm="${comm#"${comm%%[![:space:]]*}"}"
    case "$comm" in
      claude|*/claude|*/claude/versions/*|*/Claude.app/*|codex|*/codex|codex-*|*/codex-*|*/CodexCLI.app/*|ChatGPT|*/ChatGPT|*/ChatGPT.app/*)
        _lane_ctx_why="ancestor process ${comm##*/}"
        return 0 ;;
    esac
    pid="$next"
    steps=$((steps + 1))
  done
  for v in CLAUDECODE CLAUDE_CODE_SESSION_ID CLAUDE_CODE_ENTRYPOINT ONEX_LANE ONEX_LANE_ID \
           ONEX_AGENT_NAME CLAUDE_AGENT_NAME CLAUDE_SUBAGENT_NAME CODEX_THREAD_ID CODEX_SANDBOX \
           CODEX_SANDBOX_NETWORK_DISABLED CODEX_MANAGED_BY_NPM; do
    if [ -n "${!v:-}" ]; then
      _lane_ctx_why="environment $v"
      return 0
    fi
  done
  return 1
}

# A graphql call whose query comes from a file (`-f query=@f`, `--input f`) is a write
# only when that file says so; anything unreadable (stdin included) counts as a read.
_graphql_file_mutation() {
  local a prev="" f=""
  for a in "$@"; do
    case "$prev" in
      -f|-F|--field|--raw-field) case "$a" in query=@*) f="${a#query=@}" ;; esac ;;
      --input) f="$a" ;;
    esac
    case "$a" in
      --field=query=@*|--raw-field=query=@*) f="${a#*=query=@}" ;;
      --input=*) f="${a#--input=}" ;;
    esac
    prev="$a"
  done
  [ -n "$f" ] && [ "$f" != "-" ] && [ -r "$f" ] && grep -q 'mutation' "$f" 2>/dev/null
}

_lane_is_read() {
  case "$_cls" in
    api) [ "$_method" = "GET" ] || [ "$_method" = "HEAD" ]; return $? ;;
    "api graphql")
      [ "$_method" = "POST" ] || return 1
      _graphql_file_mutation "$@" && return 1
      return 0 ;;
    "pr checkout"|"variable get") return 0 ;;
  esac
  [ "$_method" = "GET" ]
}

_lane_sanctioned_script() {
  local args
  _read_parent_args
  args="$_parent_args"
  [ -n "$args" ] || return 1
  case " $args " in
    *"/skills/pr-handoff/scripts/handoff.sh "*) return 0 ;;
    *"/skills/pr-handoff/scripts/handoff_row.sh "*) return 0 ;;
    *"/skills/release-cut/scripts/cut_facts.sh "*) return 0 ;;
    *"/skills/lab-rebuild-triage/scripts/read_receipt.sh "*) return 0 ;;
    *"/skills/lab-rebuild-triage/scripts/trigger_for_sha.sh "*) return 0 ;;
    *" scripts/advisory_job_gate.py "*|*"/scripts/advisory_job_gate.py "*) return 0 ;;
  esac
  return 1
}

# Is the lane read guard strict for this call's verb? Only gh-gateway.env decides.
_lane_read_strict() {
  local conf="${XDG_CONFIG_HOME:-$HOME/.config}/omni/gh-gateway.env" line key strict_value
  [ -f "$conf" ] || return 1
  _ascii_upper_into key "$_cls"
  key="${key// /_}"
  key="${key//[^A-Z0-9_]/}"
  [ -n "$key" ] || return 1
  key="ONEX_GH_LANE_READ_STRICT_$key"
  while IFS= read -r line || [ -n "$line" ]; do
    case "$line" in
      "$key"=*|ONEX_GH_LANE_READ_STRICT=*)
        _conf_strip_comment_into strict_value "${line#*=}"
        [ "$strict_value" = "1" ] && return 0 ;;
    esac
  done < "$conf"
  return 1
}

# The local readers a lane read is pointed at, on a strict refusal and a spent budget.
_lane_read_alternatives() {
  printf '%s\n' \
    'Read it locally instead:' \
    "  PR state, checks, reviews, mergeability: python3 <omni plugin>/skills/merge-drain/scripts/pr_state_local.py --pr ${_rs_owner:-OmniNode-ai}/$_lr_r#<n>   (--status for the state file's age; the same records are on the bus as onex.evt.omnimarket.pr-state-observed.v1)" \
    "  files, contents, diffs, commits, tags, history: git -C \$OMNI_HOME/$_lr_r show|log|diff origin/dev...   (the canonical clones, kept fetched by canonical-clone-sync)" \
    '  a failing-job log, one job'"'"'s run id and steps, one check run'"'"'s output: gh api repos/<o>/<r>/actions/jobs/<id>/logs, gh api repos/<o>/<r>/actions/jobs/<id>, gh api repos/<o>/<r>/check-runs/<id>[/annotations], gh run view <run> --log-failed; the job id is in the watcher record (ci.detail) and these are served by the cached read gateway with a per-hour budget; so is one commit object by its full 40-hex sha, gh api repos/<o>/<r>/commits/<sha> (the receipt-hardening hook proves a receipt commit_sha with it)' \
    'Writes (pr create|edit|comment|review, workflow run, run rerun, api POST/PATCH/PUT/DELETE, graphql mutation) are unaffected.' >&2
}

# --- logged fallback for named consumers (OMN-20911) -------------------------------
# RULING 2026-10-12T05:03:28Z: a gate whose replacement path does not work end to end
# today falls back to the old path with a logged fallback until the replacement proves
# out, and is then made strict. The consumers below make a GitHub call from inside a lane
# (a pre-commit hook or a lane-run script) and had no working replacement when the guards
# shipped, so each keeps its old call by name, decided on the DIRECT parent only (like
# _lane_sanctioned_script), never on the environment:
#   enforcement-surface-placement  onex_change_control's placement pre-commit hook
#                                   (check-platform-leads-review-tripwire) reads live
#                                   branch protection, which no clone holds;
#   worktree-prune                  scripts/prune-worktrees.sh, merged-PR limb (gh pr list);
#   worktree-auto-prune             scripts/worktree_auto_prune.py, merged-PR limb;
#   bulk-pr-throttle                omnibase_infra scripts/ci/bulk_pr_throttle.py, the
#                                   allow_auto_merge repository read;
#   workflow-run                    `gh workflow run` from a lane (lane write guard below):
#                                   its replacement, onex scm workflow-run, fails on the
#                                   bus terminal subscribe.
# Every use appends one FRICTION row (gate, consumer, the call it fell back to) to
# $ONEX_STATE_DIR/friction/gh-lane-fallback.rows, else to the gh-usage cache directory.
# A use that cannot be recorded is refused like any other lane read: an uncounted
# fallback could never be proven unused. Making a consumer strict again is deleting its
# line here once its row count stays at zero.
_fb_consumer=""
_fb_match() {
  _fb_consumer=""
  local args
  _read_parent_args
  args="$_parent_args"
  [ -n "$args" ] || return 1
  case " $args " in
    *"/check-platform-leads-review-tripwire "*|*" check-platform-leads-review-tripwire "*|\
    *"/check_platform_leads_review_tripwire.py "*)
      _fb_consumer="enforcement-surface-placement" ;;
    *"/prune-worktrees.sh "*|*" prune-worktrees.sh "*) _fb_consumer="worktree-prune" ;;
    *"/worktree_auto_prune.py "*|*" worktree_auto_prune.py "*) _fb_consumer="worktree-auto-prune" ;;
    *"/bulk_pr_throttle.py "*|*" bulk_pr_throttle.py "*) _fb_consumer="bulk-pr-throttle" ;;
    *) return 1 ;;
  esac
  return 0
}

# _fb_record <gate> <consumer> <the call it fell back to> <replacement that does not work>
_fb_record() {
  local dir file ts
  if [ -n "${ONEX_STATE_DIR:-}" ]; then
    dir="$ONEX_STATE_DIR/friction"
  else
    dir="${XDG_CACHE_HOME:-$HOME/.cache}/omni/gh-usage"
  fi
  file="$dir/gh-lane-fallback.rows"
  mkdir -p "$dir" 2>/dev/null || return 1
  _resolve_lane
  _resolve_parent_host
  ts="$(date -u +%Y-%m-%dT%H:%M:%SZ)"
  printf '%s | FRICTION | lane=%s | ticket=OMN-20911 | gate=%s | consumer=%s | fallback=%s | host=%s | cost=~1 lane-minutes | logged fallback (RULING 2026-10-12T05:03:28Z): %s used the old gh path because its replacement (%s) does not work end to end yet; the gate goes strict for it when this consumer has no row\n' \
    "$ts" "$(_clean "$_lane")" "$(_clean "$1")" "$(_clean "$2")" "$(_clean "$3")" \
    "$_lane_host" "$(_clean "$2")" "$(_clean "$4")" >> "$file" 2>/dev/null || return 1
  _fb_file="$file"
  return 0
}

_gw=0
_gw_shape "$@" && _gw=1
if [ "$_gw" -eq 0 ] && _lane_is_read "$@" && ! _cacheable "$@" \
   && [ "${_endpoint#/}" != "rate_limit" ] \
   && ! _prs_exact_head "$@" && ! _prs_caller_allowed \
   && _lane_context && ! _lane_sanctioned_script; then
  if [ "$_cls" = "api" ]; then _lr_class="gh api $_method ${_endpoint:--}"; else _lr_class="gh $_cls"; fi
  if _fb_match && _fb_record gh-lane-read-guard "$_fb_consumer" "$_lr_class" "a lane-local reader"; then
    printf '%s\n' \
      "FALLBACK (OMN-20911): $_lr_class from a lane ($_lane_ctx_why) is allowed for the named consumer $_fb_consumer until its replacement works; this use is recorded in $_fb_file." >&2
  else
    _prs_resolve "$@"
    _lr_r="${_rs_repo:-<repo>}"
    if ! _lane_read_strict; then
      # Fallback: the cached read gateway below serves it, counts it and logs it.
      _gw=1
      _gw_kind=fallback
    else
      printf '%s\n' \
        "REFUSED (OMN-20911): $_lr_class is a GitHub read from a lane ($_lane_ctx_why). Lanes do not read GitHub; gh is for writes (RULING 2026-10-10T18:17:36Z, re-affirming RULING 2026-09-25T14:34:28Z). This verb is strict in gh-gateway.env." >&2
      _lane_read_alternatives
      _refusal_row gh_shim_lane_read_guard lane-github-read-via-gh-shim "REFUSED (OMN-20911): $_lr_class is a GitHub read from a lane ($_lane_ctx_why)"
      _call_log 1 refused
      exit 1
    fi
  fi
fi
[ "$_gw_kind" = "fallback" ] || unset _lr_class _lr_r _rs_owner _rs_repo _rs_n


# Run one gh call and leave its routing identity/reason in _route. With routing
# disabled this is deliberately the same single command as the old shim path.
_run_gh() {
  _route=""
  if [ "${ONEX_GH_READ_ROUTING:-}" != "1" ]; then
    "$real" "$@"
    return $?
  fi

  # A candidate is only ever "worth asking the router about" -- gh_route.py's own
  # classify() is the one place that decides read vs not (mutation, viewer-resolving,
  # non-OmniNode-ai owner, unscoped search all still land on the operator there), so
  # widening this set is safe: it was narrower than what the router actually
  # classifies as a read (OMN-19852 P2 -- `gh search`, `repo view`, `issue view|list`,
  # `pr diff` and `api graphql` reads were silently running on the operator, on this
  # host and everywhere else the shim is installed, because they never reached the
  # router at all).
  local candidate=0 router="" py="" rf="" rc=0
  if [ "$_cls" = "api" ] && { [ "$_method" = "GET" ] || [ "$_method" = "HEAD" ]; }; then
    candidate=1
  else
    case "$_cls" in
      "pr view"|"pr list"|"pr checks"|"pr diff"|"run view"|"run list"|"repo view"|"issue view"|"issue list") candidate=1 ;;
      "search "*) candidate=1 ;;
    esac
  fi
  if [ "$candidate" -ne 1 ]; then
    "$real" "$@"
    rc=$?
    _route="operator shim-not-a-read"
    return "$rc"
  fi

  if [ -n "${ONEX_GH_ROUTER:-}" ]; then
    router="$ONEX_GH_ROUTER"
  else
    router="$(cd "$(dirname "$self")" 2>/dev/null && pwd)/gh_route.py"
  fi
  # The router is stdlib-only and makes no network connection itself (the
  # real gh and the mint command do), so any python3 on PATH can run it;
  # python3.13 first because that is the project interpreter.
  if [ -n "${ONEX_GH_ROUTE_PYTHON:-}" ]; then
    py="$ONEX_GH_ROUTE_PYTHON"
  else
    py="$(command -v python3.13 2>/dev/null)"
    [ -n "$py" ] || py="$(command -v python3 2>/dev/null)"
  fi
  if [ ! -f "$router" ] || [ ! -r "$router" ] || [ -z "$py" ] || [ ! -x "$py" ]; then
    "$real" "$@"
    rc=$?
    _route="operator-fallback router-unavailable"
    return "$rc"
  fi
  rf="$(mktemp "${TMPDIR:-/tmp}/onex-gh-route.XXXXXX" 2>/dev/null)"
  if [ -z "$rf" ]; then
    "$real" "$@"
    rc=$?
    _route="operator-fallback router-unavailable"
    return "$rc"
  fi
  _resolve_lane
  ONEX_LANE="$_lane" "$py" "$router" exec --result-file "$rf" -- "$@"
  rc=$?
  IFS= read -r _route < "$rf" || true
  rm -f "$rf" 2>/dev/null
  if [ -z "$_route" ] && [ "$rc" -ne 0 ]; then
    "$real" "$@"
    rc=$?
    _route="operator-fallback router-failed"
  fi
  return "$rc"
}

# --- merge-queue bypass guard (OMN-17427) -------------------------------------
# omnibase_infra#4197 was pulled from the dev merge queue for failed checks at
# 14:15:03Z on 2026-09-28 and then landed anyway by a raw REST PUT merge at
# 14:27:17Z: the merge-drain workflow's own general rule told the land lane to
# do exactly that ("Merges by REST squash on the exact head: gh api -X PUT
# .../pulls/<n>/merge"), with no carve-out for a queue-protected branch, while
# a second, repo-specific instruction a few lines later in the same prompt said
# "never a REST merge". A prompt-text fix (repo_drains.js, this same ticket)
# removes that contradiction, but a land lane is an LLM reading a prompt, and a
# text rule is advice, not a control. This is the mechanical stop that holds
# regardless of what any prompt says: it resolves the merge-queue rule LIVE for
# the EXACT repo+branch a merge call targets -- never a hardcoded repo list, so
# a queue ruleset added to a second repo tomorrow is covered with no code
# change here -- and refuses the two shapes that bypass a queue: a raw
# `gh api ... -X PUT pulls/<n>/merge`, and `gh pr merge ... --admin`. A bare
# `gh pr merge` naming neither `--match-head-commit` nor `--auto` is also
# refused on a queue branch: those two flags are the only forms every sanctioned
# caller in this codebase uses (merge-drain SKILL.md, repo_drains.js,
# arm_green_prs.py), so an invocation carrying neither is unverified, not
# merely unusual, and this guard's own fail-closed rule (below) treats it the
# same as a call it could not resolve at all.
#
# Fail-closed, narrowly: only these two risky shapes are ever evaluated (a
# read, a safe enqueue-form merge, and everything that is not `pr merge` or a
# `pulls/.../merge` PUT never reaches this block at all, so an API hiccup here
# can never brick unrelated gh traffic). Once a call IS one of the two risky
# shapes, an unresolvable repo, PR number, base branch or rules read is BLOCKED
# rather than assumed safe -- CLAUDE.md rule 16: an unverified merge-queue
# status is never treated as "no queue". The one-line remedy on a false-positive
# block is always available and always safe: retry with the sanctioned enqueue
# form, `gh pr merge <n> --repo <owner>/<repo> --squash --match-head-commit
# <head>`.
_mq_is_rest_put=0
_mq_is_merge_call=0
_mq_admin=0
_mq_safe_flag=0
_mq_repo=""
_mq_pr_num=""
if [ "${1:-}" = "pr" ] && [ "${2:-}" = "merge" ]; then
  _mq_is_merge_call=1
  case "${3:-}" in ''|-*) ;; *) _mq_pr_num="$3" ;; esac
  _mq_prev=""
  for _mq_a in "$@"; do
    case "$_mq_prev" in -R|--repo) _mq_repo="$_mq_a" ;; esac
    case "$_mq_a" in
      --repo=*) _mq_repo="${_mq_a#--repo=}" ;;
      --admin) _mq_admin=1 ;;
      --match-head-commit|--auto) _mq_safe_flag=1 ;;
    esac
    _mq_prev="$_mq_a"
  done
  if [ -z "$_mq_repo" ]; then _read_origin; _mq_repo="$_origin"; fi
elif [ "$_cls" = "api" ] && [ "$_method" = "PUT" ]; then
  case "$_endpoint" in
    repos/*/pulls/*/merge)
      _mq_is_rest_put=1
      _mq_repo="${_endpoint#repos/}"; _mq_repo="${_mq_repo%%/pulls/*}"
      _mq_pr_num="${_endpoint#repos/*/pulls/}"; _mq_pr_num="${_mq_pr_num%%/merge}"
      ;;
  esac
fi

if [ "$_mq_is_rest_put" -eq 1 ] || { [ "$_mq_is_merge_call" -eq 1 ] && { [ "$_mq_admin" -eq 1 ] || [ "$_mq_safe_flag" -eq 0 ]; }; }; then
  _mq_shape="gh api -X PUT .../pulls/<n>/merge"
  if [ "$_mq_is_merge_call" -eq 1 ]; then
    _mq_shape="gh pr merge"
    [ "$_mq_admin" -eq 1 ] && _mq_shape="$_mq_shape --admin"
    if [ "$_mq_safe_flag" -eq 0 ] && [ "$_mq_admin" -eq 0 ]; then
      _mq_shape="$_mq_shape (neither --match-head-commit nor --auto)"
    fi
  fi
  _mq_branch=""
  if [ -n "$_mq_repo" ] && [ -n "$_mq_pr_num" ]; then
    _mq_branch="$("$real" pr view "$_mq_pr_num" --repo "$_mq_repo" --json baseRefName --jq .baseRefName 2>/dev/null)"
  fi
  _mq_gated=-1  # -1 unresolved (fail closed), 0 no queue rule, 1 queue rule present
  if [ -n "$_mq_repo" ] && [ -n "$_mq_branch" ]; then
    _mq_rules="$("$real" api "repos/$_mq_repo/rules/branches/$_mq_branch" 2>/dev/null)"
    if [ -n "$_mq_rules" ]; then
      case "$_mq_rules" in
        *'"type":"merge_queue"'*|*'"type": "merge_queue"'*) _mq_gated=1 ;;
        *) _mq_gated=0 ;;
      esac
    fi
  fi
  if [ "$_mq_gated" -ne 0 ]; then
    _mq_reason="repo=${_mq_repo:-<unresolved>} pr=${_mq_pr_num:-<unresolved>} base=${_mq_branch:-<unresolved>}"
    if [ "$_mq_gated" -eq 1 ]; then
      _mq_why="BLOCKED (OMN-17427): $_mq_shape bypasses the merge_queue rule on $_mq_reason. This is the queue's own rulesets API answer (repos/$_mq_repo/rules/branches/$_mq_branch), read live just now -- not a guess. The only sanctioned landing verb on a queue-protected branch is: gh pr merge $_mq_pr_num --repo $_mq_repo --squash --match-head-commit <head>  (this enqueues rather than merging, and still exits 0 -- read back mergedAt/mergeQueueEntry before calling it merged). A PR the queue dequeued for failed checks is RED, not merged: fix the cause and re-push, or leave it blocked. Never retry this exact call."
    else
      _mq_why="BLOCKED (OMN-17427): $_mq_shape could not be confirmed safe -- $_mq_reason, and the merge-queue rules read (repos/${_mq_repo:-<unresolved>}/rules/branches/${_mq_branch:-<unresolved>}) did not return a usable answer (network, auth, an unresolved PR/base, or a real API error). An unverified merge-queue status is never treated as 'no queue' (CLAUDE.md rule 16). Retry with the sanctioned enqueue form instead, which is safe on every branch whether or not it is queue-protected: gh pr merge <n> --repo <owner>/<repo> --squash --match-head-commit <head>  -- or resolve the read failure and retry this exact call."
    fi
    printf '%s\n' "$_mq_why" >&2
    _mq_log_dir="${XDG_CACHE_HOME:-$HOME/.cache}/omni/gh-usage"
    mkdir -p "$_mq_log_dir" 2>/dev/null || true
    printf '{"ts":"%s","guard":"merge_queue_bypass","gated":%s,"shape":"%s","repo":"%s","pr":"%s","base":"%s","pid":%s}\n' \
      "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$_mq_gated" "$(_clean "$_mq_shape")" "$(_clean "${_mq_repo:-}")" "$(_clean "${_mq_pr_num:-}")" "$(_clean "${_mq_branch:-}")" "$$" \
      >> "$_mq_log_dir/merge-queue-guard.jsonl" 2>/dev/null || true
    _call_log 1 refused
    exit 1
  fi
fi
unset _mq_a _mq_prev _mq_shape _mq_reason _mq_why _mq_rules _mq_log_dir


# --- cached read gateway (OMN-20911) ---------------------------------------------
# The gateway shapes (_gw_shape: a failing-job log, one check run's detail, one commit object) reach GitHub
# only through here, for every caller but the PR-state guard's allowed callers. A hit is
# served from ${XDG_CACHE_HOME:-$HOME/.cache}/omni/gh-shim/gateway (a finished job's log
# and a completed check run do not change); a miss spends one unit of this host's hourly
# budget, and a spent budget refuses until the next UTC hour. TTL and budget come only
# from ${XDG_CONFIG_HOME:-$HOME/.config}/omni/gh-gateway.env (ONEX_GH_GATEWAY_TTL, default
# 21600 s; ONEX_GH_GATEWAY_BUDGET, default 60 misses an hour), never from the environment,
# so a lane cannot raise its own budget. Only a successful answer is cached.
# A lane read the lane read guard let through (_gw_kind=fallback) is held for at most
# 300 s, keyed also on GH_REPO and the origin remote (a verb with no --repo reads the
# working directory's repository), and logged with action `fallback`. A fallback read
# that acts or streams locally (pr checkout, run download|watch, release download,
# browse) or reads its query from a file is never cached: it spends a unit and runs.
# The bus gateway (OMN-17427 plan) replaces this host-local cache.
if [ "$_gw" -eq 1 ] && ! _prs_caller_allowed; then
  _gw_ttl=21600
  _gw_budget=60
  _gw_conf="${XDG_CONFIG_HOME:-$HOME/.config}/omni/gh-gateway.env"
  if [ -f "$_gw_conf" ]; then
    while IFS= read -r _line || [ -n "$_line" ]; do
      _conf_strip_comment_into _conf_v "${_line#*=}"
      case "$_conf_v" in ""|*[!0-9]*) continue ;; esac
      case "$_line" in
        ONEX_GH_GATEWAY_TTL=*) _gw_ttl="$_conf_v" ;;
        ONEX_GH_GATEWAY_BUDGET=*) _gw_budget="$_conf_v" ;;
      esac
    done < "$_gw_conf"
  fi
  _gw_hour_tag=""
  if [ "$_gw_kind" = "board" ]; then
    _gw_ttl=300
    _gw_budget=60
    _gw_hour_tag="-board"
  fi
  _gw_action=allowed
  _gw_nocache=0
  if [ "$_gw_kind" = "fallback" ]; then
    _gw_action=fallback
    [ "$_gw_ttl" -gt 300 ] && _gw_ttl=300
    case "$_cls" in
      "pr checkout"|"run download"|"run watch"|"release download"|browse) _gw_nocache=1 ;;
    esac
    for _gw_a in "$@"; do
      case "$_gw_a" in *=@*|--input|--input=*) _gw_nocache=1 ;; esac
    done
  fi
  _gw_dir="${XDG_CACHE_HOME:-$HOME/.cache}/omni/gh-shim/gateway"
  _gw_refuse() {
    printf '%s\n' "REFUSED (OMN-20911): the cached read gateway $*" >&2
    _call_log 1 refused
    exit 1
  }
  # mkdir -p exits 0 on an existing directory it cannot write, so a budget directory left
  # read-only passed the check above and every read was refused at the append below as a
  # file fault (OMN-19998). A path this user owns gets its owner write bit back; anything
  # else still refuses, naming the path, its mode and owner, and this uid.
  _gw_hour_file="$_gw_dir/budget/$(date -u +%Y%m%d%H)$_gw_hour_tag"
  for _gw_path in "$_gw_dir/budget" "$_gw_hour_file"; do
    [ ! -w "$_gw_path" ] && [ -O "$_gw_path" ] && chmod u+rwX "$_gw_path" 2>/dev/null || true
  done
  _gw_desc() { ls -ld "$1" 2>/dev/null | awk '{print $1" owner "$3}'; }
  if ! mkdir -p "$_gw_dir/budget" 2>/dev/null || [ ! -w "$_gw_dir/budget" ]; then
    _gw_refuse "cannot create or write its cache and budget directory $_gw_dir/budget ($(_gw_desc "$_gw_dir/budget"); this is uid $(id -u)), so it cannot count this read against the hourly budget; fix the directory rather than read uncounted."
  fi
  _gw_scope="${GH_HOST:-github.com}|${_method:-GET}"
  if [ "$_cls" = "run view" ] || [ "$_gw_kind" = "fallback" ]; then _read_origin; fi
  [ "$_cls" = "run view" ] && _gw_scope="$_gw_scope|$_origin"
  [ "$_gw_kind" = "fallback" ] && _gw_scope="$_gw_scope|${GH_REPO:-}|$_origin"
  # `gh run view <run> --log-failed` with no --attempt or --job reads the latest attempt,
  # which a rerun replaces, so that answer is held for at most five minutes. A job id and
  # an explicit attempt name one finished attempt and keep the full TTL.
  if [ "$_cls" = "run view" ] && [ "$_gw_ttl" -gt 300 ]; then
    _gw_pinned=0
    for _gw_a in "$@"; do
      case "$_gw_a" in --attempt|--attempt=*|-a|--job|--job=*|-j) _gw_pinned=1 ;; esac
    done
    [ "$_gw_pinned" -eq 1 ] || _gw_ttl=300
  fi
  _gw_entry="$_gw_dir/$(_sha "$_gw_scope|$(printf '%s\037' "$@")")"
  _now="$(date +%s)"
  if [ $(( $$ % 50 )) -eq 0 ]; then
    find "$_gw_dir" -type f -mmin +2880 -delete 2>/dev/null
  fi
  if [ "$_gw_nocache" -eq 0 ] && [ -f "$_gw_entry.meta" ]; then
    read -r _gw_at < "$_gw_entry.meta"
    case "$_gw_at" in
      ""|*[!0-9]*) ;;
      *)
        if [ $((_now - _gw_at)) -lt "$_gw_ttl" ]; then
          cat "$_gw_entry.out" 2>/dev/null
          _log 0 hit "$_gw_action"
          exit 0
        fi ;;
    esac
  fi
  # Claim the unit first, then count: each claim is one short O_APPEND line, so two
  # concurrent misses can never both read a count below the budget and both proceed (no
  # check-then-act window). A refused claim stays counted, which only over-counts the hour.
  if ! { printf '%s\n' "$$" >> "$_gw_hour_file"; } 2>/dev/null; then
    _gw_refuse "cannot record this read in its budget file $_gw_hour_file (it is $(_gw_desc "$_gw_hour_file"); budget directory $(_gw_desc "$_gw_dir/budget"); this is uid $(id -u)): a path permission, full disk or sandbox write failure; fix the file rather than read uncounted."
  fi
  _gw_spent="$({ wc -l < "$_gw_hour_file"; } 2>/dev/null | tr -d '[:space:]')"
  case "$_gw_spent" in ""|*[!0-9]*) _gw_spent="$((_gw_budget + 1))" ;; esac
  if [ "$_gw_spent" -gt "$_gw_budget" ] && [ "$_gw_kind" = "fallback" ]; then
    printf '%s\n' \
      "REFUSED (OMN-20911): $_lr_class is a GitHub read from a lane ($_lane_ctx_why) and this host's lane read fallback budget is spent: ONEX_GH_GATEWAY_BUDGET=$_gw_budget GitHub reads for this UTC hour (gh-gateway.env, shared with the cached read gateway), $_gw_spent claimed; it refills at the next hour. Answers already fetched in the last 300 s are served from the cache." >&2
    _lane_read_alternatives
    _refusal_row gh_shim_lane_read_guard lane-github-read-via-gh-shim "REFUSED (OMN-20911): $_lr_class is a GitHub read from a lane ($_lane_ctx_why); lane read fallback budget ONEX_GH_GATEWAY_BUDGET=$_gw_budget spent"
    _call_log 1 refused
    exit 1
  fi
  if [ "$_gw_spent" -gt "$_gw_budget" ]; then
    _gw_refuse "has spent this host's budget of $_gw_budget GitHub reads for this UTC hour ($_gw_budget used); it refills at the next hour.
Read what you can locally meanwhile: the PR watcher state (pr_state_local.py --pr <owner>/<repo>#<n>) names every check run and its conclusion; answers already fetched this hour are served from the cache."
  fi
  if [ "$_gw_nocache" -eq 1 ]; then
    _run_gh "$@"
    _rc=$?
    _log "$_rc" none "$_gw_action"
    exit "$_rc"
  fi
  _gw_tmp="$_gw_entry.tmp.$$"
  _run_gh "$@" > "$_gw_tmp.out" 2> "$_gw_tmp.err"
  _rc=$?
  cat "$_gw_tmp.out"
  cat "$_gw_tmp.err" >&2
  if [ "$_rc" -eq 0 ]; then
    mv -f "$_gw_tmp.out" "$_gw_entry.out" 2>/dev/null
    printf '%s\n' "$_now" > "$_gw_tmp.meta" 2>/dev/null \
      && mv -f "$_gw_tmp.meta" "$_gw_entry.meta" 2>/dev/null
  fi
  rm -f "$_gw_tmp.out" "$_gw_tmp.err" "$_gw_tmp.meta" 2>/dev/null
  _log "$_rc" miss "$_gw_action"
  exit "$_rc"
fi

# --- lane write guard (OMN-20914) -----------------------------------------------
# RULING 2026-10-10T18:32:46Z: GitHub access moves onto the source-control nodes and gh
# CLI access is turned off for sub-agents, so lanes drive everything through the node
# and remember nothing. From a lane, a gh write that `onex scm` serves is refused (exit 1,
# the real gh never runs) and the refusal names the `onex scm` verb that replaces it.
#
# Coverage table: the `operations` block of node_github_repo_write_effect's contract.yaml
# in the omnimarket the `onex` command runs, the first
# ${ONEX_DISPATCH_VENV:-$OMNI_HOME/.onex-dispatch-venv}/lib/python*/site-packages/omnimarket
# (scripts/onex in omnibase_infra resolves the same venv). `onex scm` reads that block too
# (contract_operations), and omnimarket's own test binds every operation to exactly one
# verb. A call is covered only when all of these hold; otherwise it passes unchanged:
#   - an operation's description says "replaces gh <group> <sub>." and the call is that verb;
#   - the same install's onex scm table (handlers/scm/handler_scm_dispatch.py) serves
#     verb="<group>-<sub>" replacing "gh <group> <sub>" (an install from before the command
#     has the contract and no command, and refuses nothing);
#   - write_config puts the call's repository (--repo, a PR URL, else the origin remote) in
#     enforce mode: in dry_run the node plans the write and sends nothing. A
#     github_mode_by_repository row wins over its owner's github_mode_by_owner row, which
#     wins over github_mode (the contract's own precedence).
# So `gh pr merge`, `gh run rerun|cancel` and `gh api` with a non-GET method stay allowed:
# onex scm has no operation for them (it refuses merge, arm, rerun and update-branch,
# naming the landing controller).
#
# A lane is a call carrying a lane marker of node_lane_github_read_guard_effect (ONEX_LANE,
# ONEX_LANE_ID, ONEX_AGENT_NAME, CLAUDE_AGENT_NAME, CLAUDE_SUBAGENT_NAME and the CODEX_*
# markers) or a headless Claude Code entrypoint (CLAUDE_CODE_ENTRYPOINT=sdk-*). The
# operator's foreground shell and interactive session carry neither and pass.
# Allowed whatever the environment, decided on the direct parent only (as the PR-state
# guard's allowed callers are): ONEX_PR_WATCHER=1, the PR watcher module and the landing
# controller's own scripts (_prs_caller_allowed), the node effect runner (`onex run-node`,
# onex-runtime, omnibase_infra.runtime.kernel) and the release-cut tick
# (any package's omnimarket_release_cut_tick module).
# The refusal is a call-log row: class = the gh verb, endpoint = the onex scm verb.
_lw_why=""
_lw_lane() {
  _lw_why=""
  local v
  for v in ONEX_LANE ONEX_LANE_ID ONEX_AGENT_NAME CLAUDE_AGENT_NAME CLAUDE_SUBAGENT_NAME \
           CODEX_THREAD_ID CODEX_SANDBOX CODEX_SANDBOX_NETWORK_DISABLED CODEX_MANAGED_BY_NPM; do
    if [ -n "${!v:-}" ]; then
      _lw_why="environment $v"
      return 0
    fi
  done
  case "${CLAUDE_CODE_ENTRYPOINT:-}" in
    sdk-*) _lw_why="headless entrypoint $(_clean "$CLAUDE_CODE_ENTRYPOINT")"; return 0 ;;
  esac
  return 1
}

_lw_allowed_identity() {
  _prs_caller_allowed && return 0
  local args
  _read_parent_args
  args="$_parent_args"
  [ -n "$args" ] || return 1
  case " $args " in
    *"/onex run-node "*|*" onex run-node "*) return 0 ;;
    *"/onex-runtime "*|*" onex-runtime "*|*" omnibase_infra.runtime.kernel "*) return 0 ;;
    *".omnimarket_release_cut_tick "*) return 0 ;;
  esac
  return 1
}

# Sets _lw_scm (the onex scm verb) and _lw_op (the node operation) when the call is a
# covered write; returns 1 otherwise. Reads files only for a non-api write verb.
_lw_covered() {
  _lw_scm=""; _lw_op=""
  [ "$_method" = "WRITE" ] || return 1
  case "$_cls" in *" "*) ;; *) return 1 ;; esac
  local venv="${ONEX_DISPATCH_VENV:-}" pkg="" d contract dispatch table kind k v
  local op="" mode="" repo_mode="" owner_mode="" target="" owner=""
  if [ -z "$venv" ]; then
    [ -n "${OMNI_HOME:-}" ] || return 1
    venv="$OMNI_HOME/.onex-dispatch-venv"
  fi
  for d in "$venv"/lib/python*/site-packages/omnimarket; do
    [ -d "$d" ] && { pkg="$d"; break; }
  done
  [ -n "$pkg" ] || return 1
  contract="$pkg/nodes/node_github_repo_write_effect/contract.yaml"
  dispatch="$pkg/handlers/scm/handler_scm_dispatch.py"
  [ -r "$contract" ] && [ -r "$dispatch" ] || return 1
  # One line per operation ("op<TAB><name><TAB><group sub>") and per mode ("default<TAB>
  # <mode>", "repo<TAB><owner/repo><TAB><mode>", "owner<TAB><owner><TAB><mode>"), from the
  # two top-level blocks only.
  table="$(awk '
    /^[^[:space:]#]/ { sect = $1; sub_sect = "" }
    sect == "write_config:" && /^  [A-Za-z0-9_]+:/ {
      sub_sect = $1
    }
    sect == "write_config:" && sub_sect == "github_mode_by_owner:" \
      && /^[[:space:]][[:space:]][[:space:]]+[A-Za-z0-9_.-]+:/ {
      k = $0; sub(/^[[:space:]]+/, "", k); m = k; sub(/:.*/, "", k)
      sub(/^[^:]*:[[:space:]]*/, "", m); gsub(/["[:space:]]/, "", m)
      printf "owner\t%s\t%s\n", k, m; next
    }
    sect == "operations:" && /^[[:space:]]*-[[:space:]]*name:/ {
      op = $0; sub(/^[^:]*:[[:space:]]*/, "", op); gsub(/["[:space:]]/, "", op); next
    }
    sect == "operations:" && /^[[:space:]]*description:/ && op != "" {
      if (match($0, /replaces gh [a-z]+ [a-z]+\./)) {
        printf "op\t%s\t%s\n", op, substr($0, RSTART + 12, RLENGTH - 13)
      }
      op = ""; next
    }
    sect == "write_config:" && /^[[:space:]]+github_mode:/ {
      m = $0; sub(/^[^:]*:[[:space:]]*/, "", m); gsub(/["[:space:]]/, "", m)
      printf "default\t%s\n", m; next
    }
    sect == "write_config:" && /^[[:space:]]+[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+:/ {
      k = $0; sub(/^[[:space:]]+/, "", k); m = k; sub(/:.*/, "", k)
      sub(/^[^:]*:[[:space:]]*/, "", m); gsub(/["[:space:]]/, "", m)
      printf "repo\t%s\t%s\n", k, m; next
    }
  ' "$contract" 2>/dev/null)"
  [ -n "$table" ] || return 1
  _prs_resolve "$@"
  [ -n "$_rs_owner" ] && [ -n "$_rs_repo" ] && \
    target="$(printf '%s/%s' "$_rs_owner" "$_rs_repo" | tr '[:upper:]' '[:lower:]')" && \
    owner="${target%%/*}"
  while IFS="$(printf '\t')" read -r kind k v; do
    case "$kind" in
      op) [ "$v" = "$_cls" ] && op="$k" ;;
      default) mode="$k" ;;
      repo)
        if [ -n "$target" ] && \
           [ "$(printf '%s' "$k" | tr '[:upper:]' '[:lower:]')" = "$target" ]; then
          repo_mode="$v"
        fi ;;
      owner)
        if [ -n "$owner" ] && \
           [ "$(printf '%s' "$k" | tr '[:upper:]' '[:lower:]')" = "$owner" ]; then
          owner_mode="$v"
        fi ;;
    esac
  done <<EOF_LW
$table
EOF_LW
  [ -n "$op" ] || return 1
  [ "${repo_mode:-${owner_mode:-$mode}}" = "enforce" ] || return 1
  v="${_cls% *}-${_cls#* }"
  grep -qF "verb=\"$v\"" "$dispatch" 2>/dev/null || return 1
  grep -qF "replaces=\"gh $_cls\"" "$dispatch" 2>/dev/null || return 1
  _lw_scm="$v"; _lw_op="$op"
  return 0
}

if [ "$_method" = "WRITE" ] && _lw_lane && _lw_covered "$@" && ! _lw_allowed_identity \
   && ! { [ "$_cls" = "workflow run" ] \
          && _fb_record gh-lane-write-guard workflow-run "gh $_cls" "onex scm $_lw_scm" \
          && printf '%s\n' "FALLBACK (OMN-20911): gh $_cls from a lane ($_lw_why) is allowed until onex scm $_lw_scm works end to end; this use is recorded in $_fb_file." >&2; }; then
  printf '%s\n' \
    "REFUSED (OMN-20914): gh $_cls from a lane ($_lw_why); lanes do GitHub writes through the source-control node, not gh (RULING 2026-10-10T18:32:46Z)." \
    "Use instead: onex scm $_lw_scm   (node_github_repo_write_effect operation $_lw_op; onex scm $_lw_scm --help for its options, onex scm verbs for the whole table)" \
    "The verb is refused because onex scm serves it for $_rs_owner/$_rs_repo; gh pr merge, gh run rerun and gh api writes have no onex scm operation and are unaffected." >&2
  _endpoint="onex scm $_lw_scm"
  _refusal_row gh_shim_lane_write_guard covered-write-via-gh-shim "REFUSED (OMN-20914): gh $_cls from a lane ($_lw_why); use onex scm $_lw_scm"
  _call_log 1 refused
  exit 1
fi
unset _lw_why _lw_scm _lw_op _rs_owner _rs_repo _rs_n

# The harness PR-link lookup, answered from the PR watcher's state file (OMN-19479). Prints
# the JSON gh would print and returns 0 only when the state is fresher than
# ONEX_PR_WATCHER_MAX_AGE_S (default 600 s) and names exactly one OPEN PR of <repo_id> (an
# OmniNode-ai repository) whose head branch is <branch>; any other case returns 1 and the
# caller runs the real gh. $3 is the --json field list, one of the two cacheable shapes.
_watcher_link() {
  local repo_id="$1" branch="$2" fields="$3" state max name out
  command -v jq >/dev/null 2>&1 || return 1
  state="${ONEX_PR_WATCHER_STATE:-${OMNI_HOME:+$OMNI_HOME/.claude_scratch/pr-watcher/state.json}}"
  [ -n "$state" ] && [ -r "$state" ] || return 1
  max="${ONEX_PR_WATCHER_MAX_AGE_S:-600}"
  case "$max" in ""|*[!0-9]*) max=600 ;; esac
  case "$repo_id" in OmniNode-ai/?*) name="${repo_id#OmniNode-ai/}" ;; *) return 1 ;; esac
  out="$(jq -c --arg repo "$name" --arg branch "$branch" --arg fields "$fields" \
    --argjson now "$(date +%s)" --argjson max "$max" '
      select(($now - (try (.last_tick | fromdateiso8601) catch 0)) <= $max)
      | [.prs[]? | select(.facts.repo == $repo and .facts.state == "OPEN" and .facts.head_ref == $branch)] as $m
      | select(($m | length) == 1)
      | "https://github.com/OmniNode-ai/\($repo)/pull/\($m[0].facts.number)" as $url
      | if $fields == "url" then {url: $url} else {number: $m[0].facts.number, state: "OPEN", url: $url} end
    ' "$state" 2>/dev/null)" || return 1
  [ -n "$out" ] || return 1
  printf '%s\n' "$out"
}

# A PR mutation can change the cached answers for its repository: drop that
# repository's entries before it runs (every entry when the repository is
# unknown). Entries are named <repo hash>.<key>, so lookups in other
# repositories stay cached.
if [ "${1:-}" = "pr" ]; then
  case "${2:-}" in
    create|ready|close|reopen|merge)
      _mut_repo=""
      _prev=""
      for _a in "$@"; do
        case "$_prev" in -R|--repo) _mut_repo="$_a" ;; esac
        case "$_a" in --repo=*) _mut_repo="${_a#--repo=}" ;; esac
        _prev="$_a"
      done
      if [ -z "$_mut_repo" ]; then _read_origin; _mut_repo="$_origin"; fi
      if [ -n "$_mut_repo" ]; then
        rm -f "$_cache_root/$(_sha "$_mut_repo" | cut -c1-16)".* 2>/dev/null
      else
        rm -f "$_cache_root"/* 2>/dev/null
      fi
      ;;
  esac
fi

if _cacheable "$@"; then
  _top="$(git rev-parse --show-toplevel 2>/dev/null)"
  _branch="$_branch_arg"
  if [ -z "$_branch" ] && [ -n "$_top" ]; then
    _branch="$(git symbolic-ref --short -q HEAD 2>/dev/null)"
  fi
  if [ -n "$_top" ] && [ -n "$_branch" ]; then
    _read_origin
    _repo_id="$_origin"
    [ -n "$_repo_id" ] || _repo_id="$_top"
    # Only a branch name, or none, is looked up in the watcher state: a PR number, a URL or an
    # owner:branch ref names a PR the state is not asked about, so it goes to the cache and gh.
    case "$_branch_arg" in
      "") _wl_ok=1 ;;
      *[!A-Za-z0-9._/-]*) _wl_ok=0 ;;
      *[!0-9]*) _wl_ok=1 ;;
      *) _wl_ok=0 ;;
    esac
    if [ "$_wl_ok" -eq 1 ] && _wl_out="$(_watcher_link "$_repo_id" "$_branch" "$_fields")"; then
      printf '%s\n' "$_wl_out"
      _log 0 watcher
      exit 0
    fi
    _key="$(_sha "$_repo_id" | cut -c1-16).$(_sha "$_top|$_branch|$_fields")"
    _entry="$_cache_root/$_key"
    _now="$(date +%s)"
    if [ -f "$_entry.meta" ]; then
      read -r _rc _at < "$_entry.meta"
      case "$_rc$_at" in
        *[!0-9]*|"") ;;
        *)
          if [ $((_now - _at)) -lt "$ONEX_GH_SHIM_TTL" ]; then
            cat "$_entry.out" 2>/dev/null
            cat "$_entry.err" >&2 2>/dev/null
            _log "$_rc" hit
            exit "$_rc"
          fi
          ;;
      esac
    fi
    mkdir -p "$_cache_root" 2>/dev/null
    _tmp="$_entry.tmp.$$"
    _run_gh "$@" > "$_tmp.out" 2> "$_tmp.err"
    _rc=$?
    cat "$_tmp.out"
    cat "$_tmp.err" >&2
    _keep=0
    if [ "$_rc" -eq 0 ]; then
      _keep=1
    elif grep -qi 'no pull requests found' "$_tmp.err" 2>/dev/null; then
      _keep=1
    fi
    if [ "$_keep" -eq 1 ]; then
      # .meta is written last and read first, so a reader never sees a
      # half-written entry as fresh.
      mv -f "$_tmp.out" "$_entry.out" 2>/dev/null
      mv -f "$_tmp.err" "$_entry.err" 2>/dev/null
      printf '%s %s\n' "$_rc" "$_now" > "$_tmp.meta" 2>/dev/null \
        && mv -f "$_tmp.meta" "$_entry.meta" 2>/dev/null
    fi
    rm -f "$_tmp.out" "$_tmp.err" "$_tmp.meta" 2>/dev/null
    _log "$_rc" miss
    exit "$_rc"
  fi
fi

# Pass-through. Run rather than exec, so the exit code can be logged; stdin,
# stdout, stderr and the terminal are inherited unchanged.
_warn_gateway_read "$@"
_run_gh "$@"
_rc=$?
_log "$_rc" none
exit "$_rc"
