@plot-pm/board 0.22.1 → 0.23.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/plot-host.sh CHANGED
@@ -31,10 +31,21 @@
31
31
  # where GitHub's `hosts.yml` names no user;
32
32
  # exit 4 on Bitbucket, which stores no username
33
33
  # for free. Never prints `unknown`.
34
- # pr-state <number|branch> [--repo <owner/repo>] one JSON object:
34
+ # pr-state <number|branch> [--repo <owner/repo>] [--with-checks]
35
+ # one JSON object:
35
36
  # {"number":N,"state":"OPEN|MERGED|CLOSED|NONE",
36
37
  # "draft":true|false,"url":"...",
37
38
  # "mergeable":"mergeable|conflicting|unknown"}
39
+ # ON BITBUCKET, `checks` and the Jenkins lookup
40
+ # it costs are read ONLY with `--with-checks`;
41
+ # without the flag `checks` reads `unknown`
42
+ # and no Jenkins call is made. GitHub reads
43
+ # `checks` either way. No caller under
44
+ # skills/plot/scripts/ reads `.checks` from
45
+ # this op (surveyed 2026-10-24, #2481); the
46
+ # merge controller (`mergeAt`) passes the
47
+ # flag, because it refuses unless `checks`
48
+ # reads `green`.
38
49
  # Bitbucket Cloud's REST API has no field or
39
50
  # endpoint that reports merge-conflict status
40
51
  # for a pull request (measured 2026-10-20), so
@@ -50,9 +61,13 @@
50
61
  # PER BRANCH (`bb_branch_query`'s `q=` filter),
51
62
  # never a repository-wide page — a PR merged
52
63
  # before a page's newest 50 used to read as
53
- # NONE. A page full at that filter's own
54
- # ceiling without a match exits 3, the same as
55
- # any other unanswerable question.
64
+ # NONE. `bb_branch_query` follows `next`, so a
65
+ # branch with more than 50 matches is still
66
+ # read whole; only a refused call or a walk the
67
+ # page cap stopped exits 3 — not an empty match
68
+ # on a full page, which this arm's own branch
69
+ # filter makes impossible (every row already
70
+ # matches, so a short answer is a true NONE).
56
71
  # pr-merged <branch> has ANY PR for this branch merged? prints one
57
72
  # word: merged|not-merged|unknown
58
73
  # READS `mergedAt`, NEVER `state`: a merged PR
@@ -112,7 +127,10 @@
112
127
  # mismatch refuses `head-moved` (exit 1).
113
128
  # pr-ready <number> take a PR out of draft
114
129
  # merge the PR
115
- # pr-list [--state open|merged|closed|all] [--limit N] [--rich|--rich-open]
130
+ # pr-list [--state open|merged|closed|all|settled] [--limit N] [--rich|--rich-open]
131
+ # settled is merged+declined on bitbucket (no
132
+ # open sweep) and --state all on github, which
133
+ # already answers everything in one call.
116
134
  # --rich-open asks the rich fields of the OPEN
117
135
  # pull requests only, and emits every row in the
118
136
  # --rich shape. A MERGED or CLOSED row carries
@@ -423,7 +441,26 @@
423
441
  # found: <name>` on stderr, checked before any
424
442
  # issue search is spent; a 404/5xx on that
425
443
  # version-list check propagates its own exit
426
- # code instead, never read as not-found.
444
+ # code instead, never read as not-found, and a
445
+ # 200 that is not valid JSON exits 3, the same
446
+ # "cannot parse" failure `version-list` itself
447
+ # gives — never read as not-found either. THE
448
+ # EXISTENCE CHECK RUNS ONCE PER PROJECT PER
449
+ # READ, not once per page: it is skipped
450
+ # whenever `--page-token` is present, since
451
+ # `walk` (tracker-shell.ts) calls this op once
452
+ # per page and every page past the first
453
+ # carries that flag. A LATER `--state` THAT
454
+ # DISAGREES WITH `--fix-version` IS REFUSED
455
+ # (EXIT 2), in either argument order: the two
456
+ # flags are not independently meaningful
457
+ # (`--state version` alone has no name to
458
+ # search), so one silently winning would hide
459
+ # the other. EXIT 2 ALSO where an unpaged
460
+ # `--limit` is bounded away before the host is
461
+ # asked — a value of 16 or more digits refuses
462
+ # on its shape alone, since bash's own integer
463
+ # comparison cannot test it: see --limit above.
427
464
  # version-list <project> (jira only; exit 4 elsewhere) the versions of
428
465
  # one project, one JSON line each:
429
466
  # {"name":…,"released":bool,"releaseDate":…|null}.
@@ -463,11 +500,14 @@
463
500
  # credentials and through a different API — the
464
501
  # reason the tracker port has two connectors.
465
502
  # Prints `written` where the transition was
466
- # performed and `no-target` where the workflow
467
- # offers no such transition from the issue's
468
- # current state — which is also what a repeated
469
- # write reports, because the same status twice
470
- # is the same status.
503
+ # performed. Where none matches, prints
504
+ # `no-match<TAB>current<TAB>available`: the
505
+ # issue's current status and the names of the
506
+ # transitions offered from it, both read in the
507
+ # same lookup. The connector decides from them
508
+ # whether the issue already holds the status or
509
+ # no transition reaches it; this op decides
510
+ # nothing.
471
511
  # The transition id is LOOKED UP, never guessed:
472
512
  # ids are per workflow and per issue, so a
473
513
  # hardcoded one writes to the wrong column.
@@ -605,19 +645,50 @@ plot_tmpfile HOST_ERR host-err || { echo "plot-host: no temp file could be made
605
645
 
606
646
  die() { echo "plot-host: $*" >&2; exit 1; }
607
647
 
608
- # Rows in one page of an issue read: `maxResults` on Jira, and the rows `gh issue
609
- # list` fetches per request inside its one process.
648
+ # Rows in one page of a Jira issue read: its `maxResults` bound.
610
649
  ISSUE_PAGE_ROWS=100
611
650
 
612
651
  # Reports the host CLI's own words from the last call and exits 3 — a question
613
652
  # that failed, as opposed to exit 4 (cannot be asked) or an answered empty list.
614
653
  # An empty message or a recognised lookup miss is an answer; anything else exits 3.
615
- miss_or_exit3() { [ -z "$1" ] || is_lookup_miss "$1" || { echo "plot-host: $1" >&2; exit 3; }; }
616
- # `pr-merged`'s own third value for a failed call: a lookup miss still means
617
- # not-merged, anything else prints the host's words and answers `unknown`
618
- # rather than exiting — the caller already branches on this word, not a code.
619
- miss_or_unknown() { if [ -z "$1" ] || is_lookup_miss "$1"; then echo "not-merged"; else echo "plot-host: $1" >&2; echo "unknown"; fi; }
654
+ miss_or_exit3() { [ -z "$1" ] || is_lookup_miss "$1" || die3 "$1"; }
655
+ # `pr-merged`'s own third value for a failed call: a genuine PR-lookup miss
656
+ # still means not-merged — matched here on the same two phrases
657
+ # `is_lookup_miss` uses, minus its bare "not found" alternative, which also
658
+ # matches a failure naming no PR ("repository not found", 404) and would read
659
+ # as permission to delete the branch. Empty stderr is not a miss either: it
660
+ # is the host failing to say anything at all. Anything else answers `unknown`
661
+ # and prints the host's words when there are any, rather than exiting — the
662
+ # caller already branches on this word, not a code.
663
+ miss_or_unknown() { if [ -n "$1" ] && LC_ALL=C grep -qiE 'no (pull request|pullrequest)s? (found|match)|could not find.*pull request' <<<"$1"; then echo "not-merged"; else echo "${1:+plot-host: $1}" >&2; echo "unknown"; fi; }
620
664
  gh_fail() { echo "plot-host: $(cat "$HOST_ERR" 2>/dev/null)" >&2; rm -f "$HOST_ERR"; exit 3; }
665
+ # Reads the last host call's stderr into `err` and removes the file, so the
666
+ # next call starts empty. Every failed-call branch below starts with it.
667
+ host_err() { err="$(cat "$HOST_ERR" 2>/dev/null)"; rm -f "$HOST_ERR"; }
668
+
669
+ # THE ONE MARKER LOOKUP, shared by `pr-comment` and `issue-comment` — GitHub's
670
+ # REST comments endpoint is `issues/$num/comments` for both, since a PR is an
671
+ # issue under the hood. Prints the id of the comment holding `$2` (a
672
+ # substring), scoped to the comment's `.user.login` (the REST field; `gh pr
673
+ # list --json` answers `.author.login` instead, but this is the REST path) —
674
+ # so a PR participant who pastes the same marker into their own comment is
675
+ # never mistaken for this script's own prior post. Prints empty on no match.
676
+ #
677
+ # SCOPED TO THE LOGIN `gh api user` ANSWERS for the token this call writes
678
+ # with (`host.ts:358`), asked once per lookup. Not `budget_account`: it reads
679
+ # `hosts.yml` or `PLOT_BUDGET_ACCOUNT`, and neither names the author when
680
+ # `GH_TOKEN` is set or the account is a grouping name, so every lookup missed
681
+ # and posted a new comment.
682
+ #
683
+ # NO LOGIN, NO SCOPE. When `gh api user` fails or answers no valid login (an
684
+ # App installation token gets 403 there), the match falls back to the marker
685
+ # alone, as it was before #2661. A comment with no `user` field cannot be
686
+ # attributed and also matches on the marker alone.
687
+ #
688
+ # A FAILED LISTING EXITS 3 THROUGH `gh_fail`, same as a failed edit. `set -o
689
+ # pipefail` (above) makes the pipeline's exit code `gh api`'s own, so a lookup
690
+ # that cannot be read never falls through to "no marker found, post new".
691
+ gh_marker_comment_id() { gh api --paginate "repos/{owner}/{repo}/issues/$1/comments" 2>"$HOST_ERR" | jq -rs --arg m "$2" --arg who "$(gh api user -q .login 2>/dev/null | grep -E '^[A-Za-z0-9][A-Za-z0-9-]*(\[bot\])?$')" '[.[][] | select($who == "" or (.user.login // "") == "" or .user.login == $who) | select(.body | contains($m))][0].id // empty'; }
621
692
 
622
693
  # Exit 3 — reserved for "the op itself cannot proceed", distinct from `die`'s
623
694
  # generic 1. A Jenkins overlay with no instance to ask is such a case: a config
@@ -841,7 +912,7 @@ pr_list_failed() { # $1=stderr text
841
912
  pr_list_call() { # "$@"=the host command → payload on stdout, or dies
842
913
  local out rc err tmp=""
843
914
  plot_tmpfile tmp host-prlist-err \
844
- || { echo "plot-host: no temp file could be made under ${TMPDIR:-/tmp}" >&2; exit 3; }
915
+ || die3 "no temp file could be made under ${TMPDIR:-/tmp}"
845
916
  out="$("$@" 2>"$tmp")"; rc=$?
846
917
  err="$(cat "$tmp" 2>/dev/null)"; rm -f "$tmp"
847
918
  [ "$rc" -eq 0 ] || pr_list_failed "$err"
@@ -976,10 +1047,7 @@ PR_LIST_BIND_FN=""
976
1047
  # which are lower-case. One mapping, so a caller never spells a state twice.
977
1048
  bb_query_state() { # $1=adapter state word → Bitbucket's
978
1049
  case "$1" in
979
- open) printf 'OPEN' ;;
980
- merged) printf 'MERGED' ;;
981
- declined) printf 'DECLINED' ;;
982
- superseded) printf 'SUPERSEDED' ;;
1050
+ open|merged|declined|superseded) printf '%s' "$1" | tr '[:lower:]' '[:upper:]' ;;
983
1051
  *) die "bb_query_state: unknown state '$1'" ;;
984
1052
  esac
985
1053
  }
@@ -1008,11 +1076,12 @@ url_encode() { # $1=raw → percent-encoded on stdout
1008
1076
  printf '%s' "$_out"
1009
1077
  }
1010
1078
 
1011
- # Ask Bitbucket about ONE branch in ONE state, and print the `values` array.
1079
+ # Ask Bitbucket about ONE branch in ONE state, and print the combined `values`
1080
+ # array across every page the host offers.
1012
1081
  #
1013
- # WHAT IT PRINTS is the endpoint's `values` — a JSON array of 0 or 1 pull
1014
- # request objects, in the SAME shape `bb pr list --json` emits, which is what
1015
- # lets the existing jq programs consume it unchanged. The `--rich` field set
1082
+ # WHAT IT PRINTS is the endpoint's `values` — a JSON array of pull request
1083
+ # objects, in the SAME shape `bb pr list --json` emits, which is what lets the
1084
+ # existing jq programs consume it unchanged. The `--rich` field set
1016
1085
  # (`plot-host.sh:3247`) reads `.id`, `.title`, `.state`, `.source.branch.name`,
1017
1086
  # `.draft` and `.links.html.href`; the REST object carries all six.
1018
1087
  #
@@ -1024,12 +1093,24 @@ url_encode() { # $1=raw → percent-encoded on stdout
1024
1093
  # happening from the other side: a host exiting 0 while printing nothing once
1025
1094
  # read as "this repo has no PRs".
1026
1095
  #
1027
- # `pagelen=50` rather than 1. A branch may legitimately carry several pull
1028
- # requests in one state — a merged attempt and a merged successor — and the
1029
- # consumers rank them (`fleet.ts`'s `prOutranks`, the scan's OPEN-before-MERGED
1030
- # sort). Asking for one would silently hand them whichever the host listed
1031
- # first, which no adapter promises. Fifty is the endpoint's ceiling and costs
1032
- # the same as one.
1096
+ # THE QUERY FILTERS ON STATE, SO A FULL PAGE IS NEVER A SHORT NON-MATCH. Every
1097
+ # row this walk reads already matches `$_st` — Bitbucket filters server-side —
1098
+ # so a branch carrying more than 50 pull requests in one state (#2484) used to
1099
+ # truncate silently at the first page. This now follows `next` until the host
1100
+ # stops offering one, or until `BB_BRANCH_QUERY_PAGE_CAP` pages have been read,
1101
+ # whichever comes first — see that constant for why no narrower cap exists to
1102
+ # reuse.
1103
+ #
1104
+ # A STOPPED WALK REPORTS ITSELF, ON STDERR, IN `pr_list_report_truncation`'s
1105
+ # OWN WORDING ("possibly truncated") — `plot-host.sh:3093` is the precedent
1106
+ # this follows rather than inventing a second phrase for the same fact — and
1107
+ # RETURNS EXIT 3, the code `pr-merged`, `pr-merge-commit`/`pr-merge-dest` and
1108
+ # `pr-merged-heads` already read as "the question failed, not merely empty".
1109
+ # A caller reading the exit code sees one vocabulary for "the answer may be
1110
+ # short" whether the cause is a refused call or a walk the cap stopped.
1111
+ #
1112
+ # `pagelen=50` rather than 1 — the endpoint's ceiling, and the same per-page
1113
+ # cost whether this reads one page or several.
1033
1114
  # THE HOST'S OWN FAILURE TEXT LEAVES HERE UNCLASSIFIED, and that is the whole
1034
1115
  # reason this does not call `pr_list_call`. That wrapper classifies a failure
1035
1116
  # ONCE — throttled, burst, or everything else — and composes the sentence a
@@ -1038,12 +1119,79 @@ url_encode() { # $1=raw → percent-encoded on stdout
1038
1119
  # message: measured here, a `429` became *"the host failed the request and said
1039
1120
  # nothing"* because `Rate limit … exceeded` was no longer in the text being
1040
1121
  # matched. So the raw stderr and the raw exit code travel out of this function
1041
- # untouched, and the single `pr_list_call` that `pr_list_states` already wraps
1042
- # the whole sweep in does the one classification — exactly the layering
1043
- # `bb pr list` has always had.
1122
+ # untouched on the FIRST page; a later page's failure returns the same raw code
1123
+ # with no partial array printed — a caller cannot tell "zero rows" from "the
1124
+ # walk broke before it saw any", so printing a prefix here would manufacture an
1125
+ # answer this function never had.
1126
+ #
1127
+ # THE SAME `next`-WALK SHAPE AS `bb_window_listing` (`:1200`), which strips
1128
+ # `BB_API_BASE` from an absolute `next` URL to keep asking `bb api` with a
1129
+ # relative path — `bb api` concatenates `${BB_API}${path}` itself. That helper
1130
+ # has no page cap because its own completeness check is the server's `size`
1131
+ # field; this one has no `size` to check against (the endpoint's envelope here
1132
+ # carries it too, but a state-filtered count racing concurrent merges is not
1133
+ # the guard this slice adds), so the cap is the only bound on the walk.
1134
+ #
1135
+ # SHARED BY `bb_branch_query`, `bb_state_listing` AND `pr-review`'s
1136
+ # statuses/comments reads: the same walk and failure rule serve a
1137
+ # branch-filtered query, a plain state listing and a bare path alike, so the
1138
+ # loop lives once. $1=first path $2=truncation label $3=truncation detail
1139
+ # $4=row limit, or "" for the page-cap mode below; rest=global bb args →
1140
+ # combined values[] on stdout.
1141
+ #
1142
+ # TWO STOPPING RULES, CHOSEN BY WHETHER `$4` IS SET. With no limit, the walk
1143
+ # is `bb_branch_query`'s original shape: it runs until `next` is absent or
1144
+ # `BB_BRANCH_QUERY_PAGE_CAP` pages have been read, and a cap-stopped walk
1145
+ # reports itself and exits 3 — the question failed, not merely empty.
1146
+ #
1147
+ # WITH A LIMIT, THE WALK STOPS AT A ROW COUNT RATHER THAN A PAGE COUNT, AND A
1148
+ # CLEAN STOP EXITS 0. `bb_state_listing` asks for exactly the rows its caller
1149
+ # requested; stopping there is not a failure to read everything, it is
1150
+ # answering the question asked — the same distinction `pr_list_report_truncation`
1151
+ # draws for GitHub's own `--limit`. THE STOP RULE LIVES IN THE DOMAIN:
1152
+ # `walkStep` in `packages/domain/src/rules/listing-page.ts`, asked after every
1153
+ # page through `board/plot-listing-walk.mjs` with the pages read so far. It
1154
+ # stops at the first of: a page with no `next`, `$4` rows held, a page that
1155
+ # added no rows, or ceil(`$4` / `BB_LIST_PAGELEN`) pages read — the plan's cost
1156
+ # model (`2026-10-23-read-merged-prs-from-the-merge`, Approach 1). The bundle
1157
+ # prints the rows trimmed to `$4` and writes `BB_LIST_NEXT_FILE` (if set) the
1158
+ # stopping page's own `next` reading — "1" present, "0" absent, "" no
1159
+ # envelope — or "1" whenever the trim dropped a row, so
1160
+ # `pr_list_report_truncation` says "possibly truncated" for every stop that
1161
+ # left a row unread. COST: one `node` start (~40 ms) per page, at most
1162
+ # ceil(limit / 50) per state listing, beside a host request per page.
1163
+ # A REQUEST FAILURE IS STILL A REQUEST FAILURE: the limit changes how a CLEAN
1164
+ # stop is reported, never how a broken one is.
1165
+ _bb_paged_walk() {
1166
+ local _path="$1" _label="$2" _detail="$3" _limit="$4" _out _spool _next _page=0; shift 4
1167
+ # `plot_tmpfile` registers `_spool` for removal at process exit — no manual
1168
+ # `rm` on an early return; the walk only ever runs a handful of times per
1169
+ # process, so the file outliving one call costs nothing a caller can see.
1170
+ # The spool holds each page's whole response, one per line.
1171
+ plot_tmpfile _spool host-paged-walk || return 3; while [ -n "$_path" ]; do
1172
+ # A ROW-LIMIT WALK'S PAGE CAP IS `$4`, which `walkStep`'s page bound
1173
+ # ceil(`$4` / pagelen) always reaches first; with no limit it is
1174
+ # `BB_BRANCH_QUERY_PAGE_CAP`.
1175
+ [ "$((++_page))" -le "${_limit:-$BB_BRANCH_QUERY_PAGE_CAP}" ] || { echo "plot-host: $_label possibly truncated ($(jq -s 'map(.values // []) | add // [] | length' < "$_spool") rows, page cap $BB_BRANCH_QUERY_PAGE_CAP reached) — $_detail" >&2; return 3; }
1176
+ # `jq` is applied only to a SUCCESSFUL payload. Piping a failed call into it
1177
+ # would turn the host's exit code into jq's, and a parse error and a spent
1178
+ # quota are not the same fact. A failure on page 2+ returns the same raw
1179
+ # code the first page would have — see the header above.
1180
+ _out="$(bb "$@" api "$_path")" || return $?
1181
+ jq -c . <<<"$_out" >> "$_spool" && _next="$(jq -r '.next // empty' <<<"$_out")" || return 3
1182
+ # A ROW-LIMIT WALK ASKS THE DOMAIN after every page. The bundle exits 0 to
1183
+ # read the next page, 10 once it has printed the walk's answer and written
1184
+ # the stopping `next` reading, and 3 where the pages did not parse; 10
1185
+ # returns 0 here and every other code returns as it is.
1186
+ [ -z "$_limit" ] || node "$here/board/plot-listing-walk.mjs" "$_limit" "$BB_LIST_PAGELEN" "${BB_LIST_NEXT_FILE:-}" < "$_spool" || return "$(($? == 10 ? 0 : $?))"
1187
+ if [ -z "$_next" ]; then _path=""; elif [[ "$_next" == "$BB_API_BASE"/* ]]; then _path="${_next#"$BB_API_BASE"}"
1188
+ else echo "plot-host: $_label: next page '$_next' is outside $BB_API_BASE; refusing to read past it" >&2; return 3; fi
1189
+ done
1190
+ jq -c -s 'map(.values // []) | add // []' < "$_spool"
1191
+ }
1192
+
1044
1193
  bb_branch_query() { # $1=branch $2=adapter state; rest=global bb args → values[]
1045
- local _br="$1" _st="$2"; shift 2
1046
- local _q _path _out _rc
1194
+ local _br="$1" _st="$2" _q; shift 2
1047
1195
  _q="state=$(url_encode "\"$(bb_query_state "$_st")\"") AND source.branch.name=$(url_encode "\"$_br\"")"
1048
1196
  # THE WINDOW COMPOSES WITH THE STATE FILTER AND NEVER REPLACES IT. Bitbucket
1049
1197
  # takes ONE `q=` parameter, so a second one would silently win or lose
@@ -1061,27 +1209,31 @@ bb_branch_query() { # $1=branch $2=adapter state; rest=global bb args → values
1061
1209
  # so an exclusive comparison against a truncated stamp would drop a PR updated
1062
1210
  # inside the same second. Re-reading one row the caller already holds costs a
1063
1211
  # row; missing one costs a change nobody ever sees again.
1064
- [ -n "$PR_LIST_SINCE" ] \
1065
- && _q="$_q AND updated_on>=$(url_encode "\"$PR_LIST_SINCE\"")"
1066
- # The space between the two terms is encoded too; `bb api` passes the path to
1067
- # curl verbatim and an unencoded space would truncate the request line.
1068
- _q="${_q// /%20}"
1069
- # THE LEADING SLASH. See the block header — without it this is a 403 that
1070
- # reads as a scope error.
1071
- _path="/repositories/{ws}/{repo}/pullrequests?q=${_q}&pagelen=50"
1072
- # `jq` is applied only to a SUCCESSFUL payload. Piping a failed call into it
1073
- # would turn the host's exit code into jq's, and a parse error and a spent
1074
- # quota are not the same fact.
1075
- _out="$(bb "$@" api "$_path")" || return $?
1076
- printf '%s' "$_out" | jq -c '.values // []'
1212
+ [ -n "$PR_LIST_SINCE" ] && _q="$_q AND updated_on>=$(url_encode "\"$PR_LIST_SINCE\"")"
1213
+ # The space between the two terms is encoded too, inline below; `bb api`
1214
+ # passes the path to curl verbatim and an unencoded space would truncate the
1215
+ # request line. THE LEADING SLASH on the path: see the block header above —
1216
+ # without it this is a 403 that reads as a scope error.
1217
+ _bb_paged_walk "/repositories/{ws}/{repo}/pullrequests?q=${_q// /%20}&pagelen=50" "bitbucket pr-list state=$_st" "a join against this page may read older branches as 'no PR' (#333)" "" "$@"
1077
1218
  }
1078
1219
 
1079
- # A FULL `bb_branch_query` PAGE WITH NO MATCHING ROW CANNOT PROVE ABSENCE.
1080
- # $1=the JSON array, $2=a jq `any(.[]; …)` predicate naming the field that
1081
- # would carry the answer. True only at the 50-row ceiling with the predicate
1082
- # finding nothing — the one condition `pr-merged`, `pr-merge-commit` and
1083
- # `pr-merged-heads` each guard against before reading silence as a negative.
1084
- bb_full_page_lacks() { [ "$(jq 'length' <<<"$1")" -ge 50 ] && ! jq -e "$2" >/dev/null 2>&1 <<<"$1"; }
1220
+ # HOW MANY PAGES `bb_branch_query` WILL WALK BEFORE REPORTING "possibly
1221
+ # truncated" AND REFUSING TO GUESS AT THE REST.
1222
+ #
1223
+ # THERE WAS NO EXISTING CAP TO REUSE. `bb_window_listing` (`:1200`) walks
1224
+ # `next` with no cap at all — its own completeness proof is the server's
1225
+ # `size` field, read once the whole walk finishes — and nothing else in this
1226
+ # file bounds a `next`-walk by page count. The plan that commissioned this
1227
+ # change ("bounded by the existing page cap") named one that does not exist;
1228
+ # this constant is new, not reused, and that is reported in the branch's PR.
1229
+ #
1230
+ # 20, CHOSEN RATHER THAN MEASURED: at `pagelen=50` it reaches 1000 pull
1231
+ # requests for one branch in one state, an order of magnitude past the
1232
+ # largest number of pull requests measured for any single tracked branch on
1233
+ # this estate (`a-pr-list-reads-every-page.md`: 886 MERGED pull requests
1234
+ # across an entire repository, not one branch). A branch that still exceeds
1235
+ # it gets the truncation report rather than a silent prefix.
1236
+ BB_BRANCH_QUERY_PAGE_CAP=20
1085
1237
 
1086
1238
  # Ask about EVERY tracked branch in one state, printing one combined array.
1087
1239
  #
@@ -1139,8 +1291,7 @@ bb_branch_sweep() { # global bb args… --state <s> --json → one JSON array
1139
1291
  # re-parses of a growing accumulator: the old shape re-read every row it had
1140
1292
  # already seen once per branch, so eleven branches parsed the first branch's
1141
1293
  # payload eleven times.
1142
- local _spool
1143
- plot_tmpfile _spool host-sweep || return 3
1294
+ local _spool; plot_tmpfile _spool host-sweep || return 3
1144
1295
  for _br in $PR_LIST_BRANCHES; do
1145
1296
  # RETURN, NOT EXIT. This runs inside the command substitution
1146
1297
  # `pr_list_call` wraps the sweep in, so the code must travel back as this
@@ -1237,16 +1388,17 @@ bb_window_listing() { # global bb args… --state <s> --json → one JSON array
1237
1388
  # pages and arrive twice.
1238
1389
  _rows="$(jq -c -s 'add // [] | unique_by(.id)' < "$_spool")" || { rm -f "$_spool"; return 3; }
1239
1390
  rm -f "$_spool"
1240
- local _got
1241
- _got="$(jq 'length' <<<"$_rows")" || return 3
1391
+ local _got; _got="$(jq 'length' <<<"$_rows")" || return 3
1242
1392
  if [ "$_got" -lt "$_size" ] 2>/dev/null; then
1243
1393
  echo "bitbucket window state=$_st is short ($_got of $_size matches after $_pages pages); refusing it rather than printing it as whole" >&2
1244
1394
  return 3
1245
1395
  fi
1396
+ echo "plot-host: bitbucket pr-list state=$_st window complete ($_got matches, every page read) — this window holds every pull request the host has in this state since the stamp" >&2
1246
1397
  printf '%s' "$_rows"
1247
1398
  }
1248
1399
 
1249
- # List the pull requests in ONE state, one page of 50, as one array.
1400
+ # List the pull requests in ONE state, following `next` up to `PR_LIST_LIMIT`
1401
+ # rows, as one array.
1250
1402
  #
1251
1403
  # THE PLAIN LISTING, and the fourth command in `pr_list_states`' slot. It takes
1252
1404
  # the same trailing `--state <s> --json` as `bb_branch_sweep` and
@@ -1255,13 +1407,25 @@ bb_window_listing() { # global bb args… --state <s> --json → one JSON array
1255
1407
  #
1256
1408
  # /repositories/{ws}/{repo}/pullrequests?state=MERGED&pagelen=50
1257
1409
  #
1258
- # ONE REQUEST PER STATE, WHERE `bb pr list` SPENDS UP TO FIVE. `bb pr list`
1259
- # sends no `pagelen`, Bitbucket answers 10 rows a page, and `bb_paginate` walks
1260
- # pages until it holds 50. Asking `pagelen=50` returns the same 50 rows in one
1261
- # request. Measured 2026-09-30 on `quatico/quaweb-website` with bb 1.9.0: the
1262
- # three states cost 8 requests through `bb pr list` (open 1, merged 5,
1263
- # declined 2) and 3 through this path, and both return the same 67 rows
1264
- # (3 open, 50 merged, 14 declined).
1410
+ # EVERY PAGE UP TO THE LIMIT IS READ, WHERE A SINGLE REQUEST USED TO BE THE
1411
+ # WHOLE ANSWER. Before this slice, one `bb api` call at `pagelen=50` was taken
1412
+ # as the state's listing outright — correct only when a state held 50 rows or
1413
+ # fewer, and silently short against #333's measurement of ~780 merged PRs
1414
+ # invisible past the first page. `_bb_paged_walk`'s row-limit mode (its own
1415
+ # header has the stopping rule) now follows `next` until it holds
1416
+ # `PR_LIST_LIMIT` rows or the host stops offering one, so a `--limit 1000`
1417
+ # caller gets up to 1000 rows of this state rather than 50 regardless of how
1418
+ # it asked. `PR_LIST_LIMIT` empty means no `--limit` was requested, and the
1419
+ # walk then stops at `BB_LIST_PAGELEN` rows: one request, the answer every
1420
+ # caller before this slice got and still gets.
1421
+ #
1422
+ # ONE REQUEST PER STATE AT THE OLD CEILING, WHERE `bb pr list` SPENDS UP TO
1423
+ # FIVE. `bb pr list` sends no `pagelen`, Bitbucket answers 10 rows a page, and
1424
+ # `bb_paginate` walks pages until it holds 50. Asking `pagelen=50` returns the
1425
+ # same 50 rows in one request. Measured 2026-09-30 on `quatico/quaweb-website`
1426
+ # with bb 1.9.0: the three states cost 8 requests through `bb pr list` (open 1,
1427
+ # merged 5, declined 2) and 3 through this path at one page each, and both
1428
+ # return the same 67 rows (3 open, 50 merged, 14 declined).
1265
1429
  #
1266
1430
  # THE STATES STAY SEPARATE CALLS. One `state=` union over the three returns the
1267
1431
  # 50 most recently updated rows across all of them: measured on the same
@@ -1270,21 +1434,22 @@ bb_window_listing() { # global bb args… --state <s> --json → one JSON array
1270
1434
  # `bb_states_for` records, reached through the page cap instead of through a
1271
1435
  # flag.
1272
1436
  #
1273
- # ONE PAGE, AS BEFORE. 50 is the endpoint's `pagelen` ceiling and the limit
1274
- # `bb_paginate` applied, so a state holding more than 50 rows answers with its
1275
- # 50 most recent here too, and `pr_list_report_truncation` still says so —
1276
- # unless the envelope carries Bitbucket's own `page` marker and no `next`,
1277
- # which it reads back from `BB_LIST_NEXT_FILE` (`pr_list_states` sets the
1278
- # path; this runs in that call's own subshell, so a global here would never
1279
- # reach the caller). `page` is what tells a real paginated envelope from a
1280
- # `values`-only shape that never carries `next` at all regardless of total —
1281
- # the latter proves nothing and must fall through to the version table.
1437
+ # A CLEAN STOP AT THE LIMIT EXITS 0, NEVER 3. `_bb_paged_walk`'s header draws
1438
+ # the line: a row-limit stop answered exactly what the caller asked for, so it
1439
+ # is not the same fact as the page-cap stop `bb_branch_query` reports with
1440
+ # "possibly truncated" and exit 3. Whether THIS state's rows exceed the limit
1441
+ # unprovably is `pr_list_report_truncation`'s question, not this function's.
1442
+ # It reads the walk's answer back from `BB_LIST_NEXT_FILE` (`pr_list_states`
1443
+ # sets the path; this runs in that call's own subshell, so a global here would
1444
+ # never reach the caller): the stopping page's own `next`, or "1" where the
1445
+ # walk trimmed rows, so a `--limit` that is not a multiple of `pagelen` still
1446
+ # reports correctly. The length table answers only where no envelope was read.
1282
1447
  #
1283
1448
  # THE HOST'S FAILURE TEXT AND EXIT CODE LEAVE UNTOUCHED, as in
1284
- # `bb_branch_query`: `pr_list_call` classifies once, so a `429` still reads as
1285
- # a rate limit.
1449
+ # `bb_branch_query`: `pr_list_call` classifies once, so a `429` on any page
1450
+ # still reads as a rate limit.
1286
1451
  bb_state_listing() { # global bb args… --state <s> --json → one JSON array
1287
- local _st="" _args=() _out
1452
+ local _st="" _args=()
1288
1453
  while [ $# -gt 0 ]; do
1289
1454
  case "$1" in
1290
1455
  --state) _st="${2:?}"; shift 2 ;;
@@ -1293,9 +1458,9 @@ bb_state_listing() { # global bb args… --state <s> --json → one JSON array
1293
1458
  esac
1294
1459
  done
1295
1460
  [ -n "$_st" ] || die "bb_state_listing: no --state"
1296
- _out="$(bb ${_args[@]+"${_args[@]}"} api "/repositories/{ws}/{repo}/pullrequests?state=$(bb_query_state "$_st")&pagelen=$BB_LIST_PAGELEN")" || return $?
1297
- [ -n "${BB_LIST_NEXT_FILE:-}" ] && printf '%s' "$_out" | jq -r 'if (type=="object") and has("values") and has("page") then (if has("next") then "1" else "0" end) else "" end' > "$BB_LIST_NEXT_FILE"
1298
- printf '%s' "$_out" | jq -c '.values // []'
1461
+ _bb_paged_walk "/repositories/{ws}/{repo}/pullrequests?state=$(bb_query_state "$_st")&pagelen=$BB_LIST_PAGELEN" \
1462
+ "bitbucket pr-list state=$_st" "a join against this page may read older branches as 'no PR' (#333)" \
1463
+ "${PR_LIST_LIMIT:-$BB_LIST_PAGELEN}" ${_args[@]+"${_args[@]}"}
1299
1464
  }
1300
1465
 
1301
1466
  # The branches a sweep asks about, newline-or-space separated. Empty means the
@@ -1325,6 +1490,15 @@ PR_LIST_BRANCHES=""
1325
1490
  # has none."
1326
1491
  PR_LIST_SINCE=""
1327
1492
 
1493
+ # The row count `bb_state_listing` stops at, or "" to ask for one request's
1494
+ # worth and report whatever comes back — the shape every caller before this
1495
+ # slice got. Set by `pr_list_states` itself (it already holds `$2=limit` in
1496
+ # scope) immediately before the loop, and read only by `bb_state_listing`;
1497
+ # see `PR_LIST_SINCE` immediately above for why this travels as a global
1498
+ # rather than a parameter threaded through `bb_branch_sweep` and
1499
+ # `bb_window_listing`'s shared calling convention.
1500
+ PR_LIST_LIMIT=""
1501
+
1328
1502
  # How many branches the last sweep asked about, and how many answered.
1329
1503
  #
1330
1504
  # THE COMPLETENESS SIGNAL, AND WHY THE ARM STATES IT RATHER THAN THE SCAN
@@ -1381,6 +1555,14 @@ pr_sweep_report() { # $1=states answered $2=states asked
1381
1555
  pr_list_states() { # $1=backend $2=limit $3=states $4=jq-program; rest=the host command
1382
1556
  local backend="$1" limit="$2" states="$3" jq_prog="$4"; shift 4
1383
1557
  local _s _raw _rc _err _tmp _ok=0 _failed=0 _first_rc=0 _failed_states="" BB_LIST_NEXT=""
1558
+ # A GLOBAL FOR `PR_LIST_SINCE`'S REASON: `bb_state_listing` runs inside the
1559
+ # command substitution below, its own subshell, so a parameter cannot reach
1560
+ # it any other way. Read only by `bb_state_listing` — `bb_branch_sweep` and
1561
+ # `bb_window_listing` pass through unread, exactly as they do for
1562
+ # `PR_LIST_SINCE`, because the limit means nothing to either: a sweep's cost
1563
+ # is the caller's branch count and a window refuses a short read outright,
1564
+ # so neither has a row count to stop at.
1565
+ PR_LIST_LIMIT="$limit"
1384
1566
  for _s in $states; do
1385
1567
  # `bb_state_listing` RUNS INSIDE THE SUBSTITUTION BELOW, its own subshell,
1386
1568
  # so a variable it sets cannot reach this one — the same trap `pr_list_call`
@@ -1746,7 +1928,7 @@ jenkins_no_instance() {
1746
1928
  # that into exit 4, *cannot be asked*.
1747
1929
  jenkins_rest_credential() { # $1 = the bare host
1748
1930
  local u="${JENKINS_USER:-}" t="${JENKINS_API_TOKEN:-}" src="the environment" found env_file
1749
- [ -n "$u" ] || [ -n "$t" ] || { found="$(plot_env_file)"; [ -n "$found" ] && env_file="${found%|*}" && src="${found#*|}.env" && u="$(read_env_var JENKINS_USER "$env_file")" && t="$(read_env_var JENKINS_API_TOKEN "$env_file")"; }
1931
+ [ -n "$u" ] || [ -n "$t" ] || { found="$(plot_env_file JENKINS_USER JENKINS_API_TOKEN)"; [ -n "$found" ] && env_file="${found%|*}" && src="${found#*|}.env" && u="$(read_env_var JENKINS_USER "$env_file")" && t="$(read_env_var JENKINS_API_TOKEN "$env_file")"; }
1750
1932
  [ -n "$u" ] && [ -n "$t" ] && { echo "plot-host: JENKINS_USER and JENKINS_API_TOKEN read from $src" >&2; printf '%s:%s' "$u" "$t"; return 0; }
1751
1933
  command -v security >/dev/null 2>&1 || return 1; u=$(security find-generic-password -s jen -a "jenkins-user:$1" -w 2>/dev/null) || return 1
1752
1934
  t=$(security find-generic-password -s jen -a "jenkins-token:$1" -w 2>/dev/null) || return 1
@@ -1772,12 +1954,14 @@ jenkins_job_url_path() { # $1 = job path, $2 = branch or ""
1772
1954
  # `Instance:` line rather than reinvented here — `jen` already turns a slug
1773
1955
  # like `ewz` into `jenkins-ci-ewz.internal.quatico.dev` and keys its stored
1774
1956
  # credential by that resolved host, so a literal slug sent to `curl` or to
1775
- # `jenkins_rest_credential` can only fail. Prints nothing (exit 1) when `jen`
1776
- # is missing, unparseable, or the line is absent — the caller decides what an
1777
- # unresolved host means, same contract as every other helper here.
1957
+ # `jenkins_rest_credential` can only fail. Prints nothing and exits 1 when
1958
+ # `jen` is missing, unparseable, or the line is absent; exits 2 when the line
1959
+ # names no parenthesized host. The caller decides what an unresolved host
1960
+ # means, same contract as every other helper here.
1778
1961
  jenkins_resolve_host() {
1779
- local line; line=$(jen -I "$1" auth status 2>&1 | grep -iE '^Instance:' | head -1) || true
1780
- [ -n "$line" ] && sed -nE 's/.*\(https?:\/\/([^)\/]+).*/\1/p' <<<"$line" || return 1
1962
+ local line; line=$(jen -I "$1" auth status 2>&1 | grep -iE '^Instance:' | head -1)
1963
+ [ -n "$line" ] || return 1
1964
+ sed -nE 's/.*\(https?:\/\/([^)\/]+).*/\1/p' <<<"$line" | grep . || return 2
1781
1965
  }
1782
1966
 
1783
1967
  # Every Jenkins build of one job, as a JSON array (newest first), or exit 3
@@ -1835,27 +2019,67 @@ jenkins_resolve_host() {
1835
2019
  # WITH A SHA, ONLY THAT SHA'S BUILDS, never another's. `result` is null while a build
1836
2020
  # runs, Jenkins' own word for *in flight*, mapped to the `status`/`conclusion`
1837
2021
  # split the contract already uses so the shape does not fork per connector.
2022
+ #
2023
+ # THE BRANCH AND ITS SHA COME FROM THE SAME ACTION. Each `actions[]` entry
2024
+ # with a `lastBuiltRevision` becomes one `{sha, branches}` record, read off
2025
+ # that one entry — never a flat list of every action's sha paired by position
2026
+ # with a flat list of every action's branch names, which can only agree by
2027
+ # luck once an action carries zero or several branches. A build is searched
2028
+ # record by record for the one whose `branches` names the ASKED BRANCH, on a
2029
+ # plain job same as a multibranch one — the job's last path segment names a
2030
+ # job, not a branch, and is never the key. A record naming no branch never
2031
+ # matches a named branch, and the build falls back to its LAST record only
2032
+ # when none of its records name any branch at all.
2033
+ #
2034
+ # JENKINS' `tree=` PARAMETER SELECTS FIELDS, NEVER VALUES: there is no syntax
2035
+ # for "only where result != NOT_BUILT", so the `NOT_BUILT`/`ABORTED` filter can
2036
+ # only run after the fetch, in jq. `{0,$limit}` on the Jenkins side must
2037
+ # therefore ask for MORE than `$limit` builds, or a build filtered out after
2038
+ # the cut silently shrinks the answer — `runs --limit 3` over five builds where
2039
+ # two are `NOT_BUILT` returning 1 row instead of 3. The over-fetch factor is
2040
+ # fixed at 3x, uncapped: it costs response BYTES, never an extra round trip or
2041
+ # rate-budget slot (`host_slot_take`/`budget_record_call` below run once per
2042
+ # path regardless of `limit`), and a single multibranch job's full history is
2043
+ # small enough that 3x of any realistic `--limit` stays well under what one
2044
+ # `tree=` query already returns today (measured 2026-09-10: 4855 bytes for
2045
+ # five builds).
2046
+ #
2047
+ # A BRANCH JENKINS HAS NOT INDEXED REFUSES BY NAME. The branch-specific path
2048
+ # is tried first; if it answers real JSON with no `builds` key, Jenkins
2049
+ # reached the job and simply has no such branch, and the refusal says so.
2050
+ # Only the root-path retry's container check (above) can turn that into an
2051
+ # empty-history read instead. A host that never answers at all — curl
2052
+ # failure, HTML, empty body — gets the generic "did not answer" refusal,
2053
+ # since nothing there proves Jenkins was even reached.
1838
2054
  jenkins_sha_runs() {
1839
- local op="$1" branch="$2" limit="$3" sha="$4" instance slug host job cred tree body try path plain="" default_job root_path
2055
+ local op="$1" branch="$2" limit="$3" sha="$4" instance slug host job cred tree body try path plain="" default_job root_path branch_path branch_answered=""
1840
2056
  instance="$(jenkins_instance)"; [ -n "$instance" ] || jenkins_no_instance
1841
2057
  slug="${instance%%/*}"; job="${instance#*/}"; [ "$job" = "$instance" ] && job=""
1842
2058
  default_job=$(bash "$here/plot-config.sh" get "Default branch job" "" 2>/dev/null || true); [ -n "$default_job" ] && [ "$branch" = "$(git symbolic-ref --quiet --short refs/remotes/origin/HEAD 2>/dev/null | sed 's#^origin/##')" ] && job="$default_job"
1843
2059
  [ -n "${PLOT_JENKINS_JOB:-}" ] && job="$PLOT_JENKINS_JOB"; [ -n "$job" ] || { echo "plot-host: $op — the Jenkins instance names no job path; a sha lives in a job's builds, so it must be <slug>/<job/path>, not a bare host" >&2; exit 4; }
1844
2060
  # A dotted slug IS a host already, `jen`'s own passthrough rule — only a
1845
2061
  # bare slug (`ewz`) needs resolving to the host its credential is keyed by.
1846
- case "$slug" in *.*) host="$slug" ;; *) host="$(jenkins_resolve_host "$slug")" || { echo "plot-host: $op — cannot resolve Jenkins instance '$slug' to a host" >&2; echo " \`jen -I $slug auth status\` did not answer an 'Instance:' line; run it directly to see why." >&2; exit 4; } ;; esac
2062
+ case "$slug" in *.*) host="$slug" ;; *) host="$(jenkins_resolve_host "$slug")" || {
2063
+ [ $? = 2 ] && printf '%s\n' "plot-host: $op — cannot resolve Jenkins instance '$slug' to a host" " \`jen -I $slug auth status\` answered an 'Instance:' line that names no (https://…) host; run it directly to see what it names." >&2 || printf '%s\n' "plot-host: $op — cannot resolve Jenkins instance '$slug' to a host" " \`jen -I $slug auth status\` did not answer an 'Instance:' line; run it directly to see why." >&2
2064
+ exit 4; } ;; esac
1847
2065
  cred="$(jenkins_rest_credential "$host")" || {
1848
2066
  echo "plot-host: $op — no Jenkins API credential for '$host'" >&2
1849
2067
  echo " Jenkins' REST API takes basic auth with an API token, which \`jen auth login\` stores in the login keychain. The Keycloak bearer from \`jen auth token\` is NOT it." >&2
1850
2068
  exit 4
1851
2069
  }
1852
- tree="tree=builds%5Bnumber,result,building,timestamp,url,actions%5BlastBuiltRevision%5BSHA1,branch%5Bname%5D%5D%5D%5D%7B0,$limit%7D"
1853
- body=""; root_path="$(jenkins_job_url_path "$job" "")"
1854
- for path in "$(jenkins_job_url_path "$job" "$branch")" "$root_path"; do
2070
+ tree="tree=builds%5Bnumber,result,building,timestamp,url,actions%5BlastBuiltRevision%5BSHA1,branch%5Bname%5D%5D%5D%5D%7B0,$((limit * 3))%7D"
2071
+ body=""; root_path="$(jenkins_job_url_path "$job" "")"; branch_path="$(jenkins_job_url_path "$job" "$branch")"
2072
+ for path in "$branch_path" "$root_path"; do
1855
2073
  host_slot_take jenkins ''
1856
2074
  try=$(curl -sg --max-time 30 -u "$cred" "https://$host$path/api/json?$tree" 2>/dev/null) || true
1857
2075
  host_slot_give; budget_record_call jenkins ''
1858
2076
  if printf '%s' "$try" | jq -e 'has("builds")' >/dev/null 2>&1; then body="$try"; break; fi
2077
+ # A branch path that came back as REAL JSON (jq could parse and evaluate
2078
+ # it, just found no `builds` key) means Jenkins answered and indexed no
2079
+ # such branch — distinct from curl failing outright or answering HTML,
2080
+ # where jq's own exit code is 4 (empty input) or 5 (parse error) rather
2081
+ # than the 1 a successfully-evaluated `false` reports.
2082
+ [ "$path" = "$branch_path" ] && printf '%s' "$try" | jq -e . >/dev/null 2>&1 && branch_answered=1
1859
2083
  # ONLY AT THE ROOT: a multibranch container that answered its OWN `_class`
1860
2084
  # and no `builds` has not indexed this branch at all — an empty history,
1861
2085
  # not a refusal. Checking this on the BRANCH path too would be wrong: a
@@ -1867,37 +2091,39 @@ jenkins_sha_runs() {
1867
2091
  plain=1
1868
2092
  done
1869
2093
  cred=""
1870
- if [ -z "$body" ]; then
1871
- echo "plot-host: $op — Jenkins did not answer for '$host'" >&2
1872
- exit 4
1873
- fi
1874
- printf '%s' "$body" | jq -c --arg sha "$sha" --arg job "$job" --arg branch "$branch" --arg plain "$plain" 'def headsha($b): if (.br | length) > 0 then (first([.br, .shas] | transpose[] | select(.[0] == $b) | .[1]) // (.shas | last // "")) else (.shas | last // "") end;
2094
+ [ -n "$body" ] || { [ -n "$branch_answered" ] && echo "plot-host: $op — Jenkins has no branch '$branch' indexed for '$job'" >&2 || echo "plot-host: $op — Jenkins did not answer for '$host'" >&2; exit 4; }
2095
+ printf '%s' "$body" | jq -c --arg sha "$sha" --arg job "$job" --arg branch "$branch" --arg plain "$plain" --argjson limit "$limit" 'def headsha($records): ($records | map(select(any(.branches[]; . == $branch))) | first.sha) // (if [$records[].branches[]] | length == 0 then $records | last.sha // "" else "" end);
1875
2096
  [ .builds[]
1876
- | { shas: [ .actions[]? | select(.lastBuiltRevision) | .lastBuiltRevision.SHA1 ],
1877
- br: [ .actions[]? | .lastBuiltRevision.branch[]?.name // empty | sub("^(refs/remotes/|refs/heads/)"; "") | sub("^origin/"; "") ],
2097
+ | { records: [ .actions[]? | select(.lastBuiltRevision) | .lastBuiltRevision
2098
+ | { sha: .SHA1, branches: [ .branch[]?.name // empty | sub("^(refs/remotes/|refs/heads/)"; "") | sub("^origin/"; "") ] } ],
1878
2099
  status: (if .building then "in_progress" else "completed" end),
1879
2100
  conclusion: (if .building then null else (.result // null) end),
1880
2101
  url: (.url // ""),
1881
2102
  startedAt: (if .timestamp then (.timestamp / 1000 | todate) else "" end), workflow: $job } ] | map(select(.conclusion != "NOT_BUILT")) | (if $sha == "" then map(select(.conclusion != "ABORTED")) else . end)
1882
- | if $sha != "" then map(select(headsha(if $plain == "" then $branch else ($job | split("/") | last) end) as $h | $h == $sha or (($sha | test("^[0-9a-f]{7,}$")) and ($h | startswith($sha))))) elif $plain == "" then .
1883
- else map(select(if (.br | length) > 0 then any(.br[]; . == $branch) else $branch == ($job | split("/") | last) end)) end
1884
- | map(.sha = (if $sha != "" then headsha(if $plain == "" then $branch else ($job | split("/") | last) end) else headsha($branch) end) | del(.shas, .br))' || exit 4
2103
+ | if $sha != "" then map(select(headsha(.records) as $h | $h == $sha or (($sha | test("^[0-9a-f]{7,}$")) and ($h | startswith($sha)))))
2104
+ elif $plain == "" then . else map(select(any(.records[].branches[]; . == $branch))) end
2105
+ | map(.sha = headsha(.records) | del(.records)) | .[0:$limit]' || exit 4
1885
2106
  }
1886
2107
 
1887
2108
  # The sha-bound readings of the PR rows $3 whose branch colour in $2 cannot
1888
2109
  # settle the head: a JSON object keyed by branch, or nothing where no lookup
1889
2110
  # was needed. $1 = the op's name, $4 = optional path to also receive the
1890
2111
  # branches `rowsToBind` named this pass (one per line), so a caller can tell
1891
- # "named but the ask broke early" (the colour must still stand, per "absent is
1892
- # not false") from "never named because the row is past the cap" (the colour
1893
- # must not stand) without a second, duplicate run of the same `rows` verb.
2112
+ # "named but the ask broke early" from "never named because the row is past
2113
+ # the cap" without a second, duplicate run of the same `rows` verb. A row past
2114
+ # the cap never stands on its colour. A named row whose ask broke stands on it
2115
+ # in GitHub's `pr-list`, and reads `checksLookup: broken` in Bitbucket's
2116
+ # `pr-list` and `pr-state`.
1894
2117
  # $5 = optional JSON object, branch -> the checksSha the caller's PR index
1895
2118
  # already has on record; a branch bound there to its CURRENT head costs the
1896
2119
  # pass nothing to re-confirm, so `rowsToBind` (rotation) spends the cap's
1897
2120
  # lookups on branches that are absent or stale there first. Absent entirely
1898
2121
  # where the caller holds no index — every row then sorts exactly as before.
1899
2122
  # `jenkins_sha_runs` reads each named row by sha, the bundle binds them. A
1900
- # lookup that cannot ask Jenkins ends the pass, and the colour stands.
2123
+ # lookup that cannot ask Jenkins ends the pass, and the rows it did not reach
2124
+ # get no bound entry. A failing `rows` call itself (the bundle crashes or
2125
+ # prints nothing) empties $4 and returns with no stdout at all, so every
2126
+ # ambiguous row this pass reads unknown rather than some subset of them.
1901
2127
  jenkins_bind_rows() {
1902
2128
  local _named; _named="$({ jq -c . <<<"$2"; jq -c . <<<"$3"; jq -c . <<<"${5:-null}"; } | node "$here/board/plot-jenkins-pr-checks.mjs" rows 2>/dev/null)"
1903
2129
  : >"${4:-/dev/null}"; [ -z "$_named" ] && return; cut -f1 <<<"$_named" >"${4:-/dev/null}"
@@ -1906,38 +2132,94 @@ jenkins_bind_rows() {
1906
2132
  done | node "$here/board/plot-jenkins-pr-checks.mjs" bind 2>/dev/null
1907
2133
  }
1908
2134
 
2135
+ # Seconds `bb_fold_mergeable` allows one `git fetch` of the base before
2136
+ # treating it as failed. `Checks wait` (3600s) is sized for a CI poll, not one
2137
+ # fetch; this is its own, much smaller bound. No config key is read nearby
2138
+ # this call site, so a constant stands, per the plan.
2139
+ readonly BB_FETCH_BOUND_S=10
2140
+
2141
+ # Runs `git fetch -q origin "+refs/heads/$1:refs/remotes/origin/$1"` and kills
2142
+ # it if it outruns `BB_FETCH_BOUND_S`, so a stalled SSH prompt (`git fetch` has
2143
+ # no built-in timeout) cannot hang `pr-state`/`pr-list` on one row. A timed-out
2144
+ # fetch exits non-zero, same as any other failed fetch — the caller cannot and
2145
+ # need not tell the two apart (#2481).
2146
+ bb_fetch_base_bounded() {
2147
+ local base="$1" pid watcher rc was_m
2148
+ # `git fetch` can itself spawn a child (an askpass helper, ssh, a credential
2149
+ # helper) that inherits this function's stdout/stderr. Killing only $pid
2150
+ # leaves that child orphaned and still holding the pipe open, so a caller
2151
+ # waiting on the pipe to close (not just on $pid to exit) stays blocked for
2152
+ # the full hang rather than the bound — measured against a stub `git fetch`
2153
+ # that forks a long-running child: `kill -TERM "$pid"` alone left the run
2154
+ # waiting the full duration even though `bb_fetch_base_bounded` itself had
2155
+ # already returned. `set -m` makes the backgrounded `git fetch` the leader
2156
+ # of its own process group, so `kill -TERM "-$pid"` (the negative pid) signals
2157
+ # the whole group — fetch and any child it spawned — not just the leader.
2158
+ case $- in *m*) was_m=yes ;; *) was_m=no ;; esac; set -m
2159
+ GIT_TERMINAL_PROMPT=0 git fetch -q origin "+refs/heads/$base:refs/remotes/origin/$base" 2>/dev/null & pid=$!
2160
+ ( sleep "$BB_FETCH_BOUND_S"; kill -TERM "-$pid" 2>/dev/null ) & watcher=$!
2161
+ wait "$pid" 2>/dev/null; rc=$?
2162
+ kill "$watcher" 2>/dev/null; wait "$watcher" 2>/dev/null; [ "$was_m" = yes ] || set +m
2163
+ return "$rc"
2164
+ }
2165
+
1909
2166
  # Overlays the `mergeable` reading on a Bitbucket `pr-state`/`pr-list` row ($1,
1910
2167
  # carrying `state`, `headSha` and `base`) from a local `git merge-tree
1911
2168
  # --write-tree` check; Bitbucket Cloud's REST API has no conflict field (see
1912
- # `bitbucket-pr-reading.ts`). The bundle folds the reading into an OPEN row and
1913
- # returns every other row unchanged, so git runs for OPEN rows only.
2169
+ # `bitbucket-pr-reading.ts`). A row that is not `OPEN` is printed unchanged
2170
+ # before any `jq`, `git` or `node` runs for it — MERGED and CLOSED rows are
2171
+ # settled, and a NONE row has no PR, so none of that work is theirs to pay for
2172
+ # (#2481).
2173
+ #
2174
+ # $2 = the repo slug (`owner/repo`) the caller resolved the row against, via
2175
+ # `--repo`; empty where the caller passed none. The fold runs `git` in the
2176
+ # CURRENT directory against ITS `origin` — a row from another repository would
2177
+ # be folded against the wrong base, silently. So a non-empty $2 that does not
2178
+ # match the local clone's `origin` slug (read through `plot-bitbucket-slug.mjs`,
2179
+ # the same bundle the Bitbucket build-status write resolves `origin` with)
2180
+ # answers `unknown` naming the mismatch, and never guesses by running git
2181
+ # anyway. A clone whose `origin` resolves to no slug cannot be compared either,
2182
+ # and also answers `unknown` rather than assume a match.
1914
2183
  #
1915
2184
  # The base is fetched ALONE, once per distinct base per invocation
1916
- # (`BB_FETCHED`), and a failed fetch reads `unknown`: a fetch that names the
1917
- # head too fails whole on Bitbucket's short hash, and the stale `origin/<base>`
1918
- # it leaves behind answers wrongly with confidence (#2208). The head is never
1919
- # fetched; a head commit absent from the clone reads `unknown` with its sha.
1920
- # `git fetch` is a git read, not a host CLI call, so the host stays unasked.
1921
- # A bundle that cannot answer prints the unchanged row.
2185
+ # (`BB_FETCHED`), bounded by `bb_fetch_base_bounded`, and a failed or timed-out
2186
+ # fetch reads `unknown`: a fetch that names the head too fails whole on
2187
+ # Bitbucket's short hash, and the stale `origin/<base>` it leaves behind
2188
+ # answers wrongly with confidence (#2208). The head is never fetched; a head
2189
+ # commit absent from the clone reads `unknown` with its sha. `git fetch` is a
2190
+ # git read, not a host CLI call, so the host stays unasked. A bundle that
2191
+ # cannot answer prints the unchanged row.
1922
2192
  bb_fold_mergeable() {
1923
- local row="$1" state head base fetch="" in_clone="" mt_code="" mt_err=""
1924
- IFS=$'\x1f' read -r state head base < <(jq -r '[.state, (.headSha // ""), (.base // "")] | join("\u001f")' <<<"$row" 2>/dev/null)
1925
- if [ "$state" = OPEN ] && [ -n "$head" ] && [ -n "$base" ]; then
1926
- case " ${BB_FETCHED:-} " in *" $base=ok "*) fetch=ok ;; *" $base=failed "*) fetch=failed ;; *) GIT_TERMINAL_PROMPT=0 git fetch -q origin "+refs/heads/$base:refs/remotes/origin/$base" 2>/dev/null && fetch=ok || fetch=failed; BB_FETCHED="${BB_FETCHED:-} $base=$fetch" ;; esac
2193
+ local row="$1" wantrepo="${2:-}" head base fetch="" in_clone="" mt_code="" mt_err="" localrepo reason
2194
+ jq -e '.state == "OPEN"' >/dev/null 2>&1 <<<"$row" || { printf '%s\n' "$row"; return 0; }
2195
+ if [ -n "$wantrepo" ]; then
2196
+ localrepo="$(node "$here/board/plot-bitbucket-slug.mjs" "$(git config --get remote.origin.url 2>/dev/null)" 2>/dev/null)"
2197
+ [ "$localrepo" = "$wantrepo" ] || { reason="this checkout's origin is ${localrepo:-unrecognised}, not $wantrepo — cannot fold mergeable against the wrong clone"; jq -c --arg reason "$reason" '. + {mergeable:"unknown", mergeableReason:$reason}' <<<"$row"; return 0; }
2198
+ fi
2199
+ IFS=$'\x1f' read -r head base < <(jq -r '[(.headSha // ""), (.base // "")] | join("\u001f")' <<<"$row" 2>/dev/null)
2200
+ if [ -n "$head" ] && [ -n "$base" ]; then
2201
+ case " ${BB_FETCHED:-} " in *" $base=ok "*) fetch=ok ;; *" $base=failed "*) fetch=failed ;; *) bb_fetch_base_bounded "$base" && fetch=ok || fetch=failed; BB_FETCHED="${BB_FETCHED:-} $base=$fetch" ;; esac
1927
2202
  git cat-file -e "$head^{commit}" 2>/dev/null && in_clone=yes || in_clone=no
1928
2203
  [ "$fetch$in_clone" = okyes ] && { mt_err="$(git merge-tree --write-tree "origin/$base" "$head" 2>&1 >/dev/null)"; mt_code=$?; }
1929
2204
  fi
1930
2205
  printf '%s\n' "$row" "$head" "${base:+origin/$base}" "$(git --version 2>/dev/null)" "$fetch" "$in_clone" "$mt_code" "$mt_err" | node "$here/board/plot-bitbucket-mergeable.mjs" 2>/dev/null || printf '%s\n' "$row"
1931
2206
  }
1932
2207
 
1933
- # `pr-list --rich`'s per-line fold. Each row carries a `base` key only for
2208
+ # `pr-list --rich`'s per-line fold. $1 = the repo slug (see `bb_fold_mergeable`),
2209
+ # threaded onto every row. Each row carries a `base` key only for
1934
2210
  # `bb_fold_mergeable`, and this removes it again; an OPEN row whose reading is
1935
2211
  # `unknown` gains `mergeableReason`. The loop runs in one shell, so
1936
2212
  # `BB_FETCHED` holds across its rows.
1937
- bb_fold_mergeable_stream() { local line; while IFS= read -r line; do [ -z "$line" ] || bb_fold_mergeable "$line"; done | jq -c 'del(.base)'; }
2213
+ bb_fold_mergeable_stream() { local wantrepo="${1:-}" line; while IFS= read -r line; do [ -z "$line" ] || bb_fold_mergeable "$line" "$wantrepo"; done | jq -c 'del(.base)'; }
1938
2214
 
1939
2215
  # Prints the `pr-state` row of the Bitbucket PR payload $1 (`null` for no PR).
1940
2216
  #
2217
+ # $2 = "1" to ask Jenkins for the check at all; anything else (including
2218
+ # absent) skips `jenkins_instance`/`jenkins_build_map`/`jenkins_bind_rows`
2219
+ # entirely and reads `checks: unknown` with no Jenkins call made — the shell
2220
+ # side of `pr-state --with-checks`. The merge controller passes the flag;
2221
+ # `pr-merge`'s head re-read does not, because it reads only `headSha`.
2222
+ #
1941
2223
  # Without `CI: jenkins` the check is `unknown`, absent and not false, as in
1942
2224
  # `pr-list`'s plain Bitbucket arm. Under it the branch colour from
1943
2225
  # `jenkins_build_map` settles `none` and `pending`, and a head whose colour is
@@ -1946,9 +2228,14 @@ bb_fold_mergeable_stream() { local line; while IFS= read -r line; do [ -z "$line
1946
2228
  # `headSha` is `source.commit.hash`, a short hash `jenkins_sha_runs` prefix-matches.
1947
2229
  # `mergeable` is `unknown` here; `pr-state` folds the real reading on top with
1948
2230
  # `bb_fold_mergeable`, and `pr-merge --match-head` reads only `headSha`.
2231
+ #
2232
+ # A row `rowsToBind` names for a sha lookup whose `jenkins_sha_runs` call then
2233
+ # broke early (Jenkins unreachable mid-pass) must not stand on its stale branch
2234
+ # colour. The `state` verb asks `rowsToBind` itself whether this one row was
2235
+ # named, from the same colours, and reads it `checksLookup: broken`.
1949
2236
  bb_state_row() {
1950
2237
  local colours=null bound=null inst
1951
- if jq -e '.id' >/dev/null 2>&1 <<<"$1" && [ "$(ci_scheme)" = "jenkins" ]; then
2238
+ if [ "${2:-0}" = 1 ] && jq -e '.id' >/dev/null 2>&1 <<<"$1" && [ "$(ci_scheme)" = "jenkins" ]; then
1952
2239
  inst="$(jenkins_instance)"
1953
2240
  [ -z "$inst" ] || colours="$(jenkins_build_map "$inst" | jq -c 'if .status == "ok" then (.map // {}) else null end' 2>/dev/null)" || colours=null
1954
2241
  [ "$colours" = null ] || bound="$(jenkins_bind_rows pr-state "$colours" "$(jq -c '[{headRefName:.source.branch.name,headRefOid:.source.commit.hash}]' <<<"$1")")"
@@ -2292,7 +2579,8 @@ rest_pr_to_state() {
2292
2579
  state: $state,
2293
2580
  draft: (.draft // false),
2294
2581
  url: (.html_url // ""),
2295
- mergeCommit: (.merge_commit_sha // ""), headSha: (.head.sha // ""), base: (.base.ref // ""), checks: "unknown", mergeable: mergeable_of }
2582
+ mergeCommit: (.merge_commit_sha // ""), headSha: (.head.sha // ""), base: (.base.ref // ""), checks: "unknown", mergeable: mergeable_of,
2583
+ mergedAt: (.merged_at // "") }
2296
2584
  '
2297
2585
  }
2298
2586
 
@@ -2322,10 +2610,11 @@ rest_pr_to_state() {
2322
2610
  # A caller wanting it asks for it by name.
2323
2611
  bb_states_for() {
2324
2612
  case "$1" in
2325
- all) printf 'open\nmerged\ndeclined\n' ;;
2326
- closed) printf 'declined\n' ;;
2613
+ all) printf 'open\nmerged\ndeclined\n' ;;
2614
+ settled) printf 'merged\ndeclined\n' ;; # terminal only — no `open` sweep
2615
+ closed) printf 'declined\n' ;;
2327
2616
  open|merged|declined|superseded) printf '%s\n' "$1" ;;
2328
- *) die "unknown --state '$1' for the bitbucket backend (open|merged|closed|declined|superseded|all)" ;;
2617
+ *) die "unknown --state '$1' for the bitbucket backend (open|merged|closed|declined|superseded|all|settled)" ;;
2329
2618
  esac
2330
2619
  }
2331
2620
 
@@ -2424,8 +2713,7 @@ bb_assert_issue_version() {
2424
2713
  # it answers *not proven* (1) and the caller keeps its exit-3 refusal: guessing
2425
2714
  # 4 from unreadable help would turn a broken bb into *no issue tracker*.
2426
2715
  bb_lacks_issue_command() {
2427
- local help
2428
- help="$(bb --help 2>&1 | bb_strip_ansi)" || return 1
2716
+ local help; help="$(bb --help 2>&1 | bb_strip_ansi)" || return 1
2429
2717
  grep -qE '^[[:space:]]+pr([[:space:]]|$)' <<<"$help" || return 1
2430
2718
  ! grep -qE '^[[:space:]]+issues?([[:space:]]|$)' <<<"$help"
2431
2719
  }
@@ -2473,8 +2761,7 @@ bb_identify() {
2473
2761
  }
2474
2762
  ver_stripped="$(bb_strip_ansi <<<"$ver_out")"
2475
2763
 
2476
- local version
2477
- version="$(grep -oE '[0-9]+\.[0-9]+\.[0-9]+' <<<"$ver_stripped" | head -1)"
2764
+ local version; version="$(grep -oE '[0-9]+\.[0-9]+\.[0-9]+' <<<"$ver_stripped" | head -1)"
2478
2765
  [ -z "$version" ] && version="unknown"
2479
2766
 
2480
2767
  # craftamap/bb includes a git sha in parentheses: `bb version 0.6.0 (abc1234)`
@@ -2510,8 +2797,7 @@ bb_test_json_support() {
2510
2797
  # reader can reproduce — rather than a provenance verdict `bb_identify`
2511
2798
  # cannot determine. A message that guesses wrong costs more than one that
2512
2799
  # says less.
2513
- BB_CAP_PROBE_RC="$rc"
2514
- BB_CAP_PROBE_MATCH=""
2800
+ BB_CAP_PROBE_RC="$rc"; BB_CAP_PROBE_MATCH=""
2515
2801
 
2516
2802
  # THE MEASUREMENT ANSWERS FIRST, AND THE TEXT ONLY WHEN IT IS ABSENT.
2517
2803
  #
@@ -2765,7 +3051,11 @@ read_env_var() { # $1=name $2=file → the value, or nothing
2765
3051
  # desk or a scratch worktree under `Worktree root` has none of its own, and
2766
3052
  # `git rev-parse --show-toplevel` there answers with the WORKTREE, which never
2767
3053
  # holds one. Prints "<path>|" (worktree) or "<path>|the main checkout's" on a
2768
- # readable candidate, or nothing when neither location has one.
3054
+ # candidate, or nothing when neither location has one.
3055
+ #
3056
+ # $1 and $2 name the two vars a candidate must hold BOTH of — every caller
3057
+ # needs a pair, never a lone half, so a readable-but-incomplete candidate is
3058
+ # skipped in favour of the next one rather than returned anyway.
2769
3059
  #
2770
3060
  # NO UPWARD WALK past either location — the fallback is exactly one more
2771
3061
  # place to look, not a search. `--git-common-dir`'s parent is the main
@@ -2773,10 +3063,19 @@ read_env_var() { # $1=name $2=file → the value, or nothing
2773
3063
  # command fails, prints nothing, or its parent directory does not exist, this
2774
3064
  # falls through to "no main checkout .env" rather than inventing a path.
2775
3065
  plot_env_file() {
2776
- local root env_file common; root="$(git rev-parse --show-toplevel 2>/dev/null)" || root="."; env_file="$root/.env"
2777
- [ -r "$env_file" ] && { printf '%s|' "$env_file"; return 0; }
2778
- common="$(git rev-parse --git-common-dir 2>/dev/null)" && [ -n "$common" ] || return 0
2779
- env_file="$(dirname "$common")/.env"; [ -r "$env_file" ] && printf "%s|the main checkout's " "$env_file"
3066
+ local root env_file common
3067
+ root="$(git rev-parse --show-toplevel 2>/dev/null)" || root="."; env_file="$root/.env"
3068
+ plot_env_file_qualifies "$env_file" "$1" "$2" && { printf '%s|' "$env_file"; return 0; }
3069
+ common="$(git rev-parse --path-format=absolute --git-common-dir 2>/dev/null)" && [ -n "$common" ] || return 0
3070
+ env_file="$(dirname "$common")/.env"
3071
+ plot_env_file_qualifies "$env_file" "$1" "$2" && printf "%s|the main checkout's " "$env_file"
3072
+ }
3073
+
3074
+ # A candidate qualifies when it is readable and holds both named vars —
3075
+ # never a lone half of a pair.
3076
+ plot_env_file_qualifies() {
3077
+ [ -r "$1" ] || return 1
3078
+ [ -n "$(read_env_var "$2" "$1")" ] && [ -n "$(read_env_var "$3" "$1")" ]
2780
3079
  }
2781
3080
 
2782
3081
  # The env var scheme for Jira auth. The plan left the EXACT names open, to be
@@ -2792,20 +3091,18 @@ plot_env_file() {
2792
3091
  # `die3` exits the whole script only from there, not from inside a command
2793
3092
  # substitution where it would end only the subshell and leak a second error.
2794
3093
  #
2795
- # WHERE BOTH ARE UNSET, `plot_env_file` IS READ, same order and both-or-neither
2796
- # rule as `jenkins_rest_credential` — measured 2026-09-17, an operator holding
2797
- # a working pair was sent to create a second token before this fallback
2798
- # existed. THE VALUE IS NEVER PRINTED, only the source, so a 401 can be
2799
- # debugged against the right one of two possible tokens.
3094
+ # WHERE BOTH ARE UNSET, `plot_env_file` IS READ, naming the two vars so it
3095
+ # skips a candidate holding only one — measured 2026-09-17, an operator
3096
+ # holding a working pair was sent to create a second token before this
3097
+ # fallback existed. THE VALUE IS NEVER PRINTED, only the source, so a 401 can
3098
+ # be debugged against the right one of two possible tokens.
2800
3099
  jira_load_env_file() {
2801
- local found env_file source email token
3100
+ local found env_file
2802
3101
  [ -z "${JIRA_EMAIL:-}" ] && [ -z "${JIRA_API_TOKEN:-}" ] || return 0
2803
- found="$(plot_env_file)"; [ -n "$found" ] || return 0; env_file="${found%|*}"; source="${found#*|}"
2804
- email="$(read_env_var JIRA_EMAIL "$env_file")"; token="$(read_env_var JIRA_API_TOKEN "$env_file")"
2805
- # BOTH OR NEITHER. Half a Basic credential authenticates nothing, and a
2806
- # partial pickup would turn today's honest refusal into a 401 further in.
2807
- [ -n "$email" ] && [ -n "$token" ] || return 0
2808
- export JIRA_EMAIL="$email" JIRA_API_TOKEN="$token"; echo "plot-host: JIRA_EMAIL and JIRA_API_TOKEN read from ${source}.env" >&2
3102
+ found="$(plot_env_file JIRA_EMAIL JIRA_API_TOKEN)"; [ -n "$found" ] || return 0
3103
+ env_file="${found%|*}"
3104
+ export JIRA_EMAIL="$(read_env_var JIRA_EMAIL "$env_file")" JIRA_API_TOKEN="$(read_env_var JIRA_API_TOKEN "$env_file")"
3105
+ echo "plot-host: JIRA_EMAIL and JIRA_API_TOKEN read from ${found#*|}.env" >&2
2809
3106
  }
2810
3107
 
2811
3108
  jira_require_config() {
@@ -2870,8 +3167,7 @@ jira_curl() {
2870
3167
  jira_budget_account() {
2871
3168
  local raw="${JIRA_EMAIL:-}"
2872
3169
  [ -n "$raw" ] || { printf 'unknown\n'; return 0; }
2873
- local h
2874
- h="$(printf '%s' "$raw" | shasum -a 256 2>/dev/null | awk '{print $1}')"
3170
+ local h; h="$(printf '%s' "$raw" | shasum -a 256 2>/dev/null | awk '{print $1}')"
2875
3171
  # No hasher, no guess: a raw email must never be the fallback, so an
2876
3172
  # unhashable account degrades to the same word an absent one uses.
2877
3173
  [ -n "$h" ] || { printf 'unknown\n'; return 0; }
@@ -2930,10 +3226,17 @@ jira_ask() { local raw rc; raw="$(jira_curl "$@")"; rc=$?; jira_check "$raw" "$r
2930
3226
  # github (HONOURS --limit) : a state is possibly truncated when it returned
2931
3227
  # AT LEAST the requested limit. Fewer rows than
2932
3228
  # the limit PROVES completeness.
2933
- # bitbucket (ONE FIXED PAGE): the listing ignores --limit and returns one page
2934
- # per state. A page SHORTER than the page length
2935
- # is the last page, so it is complete. A page AT
2936
- # the length stays possibly truncated.
3229
+ # bitbucket (FIXED PAGE) : `bb_state_listing` FOLLOWS `next` UP TO
3230
+ # `--limit` (`_bb_paged_walk`'s row-limit mode)
3231
+ # over fixed `pagelen`-row pages, so the kind
3232
+ # stays `fixed-page` rather than becoming
3233
+ # `honours-limit` — see `listingPagingFor`. The
3234
+ # walk is complete when its last page named no
3235
+ # `next` and it trimmed no row, and possibly
3236
+ # truncated when it stopped with a `next` named
3237
+ # or a row trimmed. Where no envelope was read,
3238
+ # a page SHORTER than the measured length is
3239
+ # complete (below).
2937
3240
  #
2938
3241
  # THE PAGE LENGTH IS A READING, NEVER A CONSTANT THE RULE NAMES. The listing
2939
3242
  # asks `pagelen=$BB_LIST_PAGELEN` through `bb api`, and the length holds only
@@ -2971,8 +3274,9 @@ jira_ask() { local raw rc; raw="$(jira_curl "$@")"; rc=$?; jira_check "$raw" "$r
2971
3274
  # into a minutes-long pulse. See the plan's Done-when item 3.
2972
3275
  #
2973
3276
  # The page length Bitbucket's plain listing asks for. `bb_state_listing` sends
2974
- # it, and `pr_list_report_truncation` reads it as the page length only for a
2975
- # `bb` in BB_LIST_PAGE_VERSIONS.
3277
+ # it, `_bb_paged_walk` bounds a row-limit walk at ceil(limit / this) pages, and
3278
+ # `pr_list_report_truncation` reads it as the page length only for a `bb` in
3279
+ # BB_LIST_PAGE_VERSIONS.
2976
3280
  BB_LIST_PAGELEN=50
2977
3281
 
2978
3282
  # The `bb` versions measured to pass `pagelen` through `bb api` unchanged,
@@ -3016,13 +3320,12 @@ bb_list_page_length() {
3016
3320
  # version. #1757: `BB_LIST_PAGE_VERSIONS` names only versions this estate has
3017
3321
  # measured, so a page from any other version (1.11.1 included) could never be
3018
3322
  # proven complete by row count alone — 9 rows with no `next` read as "possibly
3019
- # truncated" even though the envelope already answered. A page WITH `next`
3020
- # proves nothing either way (Bitbucket could in principle set it with zero rows
3021
- # left), so it falls through to the length test exactly as before. Absence,
3022
- # never presence, is the signal — `$5` is "0" only when `bb_state_listing` read
3023
- # an envelope with no `next` key; "1" means `next` was present; "" means no
3024
- # envelope shape was read at all, and the version table alone decides, as
3025
- # before this slice.
3323
+ # truncated" even though the envelope already answered. With a limit,
3324
+ # `_bb_paged_walk` follows `next` and writes the reading of the page where it
3325
+ # stopped, or "1" where it trimmed rows: "0" proves the walk whole, and "1"
3326
+ # means a further page or a dropped row exists, so it is possibly truncated at
3327
+ # any row count, including 0. Only "" (no envelope shape was read) falls back
3328
+ # to the version table's page length.
3026
3329
  #
3027
3330
  # $1 backend $2 requested limit (may be "") $3 state word $4 row count
3028
3331
  # $5 envelope's own completeness reading: "0" no next, "1" next present, ""
@@ -3030,8 +3333,12 @@ bb_list_page_length() {
3030
3333
  pr_list_report_truncation() {
3031
3334
  local be="$1" limit="$2" state="$3" count="$4" next="${5:-}" len=""
3032
3335
  # no --limit → no completeness claim owed; an empty page had nothing to hide
3033
- [ -n "$limit" ] || return 0; [ "$count" -gt 0 ] 2>/dev/null || return 0
3336
+ [ -n "$limit" ] || return 0; [ "$count" -gt 0 ] 2>/dev/null || [ "$next" = "1" ] || return 0
3034
3337
  if [ "$be" = "github" ]; then
3338
+ # `gh` pages inside this one process and `gh()` recorded one request for it, so
3339
+ # the pages past the first are recorded here, from the rows: a request count,
3340
+ # not GraphQL points. The rule is the domain's (`githubExtraPages`).
3341
+ budget_record_call github github graphql "$(node "$here/board/plot-listing-pages.mjs" "$count" 2>/dev/null)"
3035
3342
  # github honours the limit: complete unless the page came back AT the limit.
3036
3343
  # Measured 2026-10-02 on this repository (1064 PRs): `--limit 1100`
3037
3344
  # answered 1065 rows and `--limit 2000` the same 1065, so a page short of
@@ -3039,9 +3346,10 @@ pr_list_report_truncation() {
3039
3346
  # exist rather than the rows requested.
3040
3347
  if [ "$count" -lt "$limit" ] 2>/dev/null; then pr_list_report_complete "$be" "$limit" "$state" "$count"; return 0; fi
3041
3348
  else
3042
- # A fixed page: complete below a measured length, or whose own envelope
3043
- # named no further page — unprovable otherwise.
3044
- [ "$next" = "0" ] || len="$(bb_list_page_length)"
3349
+ # A walk whose last page named no further page is complete; one that
3350
+ # stopped with a further page named or rows trimmed is not; an unread
3351
+ # envelope is complete only below a measured page length.
3352
+ [ -n "$next" ] || len="$(bb_list_page_length)"
3045
3353
  if [ "$next" = "0" ] || { [ -n "$len" ] && [ "$count" -lt "$len" ] 2>/dev/null; }; then pr_list_report_complete "$be" "$limit" "$state" "$count"; return 0; fi
3046
3354
  fi
3047
3355
  # Named per state so a caller can resolve exactly the states that were
@@ -3091,8 +3399,7 @@ backend_declared() {
3091
3399
  printf '%s\n' "$PLOT_HOST" | tr '[:upper:]' '[:lower:]'
3092
3400
  return
3093
3401
  fi
3094
- local v
3095
- v="$(bash "$here/plot-config.sh" get "Git host" "" | tr '[:upper:]' '[:lower:]')"
3402
+ local v; v="$(bash "$here/plot-config.sh" get "Git host" "" | tr '[:upper:]' '[:lower:]')"
3096
3403
  case "$v" in
3097
3404
  bb) echo "bitbucket"; return ;;
3098
3405
  "") : ;;
@@ -3108,8 +3415,7 @@ backend_declared() {
3108
3415
  # THE REMOTE IS EVIDENCE AND THE KEY IS A DECLARATION, so the key still wins
3109
3416
  # above. What changes is only the case where nobody said: a hostname in the
3110
3417
  # remote is a reading, and no remote is no reading.
3111
- local url
3112
- url="$(git config --get remote.origin.url 2>/dev/null || true)"
3418
+ local url; url="$(git config --get remote.origin.url 2>/dev/null || true)"
3113
3419
  case "$url" in
3114
3420
  *github.com*) echo "github"; return ;;
3115
3421
  *bitbucket.org*) echo "bitbucket"; return ;;
@@ -3355,8 +3661,11 @@ PLOT_BUDGET_HARVEST=""
3355
3661
  # and a full REST one summed to a number describing neither. Measured
3356
3662
  # 2026-09-01 from the response headers: `core` 4990 of 5000, `graphql` 0 of
3357
3663
  # 5000.
3358
- budget_record_call() { # $1=connector $2=backend-for-account $3=bucket
3664
+ budget_record_call() { # $1=connector $2=backend-for-account $3=bucket $4=spent (default 1; 0 or empty records nothing)
3359
3665
  [ -z "${PLOT_BUDGET_OFF:-}" ] || return 0
3666
+ # A spend that is not a positive number records nothing: the caller asked a rule
3667
+ # for it and the rule did not answer, and a made-up `1` would be a made-up spend.
3668
+ [ "${4-1}" -gt 0 ] 2>/dev/null || return 0
3360
3669
  local reading account bucket
3361
3670
  account="$(budget_account "${2:-$1}")"
3362
3671
  bucket="${3:-}"; [ -n "$bucket" ] || bucket="$(budget_bucket "$1")"
@@ -3364,18 +3673,17 @@ budget_record_call() { # $1=connector $2=backend-for-account $3=bucket
3364
3673
  # bucket: `X-RateLimit-Resource` names `code_search` for a search that no
3365
3674
  # reading of the command line would have classified as anything but `core`.
3366
3675
  if [ -n "${PLOT_BUDGET_HARVEST:-}" ]; then
3367
- IFS=$'\t' read -r _hbkt _blim _brem _brst <<<"$PLOT_BUDGET_HARVEST"
3368
- PLOT_BUDGET_HARVEST=""
3676
+ IFS=$'\t' read -r _hbkt _blim _brem _brst <<<"$PLOT_BUDGET_HARVEST"; PLOT_BUDGET_HARVEST=""
3369
3677
  [ -z "$_hbkt" ] || bucket="$_hbkt"
3370
3678
  # `actual` is the one basis a caller is entitled to trust, and a harvested
3371
3679
  # header is the only thing in this script that earns it: the connector said
3372
3680
  # it, about the call that just happened.
3373
- budget_append "$1" "$account" "$bucket" 1 "$_blim" "$_brem" "$_brst" actual
3681
+ budget_append "$1" "$account" "$bucket" "${4:-1}" "$_blim" "$_brem" "$_brst" actual
3374
3682
  return 0
3375
3683
  fi
3376
3684
  reading="$(budget_reading "$1")"
3377
3685
  IFS=$'\t' read -r _blim _brem _brst _bbas <<<"$reading"
3378
- budget_append "$1" "$account" "$bucket" 1 "$_blim" "$_brem" "$_brst" "$_bbas"
3686
+ budget_append "$1" "$account" "$bucket" "${4:-1}" "$_blim" "$_brem" "$_brst" "$_bbas"
3379
3687
  }
3380
3688
 
3381
3689
  # Reads `X-RateLimit-*` out of a header block, into the harvest variable.
@@ -3549,13 +3857,11 @@ host_concurrency_bound() { # $1=connector $2=account
3549
3857
  # the cadence degrade. The cost of one extra simultaneous call is a secondary
3550
3858
  # refusal that lowers the bound — evidence, through the mechanism this slice is
3551
3859
  # built on.
3552
- PLOT_SLOT_WAIT_MAX_S=30
3553
- PLOT_SLOT_POLL_S=1
3860
+ PLOT_SLOT_WAIT_MAX_S=30; PLOT_SLOT_POLL_S=1
3554
3861
 
3555
3862
  # The slot this process holds, so the wrappers can give it back. Empty where
3556
3863
  # none was taken — an unbounded connector, or a wait that ran out.
3557
- PLOT_SLOT_INDEX=''
3558
- PLOT_SLOT_ACCOUNT=''
3864
+ PLOT_SLOT_INDEX=''; PLOT_SLOT_ACCOUNT=''
3559
3865
 
3560
3866
  # Claims a slot for the call about to be made, waiting where the account is
3561
3867
  # busy. Never refuses: at worst it proceeds unbounded, which is what every
@@ -3629,6 +3935,12 @@ shift
3629
3935
  # answer at all" — the one code every caller reads as permanent rather than
3630
3936
  # transient. Collapsing it to 1 here would tell a GitLab repo to retry forever.
3631
3937
  be="$(backend)" || exit $?
3938
+ # PLOT_HOST_OTHER=1 ASKS THE OTHER DRIVABLE BACKEND, the `HOST_DRIVES` entry
3939
+ # that is not this checkout's own. `hostShell.prState` and `prMerged` set it to
3940
+ # retry a cross-repo `--repo` reference on a clean miss (#2158); the decision is
3941
+ # `rules/cross-repo-probe.ts`. The variable stays in the environment, so a
3942
+ # re-exec of this script asks the same backend.
3943
+ [ -z "${PLOT_HOST_OTHER:-}" ] || be="$(printf '%s\n' $HOST_DRIVES | awk -v be="$be" '$0 != be { o = $0 } END { print o }')"
3632
3944
 
3633
3945
  # EVERY GITHUB OP CONSULTS THE ROUTER, ONCE, HERE. `gh_route` is asked before
3634
3946
  # the op runs and its answer is read from `$route` by whichever arm needs it —
@@ -3728,10 +4040,11 @@ case "$op" in
3728
4040
 
3729
4041
  pr-state)
3730
4042
  ref="${1:?pr-state needs a PR number or branch}"; shift || true
3731
- repo_args=()
4043
+ repo_args=(); repo_slug=""; with_checks=0
3732
4044
  while [ $# -gt 0 ]; do
3733
4045
  case "$1" in
3734
- --repo) repo_args=(-R "${2:?}"); shift 2 ;;
4046
+ --repo) repo_args=(-R "${2:?}"); repo_slug="${2:?}"; shift 2 ;;
4047
+ --with-checks) with_checks=1; shift ;;
3735
4048
  *) die "pr-state: unknown arg $1" ;;
3736
4049
  esac
3737
4050
  done
@@ -3754,7 +4067,7 @@ case "$op" in
3754
4067
  rm -f "$HOST_ERR"
3755
4068
  rest_pr_to_state <<<"$out"
3756
4069
  else
3757
- err="$(cat "$HOST_ERR" 2>/dev/null)"; rm -f "$HOST_ERR"
4070
+ host_err
3758
4071
  host_miss_or_fail "$err" \
3759
4072
  '{"number":0,"state":"NONE","draft":false,"url":"","mergeCommit":""}' || exit $?
3760
4073
  fi
@@ -3775,7 +4088,7 @@ case "$op" in
3775
4088
  jq -c '.[0]' <<<"$out" | rest_pr_to_state
3776
4089
  fi
3777
4090
  else
3778
- err="$(cat "$HOST_ERR" 2>/dev/null)"; rm -f "$HOST_ERR"
4091
+ host_err
3779
4092
  host_miss_or_fail "$err" \
3780
4093
  '{"number":0,"state":"NONE","draft":false,"url":"","mergeCommit":""}' || exit $?
3781
4094
  fi
@@ -3783,11 +4096,11 @@ case "$op" in
3783
4096
  # mergeCommit is what lets a caller ask "which release contains this?" —
3784
4097
  # `git tag --contains <sha>` answers exactly, where dates cannot. It is ""
3785
4098
  # for anything unmerged, which is the honest answer rather than a guess.
3786
- elif out="$(gh ${repo_args[@]+"${repo_args[@]}"} pr view "$ref" --json number,state,isDraft,url,mergeCommit,headRefOid,baseRefName,statusCheckRollup,mergeable,mergeStateStatus 2>"$HOST_ERR")"; then
4099
+ elif out="$(gh ${repo_args[@]+"${repo_args[@]}"} pr view "$ref" --json number,state,isDraft,url,mergeCommit,headRefOid,baseRefName,statusCheckRollup,mergeable,mergeStateStatus,mergedAt 2>"$HOST_ERR")"; then
3787
4100
  rm -f "$HOST_ERR"
3788
- jq -c "$CHECKS_OF$MERGEABLE_OF"'{number:.number,state:.state,draft:.isDraft,url:.url,mergeCommit:(.mergeCommit.oid // ""),headSha:(.headRefOid // ""),base:(.baseRefName // ""),checks:checks_of,checksSha:(.headRefOid // ""),mergeable:mergeable_of}' <<<"$out"
4101
+ jq -c "$CHECKS_OF$MERGEABLE_OF"'{number:.number,state:.state,draft:.isDraft,url:.url,mergeCommit:(.mergeCommit.oid // ""),headSha:(.headRefOid // ""),base:(.baseRefName // ""),checks:checks_of,checksSha:(.headRefOid // ""),mergeable:mergeable_of,mergedAt:(.mergedAt // "")}' <<<"$out"
3789
4102
  else
3790
- err="$(cat "$HOST_ERR" 2>/dev/null)"; rm -f "$HOST_ERR"
4103
+ host_err
3791
4104
  # REFUSED FOR RATE IS NOT ANSWERED. The budget gate above could not see
3792
4105
  # this coming — `rate_limit` does not report the secondary limit — so the
3793
4106
  # cheap path was chosen and then declined. The second path is the one
@@ -3822,9 +4135,15 @@ case "$op" in
3822
4135
  if [[ "$ref" =~ ^[0-9]+$ ]]; then
3823
4136
  if out="$(bb ${repo_args[@]+"${repo_args[@]}"} pr view "$ref" --json 2>"$HOST_ERR")"; then
3824
4137
  rm -f "$HOST_ERR"
3825
- bb_fold_mergeable "$(bb_state_row "$out")"
4138
+ # `$(bb_state_row ...)` RUNS IN A SUBSHELL, so a failure inside it
4139
+ # (a bad Jenkins answer, an unreadable row) was lost the moment its
4140
+ # stdout was captured — `bb_fold_mergeable` always saw success. The
4141
+ # assignment's status is the substitution's, so `|| exit $?` ends the
4142
+ # op with it before `bb_fold_mergeable` (which cannot fail) runs.
4143
+ state_row="$(bb_state_row "$out" "$with_checks")" || exit $?
4144
+ bb_fold_mergeable "$state_row" "$repo_slug"
3826
4145
  else
3827
- err="$(cat "$HOST_ERR" 2>/dev/null)"; rm -f "$HOST_ERR"
4146
+ host_err
3828
4147
  host_miss_or_fail "$err" '{"number":0,"state":"NONE","draft":false,"url":"","mergeCommit":""}' || exit $?
3829
4148
  fi
3830
4149
  else
@@ -3881,9 +4200,13 @@ case "$op" in
3881
4200
  # The hash rides on the page the branch query already fetched, so this
3882
4201
  # costs no extra call. `bb_branch_query` already filtered to the
3883
4202
  # branch, so every row in `out` already matches it.
3884
- bb_fold_mergeable "$(bb_state_row "$(jq -c '.[0] // null' <<<"$out")")"
4203
+ #
4204
+ # The exit status is kept through the command substitution the same
4205
+ # way the numeric-ref arm above does — see its comment.
4206
+ state_row="$(bb_state_row "$(jq -c '.[0] // null' <<<"$out")" "$with_checks")" || exit $?
4207
+ bb_fold_mergeable "$state_row" "$repo_slug"
3885
4208
  else
3886
- err="$(cat "$HOST_ERR" 2>/dev/null)"; rm -f "$HOST_ERR"
4209
+ host_err
3887
4210
  host_miss_or_fail "$err" '{"number":0,"state":"NONE","draft":false,"url":"","mergeCommit":""}' || exit $?
3888
4211
  fi
3889
4212
  fi
@@ -3903,8 +4226,7 @@ case "$op" in
3903
4226
  # deciding whether to remove something. Exit 3 is still reserved for the call
3904
4227
  # itself failing in a way this adapter does not recognise as a miss.
3905
4228
  pr-merged)
3906
- ref="${1:?pr-merged needs a branch}"; shift || true
3907
- repo_args=()
4229
+ ref="${1:?pr-merged needs a branch}"; shift || true; repo_args=()
3908
4230
  while [ $# -gt 0 ]; do
3909
4231
  case "$1" in
3910
4232
  --repo) repo_args=(-R "${2:?}"); shift 2 ;;
@@ -3921,7 +4243,7 @@ case "$op" in
3921
4243
  rm -f "$HOST_ERR"
3922
4244
  jq -e 'any(.[]; .mergedAt != null)' >/dev/null 2>&1 <<<"$out" && echo "merged" || echo "not-merged"
3923
4245
  else
3924
- err="$(cat "$HOST_ERR" 2>/dev/null)"; rm -f "$HOST_ERR"
4246
+ host_err
3925
4247
  miss_or_unknown "$err"
3926
4248
  fi
3927
4249
  else
@@ -3936,16 +4258,11 @@ case "$op" in
3936
4258
  # ceiling (see `bb_branch_sweep`'s header).
3937
4259
  if out="$(bb_branch_query "$ref" merged ${repo_args[@]+"${repo_args[@]}"} 2>"$HOST_ERR")"; then
3938
4260
  rm -f "$HOST_ERR"
3939
- # A FULL PAGE CANNOT PROVE ABSENCE. `bb_branch_query` asks pagelen=50,
3940
- # and a branch carrying more than 50 merged PRs could hide a MERGED row
3941
- # past it — so 50 rows with none matching answers `unknown`, not
3942
- # `not-merged`, the same rule a failed call follows below.
3943
- if jq -e 'any(.[]; .state == "MERGED")' >/dev/null 2>&1 <<<"$out"; then echo "merged"
3944
- elif bb_full_page_lacks "$out" 'any(.[]; .state == "MERGED")'; then echo "plot-host: pr-merged: the branch query for '$ref' returned a full page with no merged PR; cannot prove absence" >&2; echo "unknown"
3945
- else echo "not-merged"
3946
- fi
4261
+ # `bb_branch_query` now follows every page, so a row's absence here is
4262
+ # the host's own answer rather than a page boundary (#2484).
4263
+ jq -e 'any(.[]; .state == "MERGED")' >/dev/null 2>&1 <<<"$out" && echo "merged" || echo "not-merged"
3947
4264
  else
3948
- err="$(cat "$HOST_ERR" 2>/dev/null)"; rm -f "$HOST_ERR"
4265
+ host_err
3949
4266
  miss_or_unknown "$err"
3950
4267
  fi
3951
4268
  fi
@@ -3967,8 +4284,8 @@ case "$op" in
3967
4284
  # this only for a branch it has already been told merged, and the plan it
3968
4285
  # serves budgets one host call per branch either way.
3969
4286
  #
3970
- # `--state all` and `--limit 100` for `pr-merged`'s own two reasons: a
3971
- # merged PR reports CLOSED, and the newest PR is not the merge.
4287
+ # `--state all` for `pr-merged`'s own two reasons: a merged PR reports
4288
+ # CLOSED, and the newest PR is not the merge.
3972
4289
  #
3973
4290
  # PRINTS NOTHING AND EXITS 0 where no PR merged — an ANSWER, the same shape
3974
4291
  # `pr-state` gives for a missing PR. Exit 3 is the question failing.
@@ -3976,10 +4293,13 @@ case "$op" in
3976
4293
  # `pr-merge-dest` RUNS THE SAME QUERY and prints every merged PR instead of
3977
4294
  # the first sha: one `number<TAB>base<TAB>sha<TAB>mergedAt` line each, read
3978
4295
  # off the same payload. `plot-release-chain.mjs` asks it once per hop of a
3979
- # release-chain walk. Bitbucket names no merge time, so `mergedAt` is
3980
- # `updated_on`, as in `pr-list`.
3981
- ref="${1:?$op needs a branch}"; shift || true
3982
- repo_args=()
4296
+ # release-chain walk, where under-reading is a silent wrong hop rather than
4297
+ # a cheap prefilter (#2238) — so GitHub's `--limit` grows and the query
4298
+ # re-asks until a page returns short of it, same proof as
4299
+ # `pr_list_report_truncation`. Bitbucket's arm already pages in full via
4300
+ # `_bb_paged_walk` (#2484); its `mergedAt` is `updated_on` as in `pr-list`,
4301
+ # since the endpoint carries no real merge timestamp (#2202).
4302
+ ref="${1:?$op needs a branch}"; shift || true; repo_args=()
3983
4303
  while [ $# -gt 0 ]; do
3984
4304
  case "$1" in
3985
4305
  --repo) repo_args=(-R "${2:?}"); shift 2 ;;
@@ -3988,19 +4308,27 @@ case "$op" in
3988
4308
  done
3989
4309
  if [ "$op" = pr-merge-dest ]; then pick='.[] | [.n, .b, .s, .t] | @tsv'; else pick='first.s // empty'; fi
3990
4310
  if [ "$be" = "github" ]; then
3991
- if out="$(gh ${repo_args[@]+"${repo_args[@]}"} pr list --head "$ref" --state all --limit 100 --json number,mergedAt,mergeCommit,baseRefName 2>"$HOST_ERR")"; then
4311
+ limit=100
4312
+ # A page as long as `--limit` may have been cut, so the limit doubles and
4313
+ # the query re-asks. The loop ends one of two ways: a short page, after
4314
+ # which `$HOST_ERR` is gone, or a failed call, which leaves `$HOST_ERR`
4315
+ # in place because the redirect creates it before `gh` runs.
4316
+ while out="$(gh ${repo_args[@]+"${repo_args[@]}"} pr list --head "$ref" --state all --limit "$limit" --json number,mergedAt,mergeCommit,baseRefName 2>"$HOST_ERR")"; do
3992
4317
  rm -f "$HOST_ERR"
3993
- # The FIRST merged PR carrying a sha. A branch may hold several merged
3994
- # PRs; each names its own merge commit, and any of them is a commit that
3995
- # landed this branch's work.
3996
- jq -r 'map(select(.mergedAt != null and .mergeCommit != null)
3997
- | {n: .number, b: (.baseRefName // ""), s: .mergeCommit.oid, t: .mergedAt}) | '"$pick" <<<"$out"
3998
- else
3999
- err="$(cat "$HOST_ERR" 2>/dev/null)"; rm -f "$HOST_ERR"
4318
+ [ "$(jq 'length' <<<"$out")" -lt "$limit" ] && break
4319
+ limit=$((limit * 2))
4320
+ done
4321
+ if [ -e "$HOST_ERR" ]; then
4322
+ host_err
4000
4323
  # A lookup miss is an answer: no PR, so no merge commit. Anything else
4001
4324
  # is the question failing, and silence must not read as "carried
4002
4325
  # nothing" — the caller distinguishes the two by the exit code.
4003
4326
  miss_or_exit3 "$err"
4327
+ else
4328
+ # Every merged PR carrying a sha, earliest-first ordering left to the
4329
+ # reader — `pickReleaseHop` and `pr-merge-commit`'s own `first` both sort.
4330
+ jq -r 'map(select(.mergedAt != null and .mergeCommit != null)
4331
+ | {n: .number, b: (.baseRefName // ""), s: .mergeCommit.oid, t: .mergedAt}) | '"$pick" <<<"$out"
4004
4332
  fi
4005
4333
  else
4006
4334
  bb_require_json
@@ -4009,11 +4337,10 @@ case "$op" in
4009
4337
  # `merge_commit.hash` on a merged PR.
4010
4338
  if out="$(bb_branch_query "$ref" merged ${repo_args[@]+"${repo_args[@]}"} 2>"$HOST_ERR")"; then
4011
4339
  rm -f "$HOST_ERR"
4012
- bb_full_page_lacks "$out" 'any(.[]; .merge_commit.hash != null)' && { echo "plot-host: $op: the branch query for '$ref' returned a full page with no merge commit; cannot prove absence" >&2; exit 3; }
4013
4340
  jq -r 'map(select(.merge_commit.hash != null)
4014
4341
  | {n: .id, b: (.destination.branch.name // ""), s: .merge_commit.hash, t: (.updated_on // "")}) | '"$pick" <<<"$out"
4015
4342
  else
4016
- err="$(cat "$HOST_ERR" 2>/dev/null)"; rm -f "$HOST_ERR"
4343
+ host_err
4017
4344
  miss_or_exit3 "$err"
4018
4345
  fi
4019
4346
  fi
@@ -4030,8 +4357,7 @@ case "$op" in
4030
4357
  # A FAILURE WITH NO MESSAGE IS A FAILURE HERE, unlike `pr-state`: an empty
4031
4358
  # answer makes the caller fall back to a patch-id reading, so silence must
4032
4359
  # not stand in for *no merged head*. Only a recognised lookup miss is empty.
4033
- ref="${1:?pr-merged-heads needs a branch}"; shift || true
4034
- repo_args=()
4360
+ ref="${1:?pr-merged-heads needs a branch}"; shift || true; repo_args=()
4035
4361
  while [ $# -gt 0 ]; do
4036
4362
  case "$1" in
4037
4363
  --repo) repo_args=(-R "${2:?}"); shift 2 ;;
@@ -4043,8 +4369,8 @@ case "$op" in
4043
4369
  rm -f "$HOST_ERR"
4044
4370
  jq -r '.[] | select(.mergedAt != null and .headRefOid != null) | .headRefOid' <<<"$out" || exit 3
4045
4371
  else
4046
- err="$(cat "$HOST_ERR" 2>/dev/null)"; rm -f "$HOST_ERR"
4047
- [ -n "$err" ] && is_lookup_miss "$err" || { echo "plot-host: ${err:-gh pr list failed}" >&2; exit 3; }
4372
+ host_err
4373
+ [ -n "$err" ] && is_lookup_miss "$err" || die3 "${err:-gh pr list failed}"
4048
4374
  fi
4049
4375
  else
4050
4376
  bb_require_json
@@ -4053,27 +4379,33 @@ case "$op" in
4053
4379
  # `source.commit.hash`.
4054
4380
  if out="$(bb_branch_query "$ref" merged ${repo_args[@]+"${repo_args[@]}"} 2>"$HOST_ERR")"; then
4055
4381
  rm -f "$HOST_ERR"
4056
- bb_full_page_lacks "$out" 'any(.[]; .source.commit.hash != null)' && { echo "plot-host: pr-merged-heads: the branch query for '$ref' returned a full page with no merged head; cannot prove absence" >&2; exit 3; }
4057
4382
  jq -r '.[] | (.source.commit.hash // empty)' <<<"$out" || exit 3
4058
4383
  else
4059
- err="$(cat "$HOST_ERR" 2>/dev/null)"; rm -f "$HOST_ERR"
4060
- [ -n "$err" ] && is_lookup_miss "$err" || { echo "plot-host: ${err:-the branch query failed}" >&2; exit 3; }
4384
+ host_err
4385
+ [ -n "$err" ] && is_lookup_miss "$err" || die3 "${err:-the branch query failed}"
4061
4386
  fi
4062
4387
  fi
4063
4388
  ;;
4064
4389
 
4065
4390
  pr-review)
4066
4391
  if [ "$be" != "github" ]; then
4067
- pr="/repositories/{ws}/{repo}/pullrequests/${1:?pr-review needs a PR number}"
4392
+ pr="/repositories/{ws}/{repo}/pullrequests/${1:?pr-review needs a PR number}"; detail="a bypass or check recorded only on a later page would be missed"
4393
+ # `_bb_paged_walk` (its own header has the cap/failure rule) follows
4394
+ # `next` for both reads, so a `review-bypass:` comment or a status
4395
+ # recorded only on a later page is not missed (#2484). THE WRAP GOES
4396
+ # THROUGH STDIN, NOT `--argjson`: that flag passes its value through
4397
+ # argv, which Linux caps at 128 KB (`MAX_ARG_STRLEN`) — a large enough
4398
+ # page would die silently and read as "no rows" on CI while passing on
4399
+ # macOS, the exact fabricated-absence bug this slice removes.
4068
4400
  out="$(bb api "$pr")" && sha="$(jq -re '.source.commit.hash' <<<"$out")" \
4069
- && st="$(bb api "/repositories/{ws}/{repo}/commit/$sha/statuses?sort=-created_on&pagelen=50")" && cm="$(bb api "$pr/comments?pagelen=100")" \
4070
- && printf '%s\n%s\n%s\n' "$sha" "$(jq -c . <<<"$st")" "$(jq -c . <<<"$cm")" | node "$here/board/plot-jenkins-pr-checks.mjs" review \
4071
- || { echo "plot-host: pr-review: the read failed" >&2; exit 3; }
4072
- exit 0
4073
- fi
4401
+ && st="$(_bb_paged_walk "/repositories/{ws}/{repo}/commit/$sha/statuses?sort=-created_on&pagelen=50" "bitbucket pr-review" "$detail" "" | jq -c '{values: .}')" \
4402
+ && cm="$(_bb_paged_walk "$pr/comments?pagelen=100" "bitbucket pr-review" "$detail" "" | jq -c '{values: .}')" \
4403
+ && printf '%s\n%s\n%s\n' "$sha" "$st" "$cm" | node "$here/board/plot-jenkins-pr-checks.mjs" review \
4404
+ || die3 "pr-review: the read failed"
4405
+ exit 0; fi
4074
4406
  out="$(gh pr view "${1:?pr-review needs a PR number}" --json headRefOid,comments)" && st="$(gh api "repos/{owner}/{repo}/commits/$(jq -r .headRefOid <<<"$out")/statuses")" \
4075
4407
  && jq -c --argjson st "$st" '{sha: .headRefOid, state: ([$st[] | select(.context == "plot/review")][0].state // "absent"), bypass: any(.comments[]?; .body | startswith("review-bypass:"))}' <<<"$out" \
4076
- || { echo "plot-host: pr-review: the read failed" >&2; exit 3; } ;;
4408
+ || die3 "pr-review: the read failed" ;;
4077
4409
 
4078
4410
  pr-create)
4079
4411
  title=""; body=""; base=""; head=""; draft=0
@@ -4115,14 +4447,14 @@ case "$op" in
4115
4447
  # answers 5 with its one-line notice where no key is declared: the merge
4116
4448
  # then runs as the signed-in `gh` identity. The token goes straight into
4117
4449
  # GH_TOKEN — never into argv, a file, or a log line.
4118
- merger_repo=$(gh repo view --json nameWithOwner --jq '.nameWithOwner' 2>/dev/null) || { echo "plot-host: pr-merge: gh repo view could not resolve owner/repo from the current checkout" >&2; exit 3; }
4450
+ merger_repo=$(gh repo view --json nameWithOwner --jq '.nameWithOwner' 2>/dev/null) || die3 "pr-merge: gh repo view could not resolve owner/repo from the current checkout"
4119
4451
  merger_token=$(node "$here/plot-merger-token.mjs" "$merger_repo") || { mc=$?; [ "$mc" = 5 ] || exit "$mc"; }
4120
4452
  args=(pr merge "$num"); [ "$squash" = 1 ] && args+=(--squash) || args+=(--merge); [ "$delbranch" = 1 ] && args+=(--delete-branch)
4121
4453
  if [ -n "$merger_token" ]; then GH_TOKEN="$merger_token" gh "${args[@]}" --match-head-commit "$pin"; else gh "${args[@]}" --match-head-commit "$pin"; fi
4122
4454
  # Bitbucket's merge endpoint takes no head precondition (measured 2026-10-18,
4123
4455
  # see plan Notes), so the pin is enforced by re-reading the head via bb_state_row
4124
4456
  # right before merging; it matches by prefix, 7+ hex (domain's sameCommit).
4125
- elif [ -n "$pin" ]; then bb_require_json; head_out="$(bb pr view "$num" --json 2>"$HOST_ERR")" || { err="$(cat "$HOST_ERR" 2>/dev/null)"; rm -f "$HOST_ERR"; echo "plot-host: $err" >&2; exit 3; }; rm -f "$HOST_ERR"; head_sha="$(bb_state_row "$head_out" | jq -r '.headSha // ""')"; head_l="$(printf '%s' "$head_sha" | tr '[:upper:]' '[:lower:]')"; pin_l="$(printf '%s' "$pin" | tr '[:upper:]' '[:lower:]')"; [[ "$head_l" =~ ^[0-9a-f]{7,}$ && "$pin_l" =~ ^[0-9a-f]{7,}$ ]] && { [[ "$head_l" == "$pin_l"* ]] || [[ "$pin_l" == "$head_l"* ]]; } || { echo "plot-host: pr-merge --match-head: head-moved — PR #$num is at ${head_sha:-unknown}, caller read $pin; nothing was merged" >&2; exit 1; }; args=(pr merge "$num"); [ "$squash" = 1 ] && args+=(--squash); [ "$delbranch" = 1 ] && args+=(--delete-branch); bb "${args[@]}"
4457
+ elif [ -n "$pin" ]; then bb_require_json; head_out="$(bb pr view "$num" --json 2>"$HOST_ERR")" || { host_err; die3 "$err"; }; rm -f "$HOST_ERR"; head_sha="$(bb_state_row "$head_out" | jq -r '.headSha // ""')"; head_l="$(printf '%s' "$head_sha" | tr '[:upper:]' '[:lower:]')"; pin_l="$(printf '%s' "$pin" | tr '[:upper:]' '[:lower:]')"; [[ "$head_l" =~ ^[0-9a-f]{7,}$ && "$pin_l" =~ ^[0-9a-f]{7,}$ ]] && { [[ "$head_l" == "$pin_l"* ]] || [[ "$pin_l" == "$head_l"* ]]; } || { echo "plot-host: pr-merge --match-head: head-moved — PR #$num is at ${head_sha:-unknown}, caller read $pin; nothing was merged" >&2; exit 1; }; args=(pr merge "$num"); [ "$squash" = 1 ] && args+=(--squash); [ "$delbranch" = 1 ] && args+=(--delete-branch); bb "${args[@]}"
4126
4458
  else
4127
4459
  echo "plot-host: pr-merge: bitbucket needs --match-head <sha>; nothing was merged" >&2
4128
4460
  exit 1
@@ -4148,8 +4480,7 @@ case "$op" in
4148
4480
  ;;
4149
4481
 
4150
4482
  pr-list)
4151
- state="open"
4152
- rich=0
4483
+ state="open"; rich=0
4153
4484
  # Whether the rich fields are asked of the OPEN pull requests only. Set by
4154
4485
  # `--rich-open`, which also sets `rich`: the flag narrows what is ASKED and
4155
4486
  # never what is emitted.
@@ -4160,7 +4491,7 @@ case "$op" in
4160
4491
  # — so a caller comparing `origin/*` refs would join its refs against
4161
4492
  # another repository's PRs and report every branch as having none. The
4162
4493
  # caller knows which remote its refs came from; this op cannot guess it.
4163
- repo_args=()
4494
+ repo_args=(); repo_slug=""
4164
4495
  # `gh pr list` and `bb pr list` both cap at 30 by default. That is invisible
4165
4496
  # with --state open (few repos have 30 open PRs) and bites immediately with
4166
4497
  # --state all, where the newest 30 crowd out every older merged PR. A caller
@@ -4193,7 +4524,7 @@ case "$op" in
4193
4524
  # With `--state open` asked, both calls would list the same PRs and the
4194
4525
  # second would be waste, so this collapses to plain `--rich` there.
4195
4526
  --rich-open) rich=1; rich_open=1; shift ;;
4196
- --repo) repo_args=(-R "${2:?}"); shift 2 ;;
4527
+ --repo) repo_args=(-R "${2:?}"); repo_slug="${2:?}"; shift 2 ;;
4197
4528
  # `${2:?}` REFUSES AN EMPTY VALUE, and that is the point rather than
4198
4529
  # boilerplate. `--since ""` would reach GitHub as `--search "updated:>"`,
4199
4530
  # a syntax error the host may answer with everything or with nothing —
@@ -4244,6 +4575,8 @@ case "$op" in
4244
4575
  # travel to GitHub as part of the term and match nothing.
4245
4576
  search_args=()
4246
4577
  [ -n "$since" ] && search_args=(--search "updated:>$since")
4578
+ # One named branch is asked as one: `--head` filters server-side in the same single list call.
4579
+ head_args=(); [ "$(wc -w <<<"$branches")" -eq 1 ] && head_args=(--head "$branches")
4247
4580
 
4248
4581
  # --- Jenkins CI integration (orthogonal to Git host) ---
4249
4582
  # When `CI: jenkins` is configured, build status comes from Jenkins rather
@@ -4278,6 +4611,11 @@ case "$op" in
4278
4611
  fi
4279
4612
 
4280
4613
  if [ "$be" = "github" ]; then
4614
+ # `settled` HAS NO GITHUB QUERY OF ITS OWN: `gh pr list --state all`
4615
+ # already returns every row, and the caller using `settled` (the fleet
4616
+ # scan's second call) already strips the OPEN ones itself. A second
4617
+ # filter here would duplicate that stripping rather than replace it.
4618
+ [ "$state" = "settled" ] && state="all"
4281
4619
  # THE SPLIT READ, AND IT IS TWO CALLS BECAUSE THE COST IS PER ROW.
4282
4620
  # `gh pr list` pages internally and takes no page-size flag, so 1000 rich
4283
4621
  # rows cost 1000 rows' worth of `statusCheckRollup` whatever the page.
@@ -4411,7 +4749,7 @@ case "$op" in
4411
4749
  # $jstatus != "ok" → Jenkins could not answer; every row `unknown`.
4412
4750
  # $jentry == null → the branch has no Jenkins job; `none`.
4413
4751
  # otherwise → the joined colour's `checks`, job named on fail.
4414
- _gh_raw="$(pr_list_call gh ${repo_args[@]+"${repo_args[@]}"} pr list --state "$state" ${limit_args[@]+"${limit_args[@]}"} ${search_args[@]+"${search_args[@]}"} \
4752
+ _gh_raw="$(pr_list_call gh ${repo_args[@]+"${repo_args[@]}"} pr list --state "$state" ${limit_args[@]+"${limit_args[@]}"} ${search_args[@]+"${search_args[@]}"} ${head_args[@]+"${head_args[@]}"} \
4415
4753
  --json number,title,state,headRefName,isDraft,mergeable,mergeStateStatus,reviewDecision,url,updatedAt,author,headRefOid,mergedAt)" || exit $?
4416
4754
  pr_list_report_truncation github "$limit" "$state" \
4417
4755
  "$(jq 'length' <<<"$_gh_raw" 2>/dev/null || echo 0)"
@@ -4456,7 +4794,7 @@ case "$op" in
4456
4794
  } + (if $jstatus == "ok" and $ambiguous and $eff == null then {checksLookup:"skipped"} else {} end)'
4457
4795
  else
4458
4796
  # GitHub without Jenkins (or Jenkins not configured): use GitHub rollup
4459
- _gh_raw="$(pr_list_call gh ${repo_args[@]+"${repo_args[@]}"} pr list --state "$state" ${limit_args[@]+"${limit_args[@]}"} ${search_args[@]+"${search_args[@]}"} \
4797
+ _gh_raw="$(pr_list_call gh ${repo_args[@]+"${repo_args[@]}"} pr list --state "$state" ${limit_args[@]+"${limit_args[@]}"} ${search_args[@]+"${search_args[@]}"} ${head_args[@]+"${head_args[@]}"} \
4460
4798
  --json number,title,state,headRefName,isDraft,statusCheckRollup,mergeable,mergeStateStatus,reviewDecision,url,updatedAt,author,headRefOid,mergedAt)" || exit $?
4461
4799
  pr_list_report_truncation github "$limit" "$state" \
4462
4800
  "$(jq 'length' <<<"$_gh_raw" 2>/dev/null || echo 0)"
@@ -4488,7 +4826,7 @@ case "$op" in
4488
4826
  # advances its watermark by. Without it a split full read would leave
4489
4827
  # the store unable to narrow and the daily full read would never fall
4490
4828
  # due against anything but a cold window.
4491
- _gh_raw="$(pr_list_call gh ${repo_args[@]+"${repo_args[@]}"} pr list --state "$state" ${limit_args[@]+"${limit_args[@]}"} ${search_args[@]+"${search_args[@]}"} \
4829
+ _gh_raw="$(pr_list_call gh ${repo_args[@]+"${repo_args[@]}"} pr list --state "$state" ${limit_args[@]+"${limit_args[@]}"} ${search_args[@]+"${search_args[@]}"} ${head_args[@]+"${head_args[@]}"} \
4492
4830
  --json number,title,state,headRefName,isDraft,url,updatedAt,author,headRefOid,mergedAt)" || exit $?
4493
4831
  pr_list_report_truncation github "$limit" "$state" \
4494
4832
  "$(jq 'length' <<<"$_gh_raw" 2>/dev/null || echo 0)"
@@ -4517,16 +4855,11 @@ case "$op" in
4517
4855
  # integration GitHub uses, which is why it is ABOVE the backend branch.
4518
4856
  # Bitbucket's `unknown` becomes a real value.
4519
4857
  #
4520
- # The listing has no --limit: it returns one page of 50 per state
4521
- # (`bb_state_listing`). `bb pr list` refuses the flag with `unknown flag`,
4522
- # and the page size is the endpoint's ceiling. Dropping it silently
4523
- # would serve a short page as if it were the whole set — the quiet wrong
4524
- # answer this adapter refuses elsewhere. So it is dropped AND said.
4525
- # A SWEEP IS NOT A PAGE AND OWES NO SUCH WARNING. `--limit` bounds a
4526
- # listing; a per-branch query returns that branch's pull requests and
4527
- # nothing was capped, so the notice would describe a truncation that did
4528
- # not happen. Said only for the listing it is about.
4529
- [ -n "$limit" ] && [ -z "$branches" ] && [ -z "$since" ] && echo "plot-host: bitbucket ignores --limit $limit; the listing returns one page of 50 per state" >&2
4858
+ # `bb pr list` REFUSES `--limit` OUTRIGHT ("unknown flag"), which is why
4859
+ # this goes through `bb api` rather than the CLI's own listing command.
4860
+ # The REST endpoint takes no such flag either; `--limit` is honoured by
4861
+ # `bb_state_listing` following `next` (see its header), not by anything
4862
+ # Bitbucket's API does on its own.
4530
4863
  # Establish that bb supports --json BEFORE calling it — Done-when 5.
4531
4864
  bb_require_json
4532
4865
  # Resolve the states BEFORE the loop. `for s in $(bb_states_for …)` runs
@@ -4596,19 +4929,37 @@ case "$op" in
4596
4929
  # `unknown`: its colour may belong to a commit this PR no longer
4597
4930
  # carries. A row `$named` lists but `$shamap` has no entry for is one
4598
4931
  # `jenkins_sha_runs` never reached because an earlier ask in the same
4599
- # pass broke early — "a lookup that cannot ask is not an answer",
4600
- # carried over unchanged from #2053/#2075, so its colour stands.
4932
+ # pass broke early. It reads `unknown` with `checksLookup: broken`
4933
+ # for the same reason: its colour may belong to an older commit.
4601
4934
  # `updatedAt` travels too: `rowsToBind` sorts by it to pick the most
4602
4935
  # recently updated rows, and a row list that never carries it sorts
4603
4936
  # as a no-op, leaving the cap keyed on array order instead.
4604
- _bb_jen_bind() { local s n named_file; plot_tmpfile named_file host-bbprlist-named; s="$(jenkins_bind_rows pr-list "$jen_map" "$(jq -c '[.[] | {headRefName:.source.branch.name,headRefOid:.source.commit.hash,updatedAt:.updated_on}]' <<<"$1")" "$named_file" "$_bound_shas")"; n="$(jq -R -c -s 'split("\n") | map(select(length > 0))' <"$named_file")"; PR_LIST_JQ_ARGS=(--argjson jmap "$jen_map" --arg jstatus "$jen_status" --argjson shamap "${s:-null}" --argjson named "${n:-[]}"); } # $1 = this state's raw Bitbucket rows
4937
+ # A MERGED or DECLINED row is settled; binding it spends a cap slot
4938
+ # on a row nobody acts on, the same waste `bb_fold_mergeable` was
4939
+ # fixed to skip for `mergeable` (wave 1, #2546). Filtered OUT before
4940
+ # `jenkins_bind_rows` ever sees the row, so it cannot be `$named`
4941
+ # either — a settled row reads its plain colour, never `skipped` or
4942
+ # `broken`.
4943
+ #
4944
+ # ONE CAP COVERS `--state all`. `pr_list_states` calls
4945
+ # `$PR_LIST_BIND_FN` once per state (open, merged, declined), and
4946
+ # each call starts at `SHA_LOOKUPS_PER_PASS`. Bitbucket's `state=`
4947
+ # filter returns only rows of that state, so only the open call holds
4948
+ # OPEN rows and only it can name any: the pass spends at most 5.
4949
+ _bb_jen_bind() { local s n named_file; plot_tmpfile named_file host-bbprlist-named; s="$(jenkins_bind_rows pr-list "$jen_map" "$(jq -c '[.[] | select(.state == "OPEN") | {headRefName:.source.branch.name,headRefOid:.source.commit.hash,updatedAt:.updated_on}]' <<<"$1")" "$named_file" "$_bound_shas")"; n="$(jq -R -c -s 'split("\n") | map(select(length > 0))' <"$named_file")"; PR_LIST_JQ_ARGS=(--argjson jmap "$jen_map" --arg jstatus "$jen_status" --argjson shamap "${s:-null}" --argjson named "${n:-[]}"); } # $1 = this state's raw Bitbucket rows
4605
4950
  PR_LIST_BIND_FN=_bb_jen_bind
4606
4951
  pr_list_states bitbucket "$limit" "$bb_states" '.[] |
4607
- ($jmap[.source.branch.name]) as $colour | (($colour.checks == "green" or $colour.checks == "failing")) as $ambiguous | (.source.branch.name) as $head | ((.source.commit.hash // "") != "") as $hasSha | (($named | index($head)) != null) as $wasNamed | ($shamap[.source.branch.name] // (if ($ambiguous and $hasSha and ($wasNamed | not)) then null else $colour end) // null) as $jentry |
4952
+ (.state == "OPEN") as $open | ($jmap[.source.branch.name]) as $colour | (($colour.checks == "green" or $colour.checks == "failing")) as $ambiguous | (.source.branch.name) as $head | ((.source.commit.hash // "") != "") as $hasSha | (($named | index($head)) != null) as $wasNamed | ($open and $ambiguous and $hasSha and ($wasNamed | not)) as $capped | ($open and $ambiguous and $wasNamed and ($shamap[.source.branch.name] == null)) as $broken | ($shamap[.source.branch.name] // (if ($capped or $broken) then null else $colour end) // null) as $jentry |
4608
4953
  # A ROW `$jentry == null` WITH `$ambiguous` NEVER GOT A JENKINS
4609
- # ANSWER THIS PASS — past the cap, or a lookup that broke early.
4610
- # Distinct from Jenkins naming "unknown" itself — own field
4611
- # rather than the same `checks` word (`bitbucket-jenkins-a-pr-list-row`).
4954
+ # ANSWER THIS PASS — `$capped` (past the cap, never named this
4955
+ # pass) or `$broken` (named, but `jenkins_sha_runs` broke early
4956
+ # before reaching it). Distinct from Jenkins naming "unknown"
4957
+ # itself — own field rather than the same `checks` word
4958
+ # (`bitbucket-jenkins-a-pr-list-row`). A `$broken` row must not
4959
+ # stand on `$colour`: that colour may belong to a commit this
4960
+ # PR no longer carries, the same reason `$capped` already
4961
+ # refuses it — only the reason differs between `$capped` and
4962
+ # `$broken`.
4612
4963
  {
4613
4964
  number:.id, title:.title,
4614
4965
  state:(if .state=="DECLINED" then "CLOSED" else .state end),
@@ -4625,13 +4976,13 @@ case "$op" in
4625
4976
  updatedAt:(.updated_on // ""),headSha:(.source.commit.hash // ""),mergedAt:(if .state=="MERGED" then (.updated_on // "") else "" end),checksSha:($jentry.checksSha // ""),
4626
4977
  author:(.author.nickname // ""),
4627
4978
  failing_checks:(if $jentry != null and $jentry.checks == "failing" then [$jentry.job] else [] end), base:(.destination.branch.name // "")
4628
- } + (if $jstatus == "ok" and $ambiguous and $jentry == null then {checksLookup:"skipped"} else {} end)' "${bb_cmd[@]}" | bb_fold_mergeable_stream || exit $?
4979
+ } + (if $jstatus == "ok" and $jentry == null then (if $broken then {checksLookup:"broken"} elif $capped then {checksLookup:"skipped"} else {} end) else {} end)' "${bb_cmd[@]}" | bb_fold_mergeable_stream "$repo_slug" || exit $?
4629
4980
  PR_LIST_BIND_FN=""
4630
4981
  else
4631
4982
  # Bitbucket without Jenkins: checks remain unknown
4632
4983
  pr_list_states bitbucket "$limit" "$bb_states" \
4633
4984
  '.[] | {number:.id,title:.title,state:(if .state=="DECLINED" then "CLOSED" else .state end),head:.source.branch.name,draft:(.draft // false),checks:"unknown",mergeable:"unknown",review:"",url:(.links.html.href // ""),updatedAt:(.updated_on // ""),headSha:(.source.commit.hash // ""),mergedAt:(if .state=="MERGED" then (.updated_on // "") else "" end),author:(.author.nickname // ""),failing_checks:[],base:(.destination.branch.name // "")}' \
4634
- "${bb_cmd[@]}" | bb_fold_mergeable_stream || exit $?
4985
+ "${bb_cmd[@]}" | bb_fold_mergeable_stream "$repo_slug" || exit $?
4635
4986
  fi
4636
4987
  else
4637
4988
  pr_list_states bitbucket "$limit" "$bb_states" \
@@ -4667,8 +5018,7 @@ case "$op" in
4667
5018
  # for a repository whose CI is not GitHub Actions. `CI` and `Git host` are
4668
5019
  # independent `## Plot Config` keys, and this is the op that reads the
4669
5020
  # first of them.
4670
- branch="${1:?runs needs a branch}"; shift
4671
- limit=10
5021
+ branch="${1:?runs needs a branch}"; shift; limit=10
4672
5022
  while [ $# -gt 0 ]; do
4673
5023
  case "$1" in
4674
5024
  --limit) limit="${2:?}"; shift 2 ;;
@@ -4844,7 +5194,10 @@ case "$op" in
4844
5194
  # ONE MORE CALL, ONLY FOR A CONCLUDED FAILURE (#1295): `gh run view --json
4845
5195
  # jobs` is the only place a 0-step job (no runner ever picked up the run)
4846
5196
  # shows up, apart from a real failure. A run still going or that
4847
- # succeeded costs no extra call.
5197
+ # succeeded costs no extra call. A second consumer reads the same `jobs`
5198
+ # field since 2026-10-20: `checks-verdict.ts`'s `runWasNotAcquired` and its
5199
+ # cancellation-fingerprint logic tell a genuine timeout from a near-instant
5200
+ # supersession by reading these same per-job step conclusions.
4848
5201
  _gh_db_id=$(printf '%s' "$_gh_match" | jq -r 'if (.conclusion == "failure" or .conclusion == "cancelled") then .databaseId else "" end')
4849
5202
  _gh_match=$(printf '%s' "$_gh_match" | jq -c 'del(.databaseId)') || exit 4
4850
5203
  [ -z "$_gh_db_id" ] && { printf '%s' "$_gh_match"; exit 0; }
@@ -4866,11 +5219,11 @@ case "$op" in
4866
5219
  # of them reproduces `an-outage-is-not-an-answer` — a board that says "no
4867
5220
  # issues" because it could not reach the tracker is stating a fact it does
4868
5221
  # not have.
4869
- limit=""; state="open"; since=""; page_token=""; paged=""; label=""; fix_version=""; title_has=""
5222
+ limit=""; state="open"; since=""; page_token=""; paged=""; label=""; fix_version=""; title_has=""; state_explicit=""
4870
5223
  while [ $# -gt 0 ]; do
4871
5224
  case "$1" in
4872
5225
  --limit) limit="${2:?}"; shift 2 ;;
4873
- --state) state="${2:?}"; shift 2 ;;
5226
+ --state) state="${2:?}"; state_explicit="$state"; shift 2 ;;
4874
5227
  --since) since="${2:?}"; shift 2 ;;
4875
5228
  --page-token) page_token="${2:?}"; shift 2 ;;
4876
5229
  --paged) paged=1; shift ;;
@@ -4880,6 +5233,18 @@ case "$op" in
4880
5233
  *) die "issue-list: unknown arg $1" ;;
4881
5234
  esac
4882
5235
  done
5236
+ # THIS ARM'S OWN USAGE CONTRACT EXITS 2, never `die`'s plain 1: both the
5237
+ # `--fix-version`/`--state` conflict below and the above-one-page `--limit`
5238
+ # guard further down are usage errors `issue-list` catches on itself rather
5239
+ # than a generic argument mistake, so a caller can tell the two apart.
5240
+ usage_refused() { echo "plot-host: issue-list: $*" >&2; exit 2; }
5241
+ # `--fix-version` AND AN EXPLICIT `--state` ARE NOT INDEPENDENTLY MEANINGFUL
5242
+ # (`--state version` alone has nowhere to get a name from), so one of two
5243
+ # flags silently winning would hide the other. Refused regardless of
5244
+ # argument order: the loop above always leaves `state=version` once
5245
+ # `--fix-version` is seen, so order itself cannot distinguish the two
5246
+ # un-refused outcomes a naive fix could produce.
5247
+ [ -z "$fix_version" ] || [ -z "$state_explicit" ] || [ "$state_explicit" = version ] || usage_refused "--fix-version and --state $state_explicit conflict; drop one"
4883
5248
  # `--since` is spliced into a JQL string and a search qualifier, so its shape
4884
5249
  # is checked here: a value outside it is a usage error, never a query.
4885
5250
  [[ "$state" =~ ^(open|closed|inbox|changed|version)$ ]] || die "issue-list: --state is open, closed, inbox, changed or version, not '$state'"
@@ -4934,7 +5299,25 @@ case "$op" in
4934
5299
  # THE CLOSED, CHANGED AND VERSION READS REQUIRE `Ticket prefixes`: an
4935
5300
  # unscoped `resolved >=`, `updated >=` or `fixVersion =` query reads every
4936
5301
  # project on the instance, the hazard `tracker_projects` measured.
4937
- [ -n "$scope" ] || ! [[ "$state" =~ ^(closed|changed|version)$ ]] || { echo "plot-host: $state Jira issues need 'Ticket prefixes' declared; an unscoped $state query reads the whole instance" >&2; exit 4; }; if [ "$state" = version ]; then found=""; for p in $projects; do vbody="$(jira_ask "/rest/api/2/project/$p/versions")" || exit $?; [ "$(jq --arg n "$fix_version" 'any(.[]; .name == $n)' <<<"$vbody")" = true ] && found=1; done; [ -n "$found" ] || { echo "plot-host: version-not-found: $fix_version" >&2; exit 4; }; fi
5302
+ [ -n "$scope" ] || ! [[ "$state" =~ ^(closed|changed|version)$ ]] || { echo "plot-host: $state Jira issues need 'Ticket prefixes' declared; an unscoped $state query reads the whole instance" >&2; exit 4; }
5303
+ # THE EXISTENCE CHECK RUNS ONCE PER QUESTION, NOT ONCE PER PAGE: `walk`
5304
+ # (tracker-shell.ts) calls this script once per page of a multi-page
5305
+ # `--fix-version` read, each call carrying `--page-token` from the second
5306
+ # page on. Re-running the check on every one of those re-asks Jira
5307
+ # `version-list` per `Ticket prefixes` project for a question already
5308
+ # answered on page one — 6 extra calls for a 3-page/2-project read,
5309
+ # measured 2026-10-21 (issue #2259). Gating on an absent `$page_token`
5310
+ # keeps `versionRead`'s `pages: issues.value.pages + projects.length`
5311
+ # (tracker-jira.ts) correct: one existence call per project, however many
5312
+ # pages the read takes. A malformed version-list body exits 3 like
5313
+ # `version-list`'s own parse failure does — "cannot parse" and "parsed,
5314
+ # found nothing" are different outcomes, and only the second is
5315
+ # version-not-found. `jq -e` ON A BOOLEAN RESULT IS THE THREE-WAY SWITCH:
5316
+ # exit 0 is a match (`found=1`), exit 1 is a clean no-match (the loop
5317
+ # moves on), and anything else is a parse failure jq itself could not
5318
+ # complete — `[ $? = 1 ]` is the one case that is NOT that failure, so
5319
+ # the `||` chain only reaches `exit 3` when the code is neither.
5320
+ if [ "$state" = version ] && [ -z "$page_token" ]; then found=""; for p in $projects; do vbody="$(jira_ask "/rest/api/2/project/$p/versions")" || exit $?; jq -e --arg n "$fix_version" 'any(.[]; .name == $n)' >/dev/null <<<"$vbody" && found=1 || [ $? = 1 ] || exit 3; done; [ -n "$found" ] || { echo "plot-host: version-not-found: $fix_version" >&2; exit 4; }; fi
4938
5321
  # A VERSION READ EXISTS BEFORE IT IS SEARCHED: `fixVersion = "<name>"` alone
4939
5322
  # matches nothing for a name Jira has never heard of and still exits 0 with
4940
5323
  # no rows (measured 2026-10-21) — the exact silent empty answer this guard
@@ -4999,7 +5382,17 @@ case "$op" in
4999
5382
  # refuses. `-gt`, not `-ge`: a full single page (100) is still one page
5000
5383
  # and must still answer. A non-numeric `--limit` skips this guard and
5001
5384
  # reaches Jira as an invalid `maxResults` instead — not this guard's job.
5002
- if [ -n "$paged" ]; then max="${limit:-$ISSUE_PAGE_ROWS}"; [ "$max" -le "$ISSUE_PAGE_ROWS" ] || max="$ISSUE_PAGE_ROWS"; else [[ "$max" =~ ^[0-9]+$ ]] && [ "$max" -gt "$ISSUE_PAGE_ROWS" ] && { echo "plot-host: issue-list: --limit $limit exceeds one Jira page ($ISSUE_PAGE_ROWS); pass --paged to read it a page at a time" >&2; exit 2; }; fi
5385
+ # BOUNDED BEFORE `-gt` EVER RUNS: `[0-9]+` matches a value like
5386
+ # `99999999999999999999` too, and bash's `-gt` only holds signed 64-bit
5387
+ # integers — past that it prints "integer expected" to stderr and the
5388
+ # whole `&&` chain reads as false, so the oversized value reached Jira's
5389
+ # `maxResults` unbounded (measured by hand). A run of 16+ digits is
5390
+ # outside that range regardless of value, so it refuses on digit count
5391
+ # alone, never reaching a comparison `-gt` cannot make; 1-15 digits is
5392
+ # always representable and falls through to the ordinary `-gt` check.
5393
+ if [ -n "$paged" ]; then max="${limit:-$ISSUE_PAGE_ROWS}"; [ "$max" -le "$ISSUE_PAGE_ROWS" ] || max="$ISSUE_PAGE_ROWS"
5394
+ elif [[ "$max" =~ ^[0-9]{16,}$ ]] || { [[ "$max" =~ ^[0-9]+$ ]] && [ "$max" -gt "$ISSUE_PAGE_ROWS" ]; }; then usage_refused "--limit $limit exceeds one Jira page ($ISSUE_PAGE_ROWS); pass --paged to read it a page at a time"
5395
+ fi
5003
5396
  token_args=(); [ -z "$page_token" ] || token_args=(--data-urlencode "nextPageToken=$page_token")
5004
5397
  # jq builds the query string so a JQL with spaces/quotes is encoded once,
5005
5398
  # not hand-escaped. --data-urlencode via curl -G keeps the token out of the
@@ -5084,15 +5477,16 @@ case "$op" in
5084
5477
  if out="$(gh issue list --state "$ask_state" ${limit_args[@]+"${limit_args[@]}"} \
5085
5478
  ${search_args[@]+"${search_args[@]}"} --json "$gh_json" 2>"$HOST_ERR")"; then
5086
5479
  rm -f "$HOST_ERR"
5480
+ # `gh` pages inside ONE process and the wrapper records one call per
5481
+ # process, so each page past the first is recorded here. Run before the jq
5482
+ # print below so that print's exit status is the branch's, not this call's.
5483
+ budget_record_call github github graphql "$(node "$here/board/plot-listing-pages.mjs" <<<"$out" 2>/dev/null)"
5087
5484
  jq -c --arg status "$gh_state" \
5088
5485
  '.[] | ((.state // $status) | ascii_downcase) as $actual |
5089
5486
  {number:.number,title:.title,url:(.url // ""),createdAt:(.createdAt // ""),
5090
5487
  status:$actual,statusCategory:(if $actual == "open" then "To Do" else "Done" end),assignees:[.assignees[]?.login]}
5091
5488
  + (if .updatedAt then {updatedAt:.updatedAt} else {} end) + (if .issueType.name? then {type:.issueType.name} else {} end)
5092
5489
  + (if $actual == "closed" then {closedAt:(.closedAt // "")} else {} end)' <<<"$out"
5093
- # `gh` pages by 100 inside ONE process and the wrapper records one call
5094
- # per process, so each page past the first is recorded here.
5095
- jq -r "[range(1; length / $ISSUE_PAGE_ROWS | ceil)] | .[]" <<<"$out" | while read -r _; do budget_record_call github github graphql; done
5096
5490
  else
5097
5491
  # NO empty-list fallback. `host_miss_or_fail` exists for a lookup whose
5098
5492
  # subject is absent — one PR that does not exist. A LIST has no absent
@@ -5130,8 +5524,7 @@ case "$op" in
5130
5524
  count=0
5131
5525
  while IFS= read -r line; do
5132
5526
  [[ "$line" =~ ^#0*([0-9]+)[[:space:]]+(.*)$ ]] || continue
5133
- num="${BASH_REMATCH[1]}"
5134
- rest="${BASH_REMATCH[2]}"
5527
+ num="${BASH_REMATCH[1]}"; rest="${BASH_REMATCH[2]}"
5135
5528
  # Lift the leading state badge word (NEW/OPEN/RESOLVED/…), then strip
5136
5529
  # it and its padding; the title starts after it. The badge was parsed
5137
5530
  # here before and THROWN AWAY to recover the title — it is captured
@@ -5140,8 +5533,7 @@ case "$op" in
5140
5533
  # that drifts from the one that strips.
5141
5534
  state=""
5142
5535
  if [[ "$rest" =~ ^(NEW|OPEN|ON\ HOLD|INVALID|RESOLVED|DUPLICATE|WONTFIX|CLOSED)[[:space:]]+(.*)$ ]]; then
5143
- state="${BASH_REMATCH[1]}"
5144
- rest="${BASH_REMATCH[2]}"
5536
+ state="${BASH_REMATCH[1]}"; rest="${BASH_REMATCH[2]}"
5145
5537
  fi
5146
5538
  # Map the badge onto the three-value category the board groups on.
5147
5539
  # NEW/OPEN are unstarted; RESOLVED/CLOSED are finished. The rest —
@@ -5195,16 +5587,15 @@ case "$op" in
5195
5587
  # the board. jira_check turns that 404 into exit 3 with empty stdout.
5196
5588
  jira_require_config
5197
5589
  body_json="$(jira_ask "/rest/api/2/issue/$num" \
5198
- -G --data-urlencode "fields=summary,description,status")" || exit $?
5199
- # `state` FOLLOWS issue-list's OWN WORD: `statusCategory.name == "Done"`
5200
- # is closed, same mapping as the list's open/closed reader — a second
5201
- # vocabulary here would drift from the one issue-list already keeps.
5590
+ -G --data-urlencode "fields=summary,description,status,resolution")" || exit $?
5591
+ # `state`: closed when `statusCategory.key` is `done` (`name` is localised)
5592
+ # or a resolution is set; absent is open.
5202
5593
  printf '%s' "$body_json" | jq -c --arg base "$(tracker_base_url)" '{
5203
5594
  number: .key,
5204
5595
  title: (.fields.summary // ""),
5205
5596
  body: (.fields.description // ""),
5206
5597
  url: ($base + "/browse/" + .key),
5207
- state: (if .fields.status.statusCategory.name == "Done" then "closed" else "open" end)
5598
+ state: (if .fields.status.statusCategory.key == "done" or .fields.resolution != null then "closed" else "open" end)
5208
5599
  }'
5209
5600
  elif [ "$be" = "github" ]; then
5210
5601
  if out="$(gh issue view "$num" --json number,title,body,url,state 2>"$HOST_ERR")"; then
@@ -5246,11 +5637,10 @@ case "$op" in
5246
5637
  url="$(grep -oE 'https?://[^[:space:]]+' <<<"$(grep -F 'View this issue on Bitbucket' <<<"$raw")" | head -1)"
5247
5638
  # Line 2 is `<STATE> • <reporter> opened <createdOn>` — the same badge
5248
5639
  # word `issue-list` strips from its own row, read here instead of
5249
- # discarded. RESOLVED/CLOSED close it; everything else (including states
5250
- # this vocabulary has no word for) stays open, the same default
5251
- # issue-list's mapping leaves for an unmapped badge.
5252
- bb_state="$(sed -n '2p' <<<"$raw" | sed -E 's/^([A-Z ]+)[[:space:]]*•.*$/\1/; s/[[:space:]]+$//')"
5253
- case "$bb_state" in RESOLVED|CLOSED) state=closed ;; *) state=open ;; esac
5640
+ # discarded. The five finished words close it; ON HOLD, NEW, OPEN and any
5641
+ # state this vocabulary has no word for stay open, as issue-list leaves them.
5642
+ bb_state="$(sed -n '2p' <<<"$raw" | sed -E 's/^[[:space:]]*([A-Z ]+)[[:space:]]*•.*$/\1/; s/[[:space:]]+$//')"
5643
+ case "$bb_state" in RESOLVED|CLOSED|INVALID|DUPLICATE|WONTFIX) state=closed ;; *) state=open ;; esac
5254
5644
  # Body is the block between the metadata head and the footer. The head is
5255
5645
  # the title + the two fixed meta lines (state, Type:) plus an optional
5256
5646
  # Component/Milestone/Version line; the tail is the footer. This is the
@@ -5295,8 +5685,10 @@ case "$op" in
5295
5685
  #
5296
5686
  # IDEMPOTENT BY NATURE. The same status written twice is the same status,
5297
5687
  # and Jira answers a transition to the state an issue already holds by
5298
- # naming no such transition — which this reports as `no-target` rather than
5299
- # as a failure.
5688
+ # naming no such transition. A no-match also covers the other case — the
5689
+ # status exists but the workflow has no transition to it from here — so the
5690
+ # no-match line carries the facts that tell the two apart, and the
5691
+ # connector (`tracker-jira.ts`) tells them apart.
5300
5692
  key="${1:?issue-status needs an issue key}"; want="${2:?issue-status needs a status}"
5301
5693
  [ "$(tracker_scheme)" = "jira" ] || exit 4
5302
5694
  jira_require_config
@@ -5304,17 +5696,21 @@ case "$op" in
5304
5696
  # workflow and per issue: the id for "In Progress" differs between projects
5305
5697
  # and the transition may not be available from the issue's current state at
5306
5698
  # all. A hardcoded id writes a status to the wrong column silently.
5307
- body_json="$(jira_ask "/rest/api/2/issue/$key/transitions")" || exit $?
5699
+ # ONE READ, TWO FACTS. The issue read with `expand=transitions` answers the
5700
+ # same transitions as `/transitions` and the current status beside them, so
5701
+ # a no-match costs no second call.
5702
+ body_json="$(jira_ask "/rest/api/2/issue/$key?fields=status&expand=transitions")" || exit $?
5308
5703
  tid="$(printf '%s' "$body_json" | jq -r --arg want "$want" \
5309
5704
  '[.transitions[]? | select((.name // "" | ascii_downcase) == ($want | ascii_downcase)
5310
5705
  or ((.to.name // "" | ascii_downcase) == ($want | ascii_downcase)))]
5311
5706
  | .[0].id // ""')"
5312
5707
  if [ -z "$tid" ]; then
5313
- # NO SUCH TRANSITION IS AN ANSWER, not a failure. The tracker was reached
5314
- # and holds nowhere to put this status — either the workflow has no such
5315
- # state or the issue is already in it. Reporting it as a failure would
5316
- # make a repeated write look like an outage.
5317
- printf '%s\n' 'no-target'
5708
+ # NO MATCH IS NOT YET AN ANSWER. It covers two different facts — the
5709
+ # issue already holds the status (harmless), or the status exists but no
5710
+ # transition from here reaches it (the tracker is behind). The current
5711
+ # status and the offered transitions are printed as read; an absent
5712
+ # status prints as an empty field, which the connector reads as a failure.
5713
+ printf '%s' "$body_json" | jq -r '"no-match\t\(.fields.status.name // "")\t\([.transitions[]?.name] | join(", "))"'
5318
5714
  exit 0
5319
5715
  fi
5320
5716
  jira_ask "/rest/api/2/issue/$key/transitions" \
@@ -5345,7 +5741,7 @@ case "$op" in
5345
5741
  issue-label|issue-comment|issue-close)
5346
5742
  # THE PLAN-STATE WRITES, and one-way: Plot sets a `plan:*` label, keeps one
5347
5743
  # comment per issue and closes the issue at release; nothing reads any back.
5348
- # issue-label <n> <add> [<remove,...>] adds one label, removes the rest
5744
+ # issue-label <n> <add> [<remove,...>] adds one label, creating it first where the repo lacks it, and removes only the listed ones the issue carries, in one `gh issue edit`
5349
5745
  # issue-comment <n> <marker> <body> edits the comment holding <marker>, else posts; an empty <marker> always posts
5350
5746
  # issue-close <n>
5351
5747
  # GitHub issues only, dispatched on `issue_source` like issue-open. Exit 4,
@@ -5353,12 +5749,12 @@ case "$op" in
5353
5749
  num="${1:?$op needs an issue number}"; source_said="$(issue_source)" || exit 1
5354
5750
  [ "$be" = github ] && { [ "$source_said" = git-host ] || [ "$source_said" = $'tracker\tgithub-issues' ]; } || { echo "plot-host: $op: ${source_said#*$'\t'}" >&2; exit 4; }
5355
5751
  case "$op" in
5356
- issue-label) gh issue edit "$num" --add-label "${2:?issue-label needs a label}" ${3:+--remove-label "$3"} >/dev/null 2>"$HOST_ERR" || gh_fail ;;
5752
+ issue-label) add="${2:?issue-label needs a label}"; carried="$(gh issue view "$num" --json labels -q '.labels[].name' 2>"$HOST_ERR")" || gh_fail; keep="$(comm -12 <(printf '%s\n' "${3-}" | tr , '\n' | sort) <(printf '%s\n' "$carried" | sort) | paste -sd, -)"; gh label create "$add" --color ededed --description "Plot plan phase: ${add#plan:}" >/dev/null 2>"$HOST_ERR" || grep -qi 'already exists' "$HOST_ERR" || gh_fail; gh issue edit "$num" --add-label "$add" ${keep:+--remove-label "$keep"} >/dev/null 2>"$HOST_ERR" || gh_fail ;;
5357
5753
  issue-close) gh issue close "$num" >/dev/null 2>"$HOST_ERR" || gh_fail ;;
5358
5754
  issue-comment)
5359
- cid=""; [ -z "${2-}" ] || cid="$(gh api --paginate "repos/{owner}/{repo}/issues/$num/comments" 2>"$HOST_ERR" | jq -rs --arg m "$2" '[.[][] | select(.body | contains($m))][0].id // empty')" || gh_fail
5360
- if [ -n "$cid" ]; then gh api -X PATCH "repos/{owner}/{repo}/issues/comments/$cid" -f body="${3-}" >/dev/null 2>"$HOST_ERR" || gh_fail
5361
- else gh issue comment "$num" --body "${3-}" >/dev/null 2>"$HOST_ERR" || gh_fail; fi ;;
5755
+ cid=""; [ -z "${2-}" ] || cid="$(gh_marker_comment_id "$num" "$2")" || gh_fail
5756
+ if [ -n "$cid" ]; then gh api -X PATCH "repos/{owner}/{repo}/issues/comments/$cid" -f body="${3-}" >/dev/null 2>"$HOST_ERR"
5757
+ else gh issue comment "$num" --body "${3-}" >/dev/null 2>"$HOST_ERR"; fi || gh_fail ;;
5362
5758
  esac
5363
5759
  rm -f "$HOST_ERR" ;;
5364
5760
 
@@ -5373,8 +5769,7 @@ case "$op" in
5373
5769
  printf '%s' "$body" | jq -c '.[] | {name, released: (.released // false), releaseDate: (.releaseDate // null)}' || exit 3 ;;
5374
5770
 
5375
5771
  pr-body)
5376
- num="${1:?pr-body needs a PR number}"; shift
5377
- body=""
5772
+ num="${1:?pr-body needs a PR number}"; shift; body=""
5378
5773
  while [ $# -gt 0 ]; do
5379
5774
  case "$1" in
5380
5775
  --body) body="${2:?}"; shift 2 ;;
@@ -5424,7 +5819,7 @@ case "$op" in
5424
5819
  }
5425
5820
  }' <<<"$out"
5426
5821
  else
5427
- err="$(cat "$HOST_ERR" 2>/dev/null)"; rm -f "$HOST_ERR"
5822
+ host_err
5428
5823
  # The host could not be asked. Report unknown rather than failing outright,
5429
5824
  # because this is informational — a caller that cannot read the budget
5430
5825
  # should proceed with the default path, not error out.
@@ -5664,8 +6059,8 @@ case "$op" in
5664
6059
  # the signed-in CLI identity, so it needs no App credentials and no Node
5665
6060
  # helper.
5666
6061
  [ "$be" = "github" ] || { echo "plot-host: pr-comment: bitbucket has no verified pr-comment write" >&2; exit 4; }; num="${1:?pr-comment needs a PR number}"; cid=""
5667
- [ -z "${3-}" ] || cid="$(gh api --paginate "repos/{owner}/{repo}/issues/$num/comments" 2>"$HOST_ERR" | jq -rs --arg m "$3" '[.[][] | select(.body | contains($m))][0].id // empty')" || gh_fail
5668
- if [ -n "$cid" ]; then gh api -X PATCH "repos/{owner}/{repo}/issues/comments/$cid" -f body="${2:?pr-comment needs a body}" >/dev/null 2>"$HOST_ERR" || gh_fail; else gh pr comment "$num" --body "${2:?pr-comment needs a body}" >/dev/null 2>"$HOST_ERR" || gh_fail; fi; rm -f "$HOST_ERR" ;;
6062
+ [ -z "${3-}" ] || cid="$(gh_marker_comment_id "$num" "$3")" || gh_fail
6063
+ if [ -n "$cid" ]; then gh api -X PATCH "repos/{owner}/{repo}/issues/comments/$cid" -f body="${2:?pr-comment needs a body}" >/dev/null 2>"$HOST_ERR"; else gh pr comment "$num" --body "${2:?pr-comment needs a body}" >/dev/null 2>"$HOST_ERR"; fi || gh_fail; rm -f "$HOST_ERR" ;;
5669
6064
 
5670
6065
  *)
5671
6066
  die "unknown op '$op' (backend|default-branch|pr-state|pr-create|pr-merge|pr-list|issue-list|issue-view|issue-status|issue-open|issue-label|issue-comment|issue-close|version-list|pr-body|pr-review|rate-limit|limit|ci-limit|spend-rate|commit-status|pr-comment)"