@plot-pm/board 0.22.1 → 0.23.0

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,45 @@ 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; }; }
654
+ miss_or_exit3() { [ -z "$1" ] || is_lookup_miss "$1" || die3 "$1"; }
616
655
  # `pr-merged`'s own third value for a failed call: a lookup miss still means
617
656
  # not-merged, anything else prints the host's words and answers `unknown`
618
657
  # rather than exiting — the caller already branches on this word, not a code.
619
658
  miss_or_unknown() { if [ -z "$1" ] || is_lookup_miss "$1"; then echo "not-merged"; else echo "plot-host: $1" >&2; echo "unknown"; fi; }
620
659
  gh_fail() { echo "plot-host: $(cat "$HOST_ERR" 2>/dev/null)" >&2; rm -f "$HOST_ERR"; exit 3; }
660
+ # Reads the last host call's stderr into `err` and removes the file, so the
661
+ # next call starts empty. Every failed-call branch below starts with it.
662
+ host_err() { err="$(cat "$HOST_ERR" 2>/dev/null)"; rm -f "$HOST_ERR"; }
663
+
664
+ # THE ONE MARKER LOOKUP, shared by `pr-comment` and `issue-comment` — GitHub's
665
+ # REST comments endpoint is `issues/$num/comments` for both, since a PR is an
666
+ # issue under the hood. Prints the id of the comment holding `$2` (a
667
+ # substring), scoped to the comment's `.user.login` (the REST field; `gh pr
668
+ # list --json` answers `.author.login` instead, but this is the REST path) —
669
+ # so a PR participant who pastes the same marker into their own comment is
670
+ # never mistaken for this script's own prior post. Prints empty on no match.
671
+ #
672
+ # SCOPED TO THE LOGIN `gh api user` ANSWERS for the token this call writes
673
+ # with (`host.ts:358`), asked once per lookup. Not `budget_account`: it reads
674
+ # `hosts.yml` or `PLOT_BUDGET_ACCOUNT`, and neither names the author when
675
+ # `GH_TOKEN` is set or the account is a grouping name, so every lookup missed
676
+ # and posted a new comment.
677
+ #
678
+ # NO LOGIN, NO SCOPE. When `gh api user` fails or answers no valid login (an
679
+ # App installation token gets 403 there), the match falls back to the marker
680
+ # alone, as it was before #2661. A comment with no `user` field cannot be
681
+ # attributed and also matches on the marker alone.
682
+ #
683
+ # A FAILED LISTING EXITS 3 THROUGH `gh_fail`, same as a failed edit. `set -o
684
+ # pipefail` (above) makes the pipeline's exit code `gh api`'s own, so a lookup
685
+ # that cannot be read never falls through to "no marker found, post new".
686
+ 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
687
 
622
688
  # Exit 3 — reserved for "the op itself cannot proceed", distinct from `die`'s
623
689
  # generic 1. A Jenkins overlay with no instance to ask is such a case: a config
@@ -841,7 +907,7 @@ pr_list_failed() { # $1=stderr text
841
907
  pr_list_call() { # "$@"=the host command → payload on stdout, or dies
842
908
  local out rc err tmp=""
843
909
  plot_tmpfile tmp host-prlist-err \
844
- || { echo "plot-host: no temp file could be made under ${TMPDIR:-/tmp}" >&2; exit 3; }
910
+ || die3 "no temp file could be made under ${TMPDIR:-/tmp}"
845
911
  out="$("$@" 2>"$tmp")"; rc=$?
846
912
  err="$(cat "$tmp" 2>/dev/null)"; rm -f "$tmp"
847
913
  [ "$rc" -eq 0 ] || pr_list_failed "$err"
@@ -976,10 +1042,7 @@ PR_LIST_BIND_FN=""
976
1042
  # which are lower-case. One mapping, so a caller never spells a state twice.
977
1043
  bb_query_state() { # $1=adapter state word → Bitbucket's
978
1044
  case "$1" in
979
- open) printf 'OPEN' ;;
980
- merged) printf 'MERGED' ;;
981
- declined) printf 'DECLINED' ;;
982
- superseded) printf 'SUPERSEDED' ;;
1045
+ open|merged|declined|superseded) printf '%s' "$1" | tr '[:lower:]' '[:upper:]' ;;
983
1046
  *) die "bb_query_state: unknown state '$1'" ;;
984
1047
  esac
985
1048
  }
@@ -1008,11 +1071,12 @@ url_encode() { # $1=raw → percent-encoded on stdout
1008
1071
  printf '%s' "$_out"
1009
1072
  }
1010
1073
 
1011
- # Ask Bitbucket about ONE branch in ONE state, and print the `values` array.
1074
+ # Ask Bitbucket about ONE branch in ONE state, and print the combined `values`
1075
+ # array across every page the host offers.
1012
1076
  #
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
1077
+ # WHAT IT PRINTS is the endpoint's `values` — a JSON array of pull request
1078
+ # objects, in the SAME shape `bb pr list --json` emits, which is what lets the
1079
+ # existing jq programs consume it unchanged. The `--rich` field set
1016
1080
  # (`plot-host.sh:3247`) reads `.id`, `.title`, `.state`, `.source.branch.name`,
1017
1081
  # `.draft` and `.links.html.href`; the REST object carries all six.
1018
1082
  #
@@ -1024,12 +1088,24 @@ url_encode() { # $1=raw → percent-encoded on stdout
1024
1088
  # happening from the other side: a host exiting 0 while printing nothing once
1025
1089
  # read as "this repo has no PRs".
1026
1090
  #
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.
1091
+ # THE QUERY FILTERS ON STATE, SO A FULL PAGE IS NEVER A SHORT NON-MATCH. Every
1092
+ # row this walk reads already matches `$_st` — Bitbucket filters server-side —
1093
+ # so a branch carrying more than 50 pull requests in one state (#2484) used to
1094
+ # truncate silently at the first page. This now follows `next` until the host
1095
+ # stops offering one, or until `BB_BRANCH_QUERY_PAGE_CAP` pages have been read,
1096
+ # whichever comes first — see that constant for why no narrower cap exists to
1097
+ # reuse.
1098
+ #
1099
+ # A STOPPED WALK REPORTS ITSELF, ON STDERR, IN `pr_list_report_truncation`'s
1100
+ # OWN WORDING ("possibly truncated") — `plot-host.sh:3093` is the precedent
1101
+ # this follows rather than inventing a second phrase for the same fact — and
1102
+ # RETURNS EXIT 3, the code `pr-merged`, `pr-merge-commit`/`pr-merge-dest` and
1103
+ # `pr-merged-heads` already read as "the question failed, not merely empty".
1104
+ # A caller reading the exit code sees one vocabulary for "the answer may be
1105
+ # short" whether the cause is a refused call or a walk the cap stopped.
1106
+ #
1107
+ # `pagelen=50` rather than 1 — the endpoint's ceiling, and the same per-page
1108
+ # cost whether this reads one page or several.
1033
1109
  # THE HOST'S OWN FAILURE TEXT LEAVES HERE UNCLASSIFIED, and that is the whole
1034
1110
  # reason this does not call `pr_list_call`. That wrapper classifies a failure
1035
1111
  # ONCE — throttled, burst, or everything else — and composes the sentence a
@@ -1038,12 +1114,79 @@ url_encode() { # $1=raw → percent-encoded on stdout
1038
1114
  # message: measured here, a `429` became *"the host failed the request and said
1039
1115
  # nothing"* because `Rate limit … exceeded` was no longer in the text being
1040
1116
  # 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.
1117
+ # untouched on the FIRST page; a later page's failure returns the same raw code
1118
+ # with no partial array printed — a caller cannot tell "zero rows" from "the
1119
+ # walk broke before it saw any", so printing a prefix here would manufacture an
1120
+ # answer this function never had.
1121
+ #
1122
+ # THE SAME `next`-WALK SHAPE AS `bb_window_listing` (`:1200`), which strips
1123
+ # `BB_API_BASE` from an absolute `next` URL to keep asking `bb api` with a
1124
+ # relative path — `bb api` concatenates `${BB_API}${path}` itself. That helper
1125
+ # has no page cap because its own completeness check is the server's `size`
1126
+ # field; this one has no `size` to check against (the endpoint's envelope here
1127
+ # carries it too, but a state-filtered count racing concurrent merges is not
1128
+ # the guard this slice adds), so the cap is the only bound on the walk.
1129
+ #
1130
+ # SHARED BY `bb_branch_query`, `bb_state_listing` AND `pr-review`'s
1131
+ # statuses/comments reads: the same walk and failure rule serve a
1132
+ # branch-filtered query, a plain state listing and a bare path alike, so the
1133
+ # loop lives once. $1=first path $2=truncation label $3=truncation detail
1134
+ # $4=row limit, or "" for the page-cap mode below; rest=global bb args →
1135
+ # combined values[] on stdout.
1136
+ #
1137
+ # TWO STOPPING RULES, CHOSEN BY WHETHER `$4` IS SET. With no limit, the walk
1138
+ # is `bb_branch_query`'s original shape: it runs until `next` is absent or
1139
+ # `BB_BRANCH_QUERY_PAGE_CAP` pages have been read, and a cap-stopped walk
1140
+ # reports itself and exits 3 — the question failed, not merely empty.
1141
+ #
1142
+ # WITH A LIMIT, THE WALK STOPS AT A ROW COUNT RATHER THAN A PAGE COUNT, AND A
1143
+ # CLEAN STOP EXITS 0. `bb_state_listing` asks for exactly the rows its caller
1144
+ # requested; stopping there is not a failure to read everything, it is
1145
+ # answering the question asked — the same distinction `pr_list_report_truncation`
1146
+ # draws for GitHub's own `--limit`. THE STOP RULE LIVES IN THE DOMAIN:
1147
+ # `walkStep` in `packages/domain/src/rules/listing-page.ts`, asked after every
1148
+ # page through `board/plot-listing-walk.mjs` with the pages read so far. It
1149
+ # stops at the first of: a page with no `next`, `$4` rows held, a page that
1150
+ # added no rows, or ceil(`$4` / `BB_LIST_PAGELEN`) pages read — the plan's cost
1151
+ # model (`2026-10-23-read-merged-prs-from-the-merge`, Approach 1). The bundle
1152
+ # prints the rows trimmed to `$4` and writes `BB_LIST_NEXT_FILE` (if set) the
1153
+ # stopping page's own `next` reading — "1" present, "0" absent, "" no
1154
+ # envelope — or "1" whenever the trim dropped a row, so
1155
+ # `pr_list_report_truncation` says "possibly truncated" for every stop that
1156
+ # left a row unread. COST: one `node` start (~40 ms) per page, at most
1157
+ # ceil(limit / 50) per state listing, beside a host request per page.
1158
+ # A REQUEST FAILURE IS STILL A REQUEST FAILURE: the limit changes how a CLEAN
1159
+ # stop is reported, never how a broken one is.
1160
+ _bb_paged_walk() {
1161
+ local _path="$1" _label="$2" _detail="$3" _limit="$4" _out _spool _next _page=0; shift 4
1162
+ # `plot_tmpfile` registers `_spool` for removal at process exit — no manual
1163
+ # `rm` on an early return; the walk only ever runs a handful of times per
1164
+ # process, so the file outliving one call costs nothing a caller can see.
1165
+ # The spool holds each page's whole response, one per line.
1166
+ plot_tmpfile _spool host-paged-walk || return 3; while [ -n "$_path" ]; do
1167
+ # A ROW-LIMIT WALK'S PAGE CAP IS `$4`, which `walkStep`'s page bound
1168
+ # ceil(`$4` / pagelen) always reaches first; with no limit it is
1169
+ # `BB_BRANCH_QUERY_PAGE_CAP`.
1170
+ [ "$((++_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; }
1171
+ # `jq` is applied only to a SUCCESSFUL payload. Piping a failed call into it
1172
+ # would turn the host's exit code into jq's, and a parse error and a spent
1173
+ # quota are not the same fact. A failure on page 2+ returns the same raw
1174
+ # code the first page would have — see the header above.
1175
+ _out="$(bb "$@" api "$_path")" || return $?
1176
+ jq -c . <<<"$_out" >> "$_spool" && _next="$(jq -r '.next // empty' <<<"$_out")" || return 3
1177
+ # A ROW-LIMIT WALK ASKS THE DOMAIN after every page. The bundle exits 0 to
1178
+ # read the next page, 10 once it has printed the walk's answer and written
1179
+ # the stopping `next` reading, and 3 where the pages did not parse; 10
1180
+ # returns 0 here and every other code returns as it is.
1181
+ [ -z "$_limit" ] || node "$here/board/plot-listing-walk.mjs" "$_limit" "$BB_LIST_PAGELEN" "${BB_LIST_NEXT_FILE:-}" < "$_spool" || return "$(($? == 10 ? 0 : $?))"
1182
+ if [ -z "$_next" ]; then _path=""; elif [[ "$_next" == "$BB_API_BASE"/* ]]; then _path="${_next#"$BB_API_BASE"}"
1183
+ else echo "plot-host: $_label: next page '$_next' is outside $BB_API_BASE; refusing to read past it" >&2; return 3; fi
1184
+ done
1185
+ jq -c -s 'map(.values // []) | add // []' < "$_spool"
1186
+ }
1187
+
1044
1188
  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
1189
+ local _br="$1" _st="$2" _q; shift 2
1047
1190
  _q="state=$(url_encode "\"$(bb_query_state "$_st")\"") AND source.branch.name=$(url_encode "\"$_br\"")"
1048
1191
  # THE WINDOW COMPOSES WITH THE STATE FILTER AND NEVER REPLACES IT. Bitbucket
1049
1192
  # takes ONE `q=` parameter, so a second one would silently win or lose
@@ -1061,27 +1204,31 @@ bb_branch_query() { # $1=branch $2=adapter state; rest=global bb args → values
1061
1204
  # so an exclusive comparison against a truncated stamp would drop a PR updated
1062
1205
  # inside the same second. Re-reading one row the caller already holds costs a
1063
1206
  # 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 // []'
1207
+ [ -n "$PR_LIST_SINCE" ] && _q="$_q AND updated_on>=$(url_encode "\"$PR_LIST_SINCE\"")"
1208
+ # The space between the two terms is encoded too, inline below; `bb api`
1209
+ # passes the path to curl verbatim and an unencoded space would truncate the
1210
+ # request line. THE LEADING SLASH on the path: see the block header above —
1211
+ # without it this is a 403 that reads as a scope error.
1212
+ _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
1213
  }
1078
1214
 
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"; }
1215
+ # HOW MANY PAGES `bb_branch_query` WILL WALK BEFORE REPORTING "possibly
1216
+ # truncated" AND REFUSING TO GUESS AT THE REST.
1217
+ #
1218
+ # THERE WAS NO EXISTING CAP TO REUSE. `bb_window_listing` (`:1200`) walks
1219
+ # `next` with no cap at all — its own completeness proof is the server's
1220
+ # `size` field, read once the whole walk finishes — and nothing else in this
1221
+ # file bounds a `next`-walk by page count. The plan that commissioned this
1222
+ # change ("bounded by the existing page cap") named one that does not exist;
1223
+ # this constant is new, not reused, and that is reported in the branch's PR.
1224
+ #
1225
+ # 20, CHOSEN RATHER THAN MEASURED: at `pagelen=50` it reaches 1000 pull
1226
+ # requests for one branch in one state, an order of magnitude past the
1227
+ # largest number of pull requests measured for any single tracked branch on
1228
+ # this estate (`a-pr-list-reads-every-page.md`: 886 MERGED pull requests
1229
+ # across an entire repository, not one branch). A branch that still exceeds
1230
+ # it gets the truncation report rather than a silent prefix.
1231
+ BB_BRANCH_QUERY_PAGE_CAP=20
1085
1232
 
1086
1233
  # Ask about EVERY tracked branch in one state, printing one combined array.
1087
1234
  #
@@ -1139,8 +1286,7 @@ bb_branch_sweep() { # global bb args… --state <s> --json → one JSON array
1139
1286
  # re-parses of a growing accumulator: the old shape re-read every row it had
1140
1287
  # already seen once per branch, so eleven branches parsed the first branch's
1141
1288
  # payload eleven times.
1142
- local _spool
1143
- plot_tmpfile _spool host-sweep || return 3
1289
+ local _spool; plot_tmpfile _spool host-sweep || return 3
1144
1290
  for _br in $PR_LIST_BRANCHES; do
1145
1291
  # RETURN, NOT EXIT. This runs inside the command substitution
1146
1292
  # `pr_list_call` wraps the sweep in, so the code must travel back as this
@@ -1237,8 +1383,7 @@ bb_window_listing() { # global bb args… --state <s> --json → one JSON array
1237
1383
  # pages and arrive twice.
1238
1384
  _rows="$(jq -c -s 'add // [] | unique_by(.id)' < "$_spool")" || { rm -f "$_spool"; return 3; }
1239
1385
  rm -f "$_spool"
1240
- local _got
1241
- _got="$(jq 'length' <<<"$_rows")" || return 3
1386
+ local _got; _got="$(jq 'length' <<<"$_rows")" || return 3
1242
1387
  if [ "$_got" -lt "$_size" ] 2>/dev/null; then
1243
1388
  echo "bitbucket window state=$_st is short ($_got of $_size matches after $_pages pages); refusing it rather than printing it as whole" >&2
1244
1389
  return 3
@@ -1246,7 +1391,8 @@ bb_window_listing() { # global bb args… --state <s> --json → one JSON array
1246
1391
  printf '%s' "$_rows"
1247
1392
  }
1248
1393
 
1249
- # List the pull requests in ONE state, one page of 50, as one array.
1394
+ # List the pull requests in ONE state, following `next` up to `PR_LIST_LIMIT`
1395
+ # rows, as one array.
1250
1396
  #
1251
1397
  # THE PLAIN LISTING, and the fourth command in `pr_list_states`' slot. It takes
1252
1398
  # the same trailing `--state <s> --json` as `bb_branch_sweep` and
@@ -1255,13 +1401,25 @@ bb_window_listing() { # global bb args… --state <s> --json → one JSON array
1255
1401
  #
1256
1402
  # /repositories/{ws}/{repo}/pullrequests?state=MERGED&pagelen=50
1257
1403
  #
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).
1404
+ # EVERY PAGE UP TO THE LIMIT IS READ, WHERE A SINGLE REQUEST USED TO BE THE
1405
+ # WHOLE ANSWER. Before this slice, one `bb api` call at `pagelen=50` was taken
1406
+ # as the state's listing outright — correct only when a state held 50 rows or
1407
+ # fewer, and silently short against #333's measurement of ~780 merged PRs
1408
+ # invisible past the first page. `_bb_paged_walk`'s row-limit mode (its own
1409
+ # header has the stopping rule) now follows `next` until it holds
1410
+ # `PR_LIST_LIMIT` rows or the host stops offering one, so a `--limit 1000`
1411
+ # caller gets up to 1000 rows of this state rather than 50 regardless of how
1412
+ # it asked. `PR_LIST_LIMIT` empty means no `--limit` was requested, and the
1413
+ # walk then stops at `BB_LIST_PAGELEN` rows: one request, the answer every
1414
+ # caller before this slice got and still gets.
1415
+ #
1416
+ # ONE REQUEST PER STATE AT THE OLD CEILING, WHERE `bb pr list` SPENDS UP TO
1417
+ # FIVE. `bb pr list` sends no `pagelen`, Bitbucket answers 10 rows a page, and
1418
+ # `bb_paginate` walks pages until it holds 50. Asking `pagelen=50` returns the
1419
+ # same 50 rows in one request. Measured 2026-09-30 on `quatico/quaweb-website`
1420
+ # with bb 1.9.0: the three states cost 8 requests through `bb pr list` (open 1,
1421
+ # merged 5, declined 2) and 3 through this path at one page each, and both
1422
+ # return the same 67 rows (3 open, 50 merged, 14 declined).
1265
1423
  #
1266
1424
  # THE STATES STAY SEPARATE CALLS. One `state=` union over the three returns the
1267
1425
  # 50 most recently updated rows across all of them: measured on the same
@@ -1270,21 +1428,22 @@ bb_window_listing() { # global bb args… --state <s> --json → one JSON array
1270
1428
  # `bb_states_for` records, reached through the page cap instead of through a
1271
1429
  # flag.
1272
1430
  #
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.
1431
+ # A CLEAN STOP AT THE LIMIT EXITS 0, NEVER 3. `_bb_paged_walk`'s header draws
1432
+ # the line: a row-limit stop answered exactly what the caller asked for, so it
1433
+ # is not the same fact as the page-cap stop `bb_branch_query` reports with
1434
+ # "possibly truncated" and exit 3. Whether THIS state's rows exceed the limit
1435
+ # unprovably is `pr_list_report_truncation`'s question, not this function's.
1436
+ # It reads the walk's answer back from `BB_LIST_NEXT_FILE` (`pr_list_states`
1437
+ # sets the path; this runs in that call's own subshell, so a global here would
1438
+ # never reach the caller): the stopping page's own `next`, or "1" where the
1439
+ # walk trimmed rows, so a `--limit` that is not a multiple of `pagelen` still
1440
+ # reports correctly. The length table answers only where no envelope was read.
1282
1441
  #
1283
1442
  # 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.
1443
+ # `bb_branch_query`: `pr_list_call` classifies once, so a `429` on any page
1444
+ # still reads as a rate limit.
1286
1445
  bb_state_listing() { # global bb args… --state <s> --json → one JSON array
1287
- local _st="" _args=() _out
1446
+ local _st="" _args=()
1288
1447
  while [ $# -gt 0 ]; do
1289
1448
  case "$1" in
1290
1449
  --state) _st="${2:?}"; shift 2 ;;
@@ -1293,9 +1452,9 @@ bb_state_listing() { # global bb args… --state <s> --json → one JSON array
1293
1452
  esac
1294
1453
  done
1295
1454
  [ -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 // []'
1455
+ _bb_paged_walk "/repositories/{ws}/{repo}/pullrequests?state=$(bb_query_state "$_st")&pagelen=$BB_LIST_PAGELEN" \
1456
+ "bitbucket pr-list state=$_st" "a join against this page may read older branches as 'no PR' (#333)" \
1457
+ "${PR_LIST_LIMIT:-$BB_LIST_PAGELEN}" ${_args[@]+"${_args[@]}"}
1299
1458
  }
1300
1459
 
1301
1460
  # The branches a sweep asks about, newline-or-space separated. Empty means the
@@ -1325,6 +1484,15 @@ PR_LIST_BRANCHES=""
1325
1484
  # has none."
1326
1485
  PR_LIST_SINCE=""
1327
1486
 
1487
+ # The row count `bb_state_listing` stops at, or "" to ask for one request's
1488
+ # worth and report whatever comes back — the shape every caller before this
1489
+ # slice got. Set by `pr_list_states` itself (it already holds `$2=limit` in
1490
+ # scope) immediately before the loop, and read only by `bb_state_listing`;
1491
+ # see `PR_LIST_SINCE` immediately above for why this travels as a global
1492
+ # rather than a parameter threaded through `bb_branch_sweep` and
1493
+ # `bb_window_listing`'s shared calling convention.
1494
+ PR_LIST_LIMIT=""
1495
+
1328
1496
  # How many branches the last sweep asked about, and how many answered.
1329
1497
  #
1330
1498
  # THE COMPLETENESS SIGNAL, AND WHY THE ARM STATES IT RATHER THAN THE SCAN
@@ -1381,6 +1549,14 @@ pr_sweep_report() { # $1=states answered $2=states asked
1381
1549
  pr_list_states() { # $1=backend $2=limit $3=states $4=jq-program; rest=the host command
1382
1550
  local backend="$1" limit="$2" states="$3" jq_prog="$4"; shift 4
1383
1551
  local _s _raw _rc _err _tmp _ok=0 _failed=0 _first_rc=0 _failed_states="" BB_LIST_NEXT=""
1552
+ # A GLOBAL FOR `PR_LIST_SINCE`'S REASON: `bb_state_listing` runs inside the
1553
+ # command substitution below, its own subshell, so a parameter cannot reach
1554
+ # it any other way. Read only by `bb_state_listing` — `bb_branch_sweep` and
1555
+ # `bb_window_listing` pass through unread, exactly as they do for
1556
+ # `PR_LIST_SINCE`, because the limit means nothing to either: a sweep's cost
1557
+ # is the caller's branch count and a window refuses a short read outright,
1558
+ # so neither has a row count to stop at.
1559
+ PR_LIST_LIMIT="$limit"
1384
1560
  for _s in $states; do
1385
1561
  # `bb_state_listing` RUNS INSIDE THE SUBSTITUTION BELOW, its own subshell,
1386
1562
  # so a variable it sets cannot reach this one — the same trap `pr_list_call`
@@ -1746,7 +1922,7 @@ jenkins_no_instance() {
1746
1922
  # that into exit 4, *cannot be asked*.
1747
1923
  jenkins_rest_credential() { # $1 = the bare host
1748
1924
  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")"; }
1925
+ [ -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
1926
  [ -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
1927
  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
1928
  t=$(security find-generic-password -s jen -a "jenkins-token:$1" -w 2>/dev/null) || return 1
@@ -1772,12 +1948,14 @@ jenkins_job_url_path() { # $1 = job path, $2 = branch or ""
1772
1948
  # `Instance:` line rather than reinvented here — `jen` already turns a slug
1773
1949
  # like `ewz` into `jenkins-ci-ewz.internal.quatico.dev` and keys its stored
1774
1950
  # 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.
1951
+ # `jenkins_rest_credential` can only fail. Prints nothing and exits 1 when
1952
+ # `jen` is missing, unparseable, or the line is absent; exits 2 when the line
1953
+ # names no parenthesized host. The caller decides what an unresolved host
1954
+ # means, same contract as every other helper here.
1778
1955
  jenkins_resolve_host() {
1779
1956
  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
1957
+ [ -n "$line" ] || return 1
1958
+ sed -nE 's/.*\(https?:\/\/([^)\/]+).*/\1/p' <<<"$line" | grep . || return 2
1781
1959
  }
1782
1960
 
1783
1961
  # Every Jenkins build of one job, as a JSON array (newest first), or exit 3
@@ -1835,27 +2013,67 @@ jenkins_resolve_host() {
1835
2013
  # WITH A SHA, ONLY THAT SHA'S BUILDS, never another's. `result` is null while a build
1836
2014
  # runs, Jenkins' own word for *in flight*, mapped to the `status`/`conclusion`
1837
2015
  # split the contract already uses so the shape does not fork per connector.
2016
+ #
2017
+ # THE BRANCH AND ITS SHA COME FROM THE SAME ACTION. Each `actions[]` entry
2018
+ # with a `lastBuiltRevision` becomes one `{sha, branches}` record, read off
2019
+ # that one entry — never a flat list of every action's sha paired by position
2020
+ # with a flat list of every action's branch names, which can only agree by
2021
+ # luck once an action carries zero or several branches. A build is searched
2022
+ # record by record for the one whose `branches` names the ASKED BRANCH, on a
2023
+ # plain job same as a multibranch one — the job's last path segment names a
2024
+ # job, not a branch, and is never the key. A record naming no branch never
2025
+ # matches a named branch, and the build falls back to its LAST record only
2026
+ # when none of its records name any branch at all.
2027
+ #
2028
+ # JENKINS' `tree=` PARAMETER SELECTS FIELDS, NEVER VALUES: there is no syntax
2029
+ # for "only where result != NOT_BUILT", so the `NOT_BUILT`/`ABORTED` filter can
2030
+ # only run after the fetch, in jq. `{0,$limit}` on the Jenkins side must
2031
+ # therefore ask for MORE than `$limit` builds, or a build filtered out after
2032
+ # the cut silently shrinks the answer — `runs --limit 3` over five builds where
2033
+ # two are `NOT_BUILT` returning 1 row instead of 3. The over-fetch factor is
2034
+ # fixed at 3x, uncapped: it costs response BYTES, never an extra round trip or
2035
+ # rate-budget slot (`host_slot_take`/`budget_record_call` below run once per
2036
+ # path regardless of `limit`), and a single multibranch job's full history is
2037
+ # small enough that 3x of any realistic `--limit` stays well under what one
2038
+ # `tree=` query already returns today (measured 2026-09-10: 4855 bytes for
2039
+ # five builds).
2040
+ #
2041
+ # A BRANCH JENKINS HAS NOT INDEXED REFUSES BY NAME. The branch-specific path
2042
+ # is tried first; if it answers real JSON with no `builds` key, Jenkins
2043
+ # reached the job and simply has no such branch, and the refusal says so.
2044
+ # Only the root-path retry's container check (above) can turn that into an
2045
+ # empty-history read instead. A host that never answers at all — curl
2046
+ # failure, HTML, empty body — gets the generic "did not answer" refusal,
2047
+ # since nothing there proves Jenkins was even reached.
1838
2048
  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
2049
+ 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
2050
  instance="$(jenkins_instance)"; [ -n "$instance" ] || jenkins_no_instance
1841
2051
  slug="${instance%%/*}"; job="${instance#*/}"; [ "$job" = "$instance" ] && job=""
1842
2052
  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
2053
  [ -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
2054
  # A dotted slug IS a host already, `jen`'s own passthrough rule — only a
1845
2055
  # 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
2056
+ case "$slug" in *.*) host="$slug" ;; *) host="$(jenkins_resolve_host "$slug")" || {
2057
+ [ $? = 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
2058
+ exit 4; } ;; esac
1847
2059
  cred="$(jenkins_rest_credential "$host")" || {
1848
2060
  echo "plot-host: $op — no Jenkins API credential for '$host'" >&2
1849
2061
  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
2062
  exit 4
1851
2063
  }
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
2064
+ tree="tree=builds%5Bnumber,result,building,timestamp,url,actions%5BlastBuiltRevision%5BSHA1,branch%5Bname%5D%5D%5D%5D%7B0,$((limit * 3))%7D"
2065
+ body=""; root_path="$(jenkins_job_url_path "$job" "")"; branch_path="$(jenkins_job_url_path "$job" "$branch")"
2066
+ for path in "$branch_path" "$root_path"; do
1855
2067
  host_slot_take jenkins ''
1856
2068
  try=$(curl -sg --max-time 30 -u "$cred" "https://$host$path/api/json?$tree" 2>/dev/null) || true
1857
2069
  host_slot_give; budget_record_call jenkins ''
1858
2070
  if printf '%s' "$try" | jq -e 'has("builds")' >/dev/null 2>&1; then body="$try"; break; fi
2071
+ # A branch path that came back as REAL JSON (jq could parse and evaluate
2072
+ # it, just found no `builds` key) means Jenkins answered and indexed no
2073
+ # such branch — distinct from curl failing outright or answering HTML,
2074
+ # where jq's own exit code is 4 (empty input) or 5 (parse error) rather
2075
+ # than the 1 a successfully-evaluated `false` reports.
2076
+ [ "$path" = "$branch_path" ] && printf '%s' "$try" | jq -e . >/dev/null 2>&1 && branch_answered=1
1859
2077
  # ONLY AT THE ROOT: a multibranch container that answered its OWN `_class`
1860
2078
  # and no `builds` has not indexed this branch at all — an empty history,
1861
2079
  # not a refusal. Checking this on the BRANCH path too would be wrong: a
@@ -1867,37 +2085,39 @@ jenkins_sha_runs() {
1867
2085
  plain=1
1868
2086
  done
1869
2087
  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;
2088
+ [ -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; }
2089
+ 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
2090
  [ .builds[]
1876
- | { shas: [ .actions[]? | select(.lastBuiltRevision) | .lastBuiltRevision.SHA1 ],
1877
- br: [ .actions[]? | .lastBuiltRevision.branch[]?.name // empty | sub("^(refs/remotes/|refs/heads/)"; "") | sub("^origin/"; "") ],
2091
+ | { records: [ .actions[]? | select(.lastBuiltRevision) | .lastBuiltRevision
2092
+ | { sha: .SHA1, branches: [ .branch[]?.name // empty | sub("^(refs/remotes/|refs/heads/)"; "") | sub("^origin/"; "") ] } ],
1878
2093
  status: (if .building then "in_progress" else "completed" end),
1879
2094
  conclusion: (if .building then null else (.result // null) end),
1880
2095
  url: (.url // ""),
1881
2096
  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
2097
+ | if $sha != "" then map(select(headsha(.records) as $h | $h == $sha or (($sha | test("^[0-9a-f]{7,}$")) and ($h | startswith($sha)))))
2098
+ elif $plain == "" then . else map(select(any(.records[].branches[]; . == $branch))) end
2099
+ | map(.sha = headsha(.records) | del(.records)) | .[0:$limit]' || exit 4
1885
2100
  }
1886
2101
 
1887
2102
  # The sha-bound readings of the PR rows $3 whose branch colour in $2 cannot
1888
2103
  # settle the head: a JSON object keyed by branch, or nothing where no lookup
1889
2104
  # was needed. $1 = the op's name, $4 = optional path to also receive the
1890
2105
  # 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.
2106
+ # "named but the ask broke early" from "never named because the row is past
2107
+ # the cap" without a second, duplicate run of the same `rows` verb. A row past
2108
+ # the cap never stands on its colour. A named row whose ask broke stands on it
2109
+ # in GitHub's `pr-list`, and reads `checksLookup: broken` in Bitbucket's
2110
+ # `pr-list` and `pr-state`.
1894
2111
  # $5 = optional JSON object, branch -> the checksSha the caller's PR index
1895
2112
  # already has on record; a branch bound there to its CURRENT head costs the
1896
2113
  # pass nothing to re-confirm, so `rowsToBind` (rotation) spends the cap's
1897
2114
  # lookups on branches that are absent or stale there first. Absent entirely
1898
2115
  # where the caller holds no index — every row then sorts exactly as before.
1899
2116
  # `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.
2117
+ # lookup that cannot ask Jenkins ends the pass, and the rows it did not reach
2118
+ # get no bound entry. A failing `rows` call itself (the bundle crashes or
2119
+ # prints nothing) empties $4 and returns with no stdout at all, so every
2120
+ # ambiguous row this pass reads unknown rather than some subset of them.
1901
2121
  jenkins_bind_rows() {
1902
2122
  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
2123
  : >"${4:-/dev/null}"; [ -z "$_named" ] && return; cut -f1 <<<"$_named" >"${4:-/dev/null}"
@@ -1906,38 +2126,94 @@ jenkins_bind_rows() {
1906
2126
  done | node "$here/board/plot-jenkins-pr-checks.mjs" bind 2>/dev/null
1907
2127
  }
1908
2128
 
2129
+ # Seconds `bb_fold_mergeable` allows one `git fetch` of the base before
2130
+ # treating it as failed. `Checks wait` (3600s) is sized for a CI poll, not one
2131
+ # fetch; this is its own, much smaller bound. No config key is read nearby
2132
+ # this call site, so a constant stands, per the plan.
2133
+ readonly BB_FETCH_BOUND_S=10
2134
+
2135
+ # Runs `git fetch -q origin "+refs/heads/$1:refs/remotes/origin/$1"` and kills
2136
+ # it if it outruns `BB_FETCH_BOUND_S`, so a stalled SSH prompt (`git fetch` has
2137
+ # no built-in timeout) cannot hang `pr-state`/`pr-list` on one row. A timed-out
2138
+ # fetch exits non-zero, same as any other failed fetch — the caller cannot and
2139
+ # need not tell the two apart (#2481).
2140
+ bb_fetch_base_bounded() {
2141
+ local base="$1" pid watcher rc was_m
2142
+ # `git fetch` can itself spawn a child (an askpass helper, ssh, a credential
2143
+ # helper) that inherits this function's stdout/stderr. Killing only $pid
2144
+ # leaves that child orphaned and still holding the pipe open, so a caller
2145
+ # waiting on the pipe to close (not just on $pid to exit) stays blocked for
2146
+ # the full hang rather than the bound — measured against a stub `git fetch`
2147
+ # that forks a long-running child: `kill -TERM "$pid"` alone left the run
2148
+ # waiting the full duration even though `bb_fetch_base_bounded` itself had
2149
+ # already returned. `set -m` makes the backgrounded `git fetch` the leader
2150
+ # of its own process group, so `kill -TERM "-$pid"` (the negative pid) signals
2151
+ # the whole group — fetch and any child it spawned — not just the leader.
2152
+ case $- in *m*) was_m=yes ;; *) was_m=no ;; esac; set -m
2153
+ GIT_TERMINAL_PROMPT=0 git fetch -q origin "+refs/heads/$base:refs/remotes/origin/$base" 2>/dev/null & pid=$!
2154
+ ( sleep "$BB_FETCH_BOUND_S"; kill -TERM "-$pid" 2>/dev/null ) & watcher=$!
2155
+ wait "$pid" 2>/dev/null; rc=$?
2156
+ kill "$watcher" 2>/dev/null; wait "$watcher" 2>/dev/null; [ "$was_m" = yes ] || set +m
2157
+ return "$rc"
2158
+ }
2159
+
1909
2160
  # Overlays the `mergeable` reading on a Bitbucket `pr-state`/`pr-list` row ($1,
1910
2161
  # carrying `state`, `headSha` and `base`) from a local `git merge-tree
1911
2162
  # --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.
2163
+ # `bitbucket-pr-reading.ts`). A row that is not `OPEN` is printed unchanged
2164
+ # before any `jq`, `git` or `node` runs for it — MERGED and CLOSED rows are
2165
+ # settled, and a NONE row has no PR, so none of that work is theirs to pay for
2166
+ # (#2481).
2167
+ #
2168
+ # $2 = the repo slug (`owner/repo`) the caller resolved the row against, via
2169
+ # `--repo`; empty where the caller passed none. The fold runs `git` in the
2170
+ # CURRENT directory against ITS `origin` — a row from another repository would
2171
+ # be folded against the wrong base, silently. So a non-empty $2 that does not
2172
+ # match the local clone's `origin` slug (read through `plot-bitbucket-slug.mjs`,
2173
+ # the same bundle the Bitbucket build-status write resolves `origin` with)
2174
+ # answers `unknown` naming the mismatch, and never guesses by running git
2175
+ # anyway. A clone whose `origin` resolves to no slug cannot be compared either,
2176
+ # and also answers `unknown` rather than assume a match.
1914
2177
  #
1915
2178
  # 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.
2179
+ # (`BB_FETCHED`), bounded by `bb_fetch_base_bounded`, and a failed or timed-out
2180
+ # fetch reads `unknown`: a fetch that names the head too fails whole on
2181
+ # Bitbucket's short hash, and the stale `origin/<base>` it leaves behind
2182
+ # answers wrongly with confidence (#2208). The head is never fetched; a head
2183
+ # commit absent from the clone reads `unknown` with its sha. `git fetch` is a
2184
+ # git read, not a host CLI call, so the host stays unasked. A bundle that
2185
+ # cannot answer prints the unchanged row.
1922
2186
  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
2187
+ local row="$1" wantrepo="${2:-}" head base fetch="" in_clone="" mt_code="" mt_err="" localrepo reason
2188
+ jq -e '.state == "OPEN"' >/dev/null 2>&1 <<<"$row" || { printf '%s\n' "$row"; return 0; }
2189
+ if [ -n "$wantrepo" ]; then
2190
+ localrepo="$(node "$here/board/plot-bitbucket-slug.mjs" "$(git config --get remote.origin.url 2>/dev/null)" 2>/dev/null)"
2191
+ [ "$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; }
2192
+ fi
2193
+ IFS=$'\x1f' read -r head base < <(jq -r '[(.headSha // ""), (.base // "")] | join("\u001f")' <<<"$row" 2>/dev/null)
2194
+ if [ -n "$head" ] && [ -n "$base" ]; then
2195
+ 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
2196
  git cat-file -e "$head^{commit}" 2>/dev/null && in_clone=yes || in_clone=no
1928
2197
  [ "$fetch$in_clone" = okyes ] && { mt_err="$(git merge-tree --write-tree "origin/$base" "$head" 2>&1 >/dev/null)"; mt_code=$?; }
1929
2198
  fi
1930
2199
  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
2200
  }
1932
2201
 
1933
- # `pr-list --rich`'s per-line fold. Each row carries a `base` key only for
2202
+ # `pr-list --rich`'s per-line fold. $1 = the repo slug (see `bb_fold_mergeable`),
2203
+ # threaded onto every row. Each row carries a `base` key only for
1934
2204
  # `bb_fold_mergeable`, and this removes it again; an OPEN row whose reading is
1935
2205
  # `unknown` gains `mergeableReason`. The loop runs in one shell, so
1936
2206
  # `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)'; }
2207
+ 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
2208
 
1939
2209
  # Prints the `pr-state` row of the Bitbucket PR payload $1 (`null` for no PR).
1940
2210
  #
2211
+ # $2 = "1" to ask Jenkins for the check at all; anything else (including
2212
+ # absent) skips `jenkins_instance`/`jenkins_build_map`/`jenkins_bind_rows`
2213
+ # entirely and reads `checks: unknown` with no Jenkins call made — the shell
2214
+ # side of `pr-state --with-checks`. The merge controller passes the flag;
2215
+ # `pr-merge`'s head re-read does not, because it reads only `headSha`.
2216
+ #
1941
2217
  # Without `CI: jenkins` the check is `unknown`, absent and not false, as in
1942
2218
  # `pr-list`'s plain Bitbucket arm. Under it the branch colour from
1943
2219
  # `jenkins_build_map` settles `none` and `pending`, and a head whose colour is
@@ -1946,9 +2222,14 @@ bb_fold_mergeable_stream() { local line; while IFS= read -r line; do [ -z "$line
1946
2222
  # `headSha` is `source.commit.hash`, a short hash `jenkins_sha_runs` prefix-matches.
1947
2223
  # `mergeable` is `unknown` here; `pr-state` folds the real reading on top with
1948
2224
  # `bb_fold_mergeable`, and `pr-merge --match-head` reads only `headSha`.
2225
+ #
2226
+ # A row `rowsToBind` names for a sha lookup whose `jenkins_sha_runs` call then
2227
+ # broke early (Jenkins unreachable mid-pass) must not stand on its stale branch
2228
+ # colour. The `state` verb asks `rowsToBind` itself whether this one row was
2229
+ # named, from the same colours, and reads it `checksLookup: broken`.
1949
2230
  bb_state_row() {
1950
2231
  local colours=null bound=null inst
1951
- if jq -e '.id' >/dev/null 2>&1 <<<"$1" && [ "$(ci_scheme)" = "jenkins" ]; then
2232
+ if [ "${2:-0}" = 1 ] && jq -e '.id' >/dev/null 2>&1 <<<"$1" && [ "$(ci_scheme)" = "jenkins" ]; then
1952
2233
  inst="$(jenkins_instance)"
1953
2234
  [ -z "$inst" ] || colours="$(jenkins_build_map "$inst" | jq -c 'if .status == "ok" then (.map // {}) else null end' 2>/dev/null)" || colours=null
1954
2235
  [ "$colours" = null ] || bound="$(jenkins_bind_rows pr-state "$colours" "$(jq -c '[{headRefName:.source.branch.name,headRefOid:.source.commit.hash}]' <<<"$1")")"
@@ -2292,7 +2573,8 @@ rest_pr_to_state() {
2292
2573
  state: $state,
2293
2574
  draft: (.draft // false),
2294
2575
  url: (.html_url // ""),
2295
- mergeCommit: (.merge_commit_sha // ""), headSha: (.head.sha // ""), base: (.base.ref // ""), checks: "unknown", mergeable: mergeable_of }
2576
+ mergeCommit: (.merge_commit_sha // ""), headSha: (.head.sha // ""), base: (.base.ref // ""), checks: "unknown", mergeable: mergeable_of,
2577
+ mergedAt: (.merged_at // "") }
2296
2578
  '
2297
2579
  }
2298
2580
 
@@ -2322,10 +2604,11 @@ rest_pr_to_state() {
2322
2604
  # A caller wanting it asks for it by name.
2323
2605
  bb_states_for() {
2324
2606
  case "$1" in
2325
- all) printf 'open\nmerged\ndeclined\n' ;;
2326
- closed) printf 'declined\n' ;;
2607
+ all) printf 'open\nmerged\ndeclined\n' ;;
2608
+ settled) printf 'merged\ndeclined\n' ;; # terminal only — no `open` sweep
2609
+ closed) printf 'declined\n' ;;
2327
2610
  open|merged|declined|superseded) printf '%s\n' "$1" ;;
2328
- *) die "unknown --state '$1' for the bitbucket backend (open|merged|closed|declined|superseded|all)" ;;
2611
+ *) die "unknown --state '$1' for the bitbucket backend (open|merged|closed|declined|superseded|all|settled)" ;;
2329
2612
  esac
2330
2613
  }
2331
2614
 
@@ -2424,8 +2707,7 @@ bb_assert_issue_version() {
2424
2707
  # it answers *not proven* (1) and the caller keeps its exit-3 refusal: guessing
2425
2708
  # 4 from unreadable help would turn a broken bb into *no issue tracker*.
2426
2709
  bb_lacks_issue_command() {
2427
- local help
2428
- help="$(bb --help 2>&1 | bb_strip_ansi)" || return 1
2710
+ local help; help="$(bb --help 2>&1 | bb_strip_ansi)" || return 1
2429
2711
  grep -qE '^[[:space:]]+pr([[:space:]]|$)' <<<"$help" || return 1
2430
2712
  ! grep -qE '^[[:space:]]+issues?([[:space:]]|$)' <<<"$help"
2431
2713
  }
@@ -2473,8 +2755,7 @@ bb_identify() {
2473
2755
  }
2474
2756
  ver_stripped="$(bb_strip_ansi <<<"$ver_out")"
2475
2757
 
2476
- local version
2477
- version="$(grep -oE '[0-9]+\.[0-9]+\.[0-9]+' <<<"$ver_stripped" | head -1)"
2758
+ local version; version="$(grep -oE '[0-9]+\.[0-9]+\.[0-9]+' <<<"$ver_stripped" | head -1)"
2478
2759
  [ -z "$version" ] && version="unknown"
2479
2760
 
2480
2761
  # craftamap/bb includes a git sha in parentheses: `bb version 0.6.0 (abc1234)`
@@ -2510,8 +2791,7 @@ bb_test_json_support() {
2510
2791
  # reader can reproduce — rather than a provenance verdict `bb_identify`
2511
2792
  # cannot determine. A message that guesses wrong costs more than one that
2512
2793
  # says less.
2513
- BB_CAP_PROBE_RC="$rc"
2514
- BB_CAP_PROBE_MATCH=""
2794
+ BB_CAP_PROBE_RC="$rc"; BB_CAP_PROBE_MATCH=""
2515
2795
 
2516
2796
  # THE MEASUREMENT ANSWERS FIRST, AND THE TEXT ONLY WHEN IT IS ABSENT.
2517
2797
  #
@@ -2765,7 +3045,11 @@ read_env_var() { # $1=name $2=file → the value, or nothing
2765
3045
  # desk or a scratch worktree under `Worktree root` has none of its own, and
2766
3046
  # `git rev-parse --show-toplevel` there answers with the WORKTREE, which never
2767
3047
  # holds one. Prints "<path>|" (worktree) or "<path>|the main checkout's" on a
2768
- # readable candidate, or nothing when neither location has one.
3048
+ # candidate, or nothing when neither location has one.
3049
+ #
3050
+ # $1 and $2 name the two vars a candidate must hold BOTH of — every caller
3051
+ # needs a pair, never a lone half, so a readable-but-incomplete candidate is
3052
+ # skipped in favour of the next one rather than returned anyway.
2769
3053
  #
2770
3054
  # NO UPWARD WALK past either location — the fallback is exactly one more
2771
3055
  # place to look, not a search. `--git-common-dir`'s parent is the main
@@ -2773,10 +3057,19 @@ read_env_var() { # $1=name $2=file → the value, or nothing
2773
3057
  # command fails, prints nothing, or its parent directory does not exist, this
2774
3058
  # falls through to "no main checkout .env" rather than inventing a path.
2775
3059
  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"
3060
+ local root env_file common
3061
+ root="$(git rev-parse --show-toplevel 2>/dev/null)" || root="."; env_file="$root/.env"
3062
+ plot_env_file_qualifies "$env_file" "$1" "$2" && { printf '%s|' "$env_file"; return 0; }
3063
+ common="$(git rev-parse --path-format=absolute --git-common-dir 2>/dev/null)" && [ -n "$common" ] || return 0
3064
+ env_file="$(dirname "$common")/.env"
3065
+ plot_env_file_qualifies "$env_file" "$1" "$2" && printf "%s|the main checkout's " "$env_file"
3066
+ }
3067
+
3068
+ # A candidate qualifies when it is readable and holds both named vars —
3069
+ # never a lone half of a pair.
3070
+ plot_env_file_qualifies() {
3071
+ [ -r "$1" ] || return 1
3072
+ [ -n "$(read_env_var "$2" "$1")" ] && [ -n "$(read_env_var "$3" "$1")" ]
2780
3073
  }
2781
3074
 
2782
3075
  # The env var scheme for Jira auth. The plan left the EXACT names open, to be
@@ -2792,20 +3085,18 @@ plot_env_file() {
2792
3085
  # `die3` exits the whole script only from there, not from inside a command
2793
3086
  # substitution where it would end only the subshell and leak a second error.
2794
3087
  #
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.
3088
+ # WHERE BOTH ARE UNSET, `plot_env_file` IS READ, naming the two vars so it
3089
+ # skips a candidate holding only one — measured 2026-09-17, an operator
3090
+ # holding a working pair was sent to create a second token before this
3091
+ # fallback existed. THE VALUE IS NEVER PRINTED, only the source, so a 401 can
3092
+ # be debugged against the right one of two possible tokens.
2800
3093
  jira_load_env_file() {
2801
- local found env_file source email token
3094
+ local found env_file
2802
3095
  [ -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
3096
+ found="$(plot_env_file JIRA_EMAIL JIRA_API_TOKEN)"; [ -n "$found" ] || return 0
3097
+ env_file="${found%|*}"
3098
+ export JIRA_EMAIL="$(read_env_var JIRA_EMAIL "$env_file")" JIRA_API_TOKEN="$(read_env_var JIRA_API_TOKEN "$env_file")"
3099
+ echo "plot-host: JIRA_EMAIL and JIRA_API_TOKEN read from ${found#*|}.env" >&2
2809
3100
  }
2810
3101
 
2811
3102
  jira_require_config() {
@@ -2870,8 +3161,7 @@ jira_curl() {
2870
3161
  jira_budget_account() {
2871
3162
  local raw="${JIRA_EMAIL:-}"
2872
3163
  [ -n "$raw" ] || { printf 'unknown\n'; return 0; }
2873
- local h
2874
- h="$(printf '%s' "$raw" | shasum -a 256 2>/dev/null | awk '{print $1}')"
3164
+ local h; h="$(printf '%s' "$raw" | shasum -a 256 2>/dev/null | awk '{print $1}')"
2875
3165
  # No hasher, no guess: a raw email must never be the fallback, so an
2876
3166
  # unhashable account degrades to the same word an absent one uses.
2877
3167
  [ -n "$h" ] || { printf 'unknown\n'; return 0; }
@@ -2930,10 +3220,17 @@ jira_ask() { local raw rc; raw="$(jira_curl "$@")"; rc=$?; jira_check "$raw" "$r
2930
3220
  # github (HONOURS --limit) : a state is possibly truncated when it returned
2931
3221
  # AT LEAST the requested limit. Fewer rows than
2932
3222
  # 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.
3223
+ # bitbucket (FIXED PAGE) : `bb_state_listing` FOLLOWS `next` UP TO
3224
+ # `--limit` (`_bb_paged_walk`'s row-limit mode)
3225
+ # over fixed `pagelen`-row pages, so the kind
3226
+ # stays `fixed-page` rather than becoming
3227
+ # `honours-limit` — see `listingPagingFor`. The
3228
+ # walk is complete when its last page named no
3229
+ # `next` and it trimmed no row, and possibly
3230
+ # truncated when it stopped with a `next` named
3231
+ # or a row trimmed. Where no envelope was read,
3232
+ # a page SHORTER than the measured length is
3233
+ # complete (below).
2937
3234
  #
2938
3235
  # THE PAGE LENGTH IS A READING, NEVER A CONSTANT THE RULE NAMES. The listing
2939
3236
  # asks `pagelen=$BB_LIST_PAGELEN` through `bb api`, and the length holds only
@@ -2971,8 +3268,9 @@ jira_ask() { local raw rc; raw="$(jira_curl "$@")"; rc=$?; jira_check "$raw" "$r
2971
3268
  # into a minutes-long pulse. See the plan's Done-when item 3.
2972
3269
  #
2973
3270
  # 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.
3271
+ # it, `_bb_paged_walk` bounds a row-limit walk at ceil(limit / this) pages, and
3272
+ # `pr_list_report_truncation` reads it as the page length only for a `bb` in
3273
+ # BB_LIST_PAGE_VERSIONS.
2976
3274
  BB_LIST_PAGELEN=50
2977
3275
 
2978
3276
  # The `bb` versions measured to pass `pagelen` through `bb api` unchanged,
@@ -3016,13 +3314,12 @@ bb_list_page_length() {
3016
3314
  # version. #1757: `BB_LIST_PAGE_VERSIONS` names only versions this estate has
3017
3315
  # measured, so a page from any other version (1.11.1 included) could never be
3018
3316
  # 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.
3317
+ # truncated" even though the envelope already answered. With a limit,
3318
+ # `_bb_paged_walk` follows `next` and writes the reading of the page where it
3319
+ # stopped, or "1" where it trimmed rows: "0" proves the walk whole, and "1"
3320
+ # means a further page or a dropped row exists, so it is possibly truncated at
3321
+ # any row count, including 0. Only "" (no envelope shape was read) falls back
3322
+ # to the version table's page length.
3026
3323
  #
3027
3324
  # $1 backend $2 requested limit (may be "") $3 state word $4 row count
3028
3325
  # $5 envelope's own completeness reading: "0" no next, "1" next present, ""
@@ -3030,8 +3327,12 @@ bb_list_page_length() {
3030
3327
  pr_list_report_truncation() {
3031
3328
  local be="$1" limit="$2" state="$3" count="$4" next="${5:-}" len=""
3032
3329
  # 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
3330
+ [ -n "$limit" ] || return 0; [ "$count" -gt 0 ] 2>/dev/null || [ "$next" = "1" ] || return 0
3034
3331
  if [ "$be" = "github" ]; then
3332
+ # `gh` pages inside this one process and `gh()` recorded one request for it, so
3333
+ # the pages past the first are recorded here, from the rows: a request count,
3334
+ # not GraphQL points. The rule is the domain's (`githubExtraPages`).
3335
+ budget_record_call github github graphql "$(node "$here/board/plot-listing-pages.mjs" "$count" 2>/dev/null)"
3035
3336
  # github honours the limit: complete unless the page came back AT the limit.
3036
3337
  # Measured 2026-10-02 on this repository (1064 PRs): `--limit 1100`
3037
3338
  # answered 1065 rows and `--limit 2000` the same 1065, so a page short of
@@ -3039,9 +3340,10 @@ pr_list_report_truncation() {
3039
3340
  # exist rather than the rows requested.
3040
3341
  if [ "$count" -lt "$limit" ] 2>/dev/null; then pr_list_report_complete "$be" "$limit" "$state" "$count"; return 0; fi
3041
3342
  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)"
3343
+ # A walk whose last page named no further page is complete; one that
3344
+ # stopped with a further page named or rows trimmed is not; an unread
3345
+ # envelope is complete only below a measured page length.
3346
+ [ -n "$next" ] || len="$(bb_list_page_length)"
3045
3347
  if [ "$next" = "0" ] || { [ -n "$len" ] && [ "$count" -lt "$len" ] 2>/dev/null; }; then pr_list_report_complete "$be" "$limit" "$state" "$count"; return 0; fi
3046
3348
  fi
3047
3349
  # Named per state so a caller can resolve exactly the states that were
@@ -3091,8 +3393,7 @@ backend_declared() {
3091
3393
  printf '%s\n' "$PLOT_HOST" | tr '[:upper:]' '[:lower:]'
3092
3394
  return
3093
3395
  fi
3094
- local v
3095
- v="$(bash "$here/plot-config.sh" get "Git host" "" | tr '[:upper:]' '[:lower:]')"
3396
+ local v; v="$(bash "$here/plot-config.sh" get "Git host" "" | tr '[:upper:]' '[:lower:]')"
3096
3397
  case "$v" in
3097
3398
  bb) echo "bitbucket"; return ;;
3098
3399
  "") : ;;
@@ -3108,8 +3409,7 @@ backend_declared() {
3108
3409
  # THE REMOTE IS EVIDENCE AND THE KEY IS A DECLARATION, so the key still wins
3109
3410
  # above. What changes is only the case where nobody said: a hostname in the
3110
3411
  # 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)"
3412
+ local url; url="$(git config --get remote.origin.url 2>/dev/null || true)"
3113
3413
  case "$url" in
3114
3414
  *github.com*) echo "github"; return ;;
3115
3415
  *bitbucket.org*) echo "bitbucket"; return ;;
@@ -3355,8 +3655,11 @@ PLOT_BUDGET_HARVEST=""
3355
3655
  # and a full REST one summed to a number describing neither. Measured
3356
3656
  # 2026-09-01 from the response headers: `core` 4990 of 5000, `graphql` 0 of
3357
3657
  # 5000.
3358
- budget_record_call() { # $1=connector $2=backend-for-account $3=bucket
3658
+ budget_record_call() { # $1=connector $2=backend-for-account $3=bucket $4=spent (default 1; 0 or empty records nothing)
3359
3659
  [ -z "${PLOT_BUDGET_OFF:-}" ] || return 0
3660
+ # A spend that is not a positive number records nothing: the caller asked a rule
3661
+ # for it and the rule did not answer, and a made-up `1` would be a made-up spend.
3662
+ [ "${4-1}" -gt 0 ] 2>/dev/null || return 0
3360
3663
  local reading account bucket
3361
3664
  account="$(budget_account "${2:-$1}")"
3362
3665
  bucket="${3:-}"; [ -n "$bucket" ] || bucket="$(budget_bucket "$1")"
@@ -3364,18 +3667,17 @@ budget_record_call() { # $1=connector $2=backend-for-account $3=bucket
3364
3667
  # bucket: `X-RateLimit-Resource` names `code_search` for a search that no
3365
3668
  # reading of the command line would have classified as anything but `core`.
3366
3669
  if [ -n "${PLOT_BUDGET_HARVEST:-}" ]; then
3367
- IFS=$'\t' read -r _hbkt _blim _brem _brst <<<"$PLOT_BUDGET_HARVEST"
3368
- PLOT_BUDGET_HARVEST=""
3670
+ IFS=$'\t' read -r _hbkt _blim _brem _brst <<<"$PLOT_BUDGET_HARVEST"; PLOT_BUDGET_HARVEST=""
3369
3671
  [ -z "$_hbkt" ] || bucket="$_hbkt"
3370
3672
  # `actual` is the one basis a caller is entitled to trust, and a harvested
3371
3673
  # header is the only thing in this script that earns it: the connector said
3372
3674
  # it, about the call that just happened.
3373
- budget_append "$1" "$account" "$bucket" 1 "$_blim" "$_brem" "$_brst" actual
3675
+ budget_append "$1" "$account" "$bucket" "${4:-1}" "$_blim" "$_brem" "$_brst" actual
3374
3676
  return 0
3375
3677
  fi
3376
3678
  reading="$(budget_reading "$1")"
3377
3679
  IFS=$'\t' read -r _blim _brem _brst _bbas <<<"$reading"
3378
- budget_append "$1" "$account" "$bucket" 1 "$_blim" "$_brem" "$_brst" "$_bbas"
3680
+ budget_append "$1" "$account" "$bucket" "${4:-1}" "$_blim" "$_brem" "$_brst" "$_bbas"
3379
3681
  }
3380
3682
 
3381
3683
  # Reads `X-RateLimit-*` out of a header block, into the harvest variable.
@@ -3549,13 +3851,11 @@ host_concurrency_bound() { # $1=connector $2=account
3549
3851
  # the cadence degrade. The cost of one extra simultaneous call is a secondary
3550
3852
  # refusal that lowers the bound — evidence, through the mechanism this slice is
3551
3853
  # built on.
3552
- PLOT_SLOT_WAIT_MAX_S=30
3553
- PLOT_SLOT_POLL_S=1
3854
+ PLOT_SLOT_WAIT_MAX_S=30; PLOT_SLOT_POLL_S=1
3554
3855
 
3555
3856
  # The slot this process holds, so the wrappers can give it back. Empty where
3556
3857
  # none was taken — an unbounded connector, or a wait that ran out.
3557
- PLOT_SLOT_INDEX=''
3558
- PLOT_SLOT_ACCOUNT=''
3858
+ PLOT_SLOT_INDEX=''; PLOT_SLOT_ACCOUNT=''
3559
3859
 
3560
3860
  # Claims a slot for the call about to be made, waiting where the account is
3561
3861
  # busy. Never refuses: at worst it proceeds unbounded, which is what every
@@ -3629,6 +3929,12 @@ shift
3629
3929
  # answer at all" — the one code every caller reads as permanent rather than
3630
3930
  # transient. Collapsing it to 1 here would tell a GitLab repo to retry forever.
3631
3931
  be="$(backend)" || exit $?
3932
+ # PLOT_HOST_OTHER=1 ASKS THE OTHER DRIVABLE BACKEND, the `HOST_DRIVES` entry
3933
+ # that is not this checkout's own. `hostShell.prState` and `prMerged` set it to
3934
+ # retry a cross-repo `--repo` reference on a clean miss (#2158); the decision is
3935
+ # `rules/cross-repo-probe.ts`. The variable stays in the environment, so a
3936
+ # re-exec of this script asks the same backend.
3937
+ [ -z "${PLOT_HOST_OTHER:-}" ] || be="$(printf '%s\n' $HOST_DRIVES | awk -v be="$be" '$0 != be { o = $0 } END { print o }')"
3632
3938
 
3633
3939
  # EVERY GITHUB OP CONSULTS THE ROUTER, ONCE, HERE. `gh_route` is asked before
3634
3940
  # the op runs and its answer is read from `$route` by whichever arm needs it —
@@ -3728,10 +4034,11 @@ case "$op" in
3728
4034
 
3729
4035
  pr-state)
3730
4036
  ref="${1:?pr-state needs a PR number or branch}"; shift || true
3731
- repo_args=()
4037
+ repo_args=(); repo_slug=""; with_checks=0
3732
4038
  while [ $# -gt 0 ]; do
3733
4039
  case "$1" in
3734
- --repo) repo_args=(-R "${2:?}"); shift 2 ;;
4040
+ --repo) repo_args=(-R "${2:?}"); repo_slug="${2:?}"; shift 2 ;;
4041
+ --with-checks) with_checks=1; shift ;;
3735
4042
  *) die "pr-state: unknown arg $1" ;;
3736
4043
  esac
3737
4044
  done
@@ -3754,7 +4061,7 @@ case "$op" in
3754
4061
  rm -f "$HOST_ERR"
3755
4062
  rest_pr_to_state <<<"$out"
3756
4063
  else
3757
- err="$(cat "$HOST_ERR" 2>/dev/null)"; rm -f "$HOST_ERR"
4064
+ host_err
3758
4065
  host_miss_or_fail "$err" \
3759
4066
  '{"number":0,"state":"NONE","draft":false,"url":"","mergeCommit":""}' || exit $?
3760
4067
  fi
@@ -3775,7 +4082,7 @@ case "$op" in
3775
4082
  jq -c '.[0]' <<<"$out" | rest_pr_to_state
3776
4083
  fi
3777
4084
  else
3778
- err="$(cat "$HOST_ERR" 2>/dev/null)"; rm -f "$HOST_ERR"
4085
+ host_err
3779
4086
  host_miss_or_fail "$err" \
3780
4087
  '{"number":0,"state":"NONE","draft":false,"url":"","mergeCommit":""}' || exit $?
3781
4088
  fi
@@ -3783,11 +4090,11 @@ case "$op" in
3783
4090
  # mergeCommit is what lets a caller ask "which release contains this?" —
3784
4091
  # `git tag --contains <sha>` answers exactly, where dates cannot. It is ""
3785
4092
  # 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
4093
+ 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
4094
  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"
4095
+ 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
4096
  else
3790
- err="$(cat "$HOST_ERR" 2>/dev/null)"; rm -f "$HOST_ERR"
4097
+ host_err
3791
4098
  # REFUSED FOR RATE IS NOT ANSWERED. The budget gate above could not see
3792
4099
  # this coming — `rate_limit` does not report the secondary limit — so the
3793
4100
  # cheap path was chosen and then declined. The second path is the one
@@ -3822,9 +4129,15 @@ case "$op" in
3822
4129
  if [[ "$ref" =~ ^[0-9]+$ ]]; then
3823
4130
  if out="$(bb ${repo_args[@]+"${repo_args[@]}"} pr view "$ref" --json 2>"$HOST_ERR")"; then
3824
4131
  rm -f "$HOST_ERR"
3825
- bb_fold_mergeable "$(bb_state_row "$out")"
4132
+ # `$(bb_state_row ...)` RUNS IN A SUBSHELL, so a failure inside it
4133
+ # (a bad Jenkins answer, an unreadable row) was lost the moment its
4134
+ # stdout was captured — `bb_fold_mergeable` always saw success. The
4135
+ # assignment's status is the substitution's, so `|| exit $?` ends the
4136
+ # op with it before `bb_fold_mergeable` (which cannot fail) runs.
4137
+ state_row="$(bb_state_row "$out" "$with_checks")" || exit $?
4138
+ bb_fold_mergeable "$state_row" "$repo_slug"
3826
4139
  else
3827
- err="$(cat "$HOST_ERR" 2>/dev/null)"; rm -f "$HOST_ERR"
4140
+ host_err
3828
4141
  host_miss_or_fail "$err" '{"number":0,"state":"NONE","draft":false,"url":"","mergeCommit":""}' || exit $?
3829
4142
  fi
3830
4143
  else
@@ -3881,9 +4194,13 @@ case "$op" in
3881
4194
  # The hash rides on the page the branch query already fetched, so this
3882
4195
  # costs no extra call. `bb_branch_query` already filtered to the
3883
4196
  # branch, so every row in `out` already matches it.
3884
- bb_fold_mergeable "$(bb_state_row "$(jq -c '.[0] // null' <<<"$out")")"
4197
+ #
4198
+ # The exit status is kept through the command substitution the same
4199
+ # way the numeric-ref arm above does — see its comment.
4200
+ state_row="$(bb_state_row "$(jq -c '.[0] // null' <<<"$out")" "$with_checks")" || exit $?
4201
+ bb_fold_mergeable "$state_row" "$repo_slug"
3885
4202
  else
3886
- err="$(cat "$HOST_ERR" 2>/dev/null)"; rm -f "$HOST_ERR"
4203
+ host_err
3887
4204
  host_miss_or_fail "$err" '{"number":0,"state":"NONE","draft":false,"url":"","mergeCommit":""}' || exit $?
3888
4205
  fi
3889
4206
  fi
@@ -3903,8 +4220,7 @@ case "$op" in
3903
4220
  # deciding whether to remove something. Exit 3 is still reserved for the call
3904
4221
  # itself failing in a way this adapter does not recognise as a miss.
3905
4222
  pr-merged)
3906
- ref="${1:?pr-merged needs a branch}"; shift || true
3907
- repo_args=()
4223
+ ref="${1:?pr-merged needs a branch}"; shift || true; repo_args=()
3908
4224
  while [ $# -gt 0 ]; do
3909
4225
  case "$1" in
3910
4226
  --repo) repo_args=(-R "${2:?}"); shift 2 ;;
@@ -3921,7 +4237,7 @@ case "$op" in
3921
4237
  rm -f "$HOST_ERR"
3922
4238
  jq -e 'any(.[]; .mergedAt != null)' >/dev/null 2>&1 <<<"$out" && echo "merged" || echo "not-merged"
3923
4239
  else
3924
- err="$(cat "$HOST_ERR" 2>/dev/null)"; rm -f "$HOST_ERR"
4240
+ host_err
3925
4241
  miss_or_unknown "$err"
3926
4242
  fi
3927
4243
  else
@@ -3936,16 +4252,11 @@ case "$op" in
3936
4252
  # ceiling (see `bb_branch_sweep`'s header).
3937
4253
  if out="$(bb_branch_query "$ref" merged ${repo_args[@]+"${repo_args[@]}"} 2>"$HOST_ERR")"; then
3938
4254
  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
4255
+ # `bb_branch_query` now follows every page, so a row's absence here is
4256
+ # the host's own answer rather than a page boundary (#2484).
4257
+ jq -e 'any(.[]; .state == "MERGED")' >/dev/null 2>&1 <<<"$out" && echo "merged" || echo "not-merged"
3947
4258
  else
3948
- err="$(cat "$HOST_ERR" 2>/dev/null)"; rm -f "$HOST_ERR"
4259
+ host_err
3949
4260
  miss_or_unknown "$err"
3950
4261
  fi
3951
4262
  fi
@@ -3967,8 +4278,8 @@ case "$op" in
3967
4278
  # this only for a branch it has already been told merged, and the plan it
3968
4279
  # serves budgets one host call per branch either way.
3969
4280
  #
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.
4281
+ # `--state all` for `pr-merged`'s own two reasons: a merged PR reports
4282
+ # CLOSED, and the newest PR is not the merge.
3972
4283
  #
3973
4284
  # PRINTS NOTHING AND EXITS 0 where no PR merged — an ANSWER, the same shape
3974
4285
  # `pr-state` gives for a missing PR. Exit 3 is the question failing.
@@ -3976,10 +4287,13 @@ case "$op" in
3976
4287
  # `pr-merge-dest` RUNS THE SAME QUERY and prints every merged PR instead of
3977
4288
  # the first sha: one `number<TAB>base<TAB>sha<TAB>mergedAt` line each, read
3978
4289
  # 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=()
4290
+ # release-chain walk, where under-reading is a silent wrong hop rather than
4291
+ # a cheap prefilter (#2238) — so GitHub's `--limit` grows and the query
4292
+ # re-asks until a page returns short of it, same proof as
4293
+ # `pr_list_report_truncation`. Bitbucket's arm already pages in full via
4294
+ # `_bb_paged_walk` (#2484); its `mergedAt` is `updated_on` as in `pr-list`,
4295
+ # since the endpoint carries no real merge timestamp (#2202).
4296
+ ref="${1:?$op needs a branch}"; shift || true; repo_args=()
3983
4297
  while [ $# -gt 0 ]; do
3984
4298
  case "$1" in
3985
4299
  --repo) repo_args=(-R "${2:?}"); shift 2 ;;
@@ -3988,19 +4302,27 @@ case "$op" in
3988
4302
  done
3989
4303
  if [ "$op" = pr-merge-dest ]; then pick='.[] | [.n, .b, .s, .t] | @tsv'; else pick='first.s // empty'; fi
3990
4304
  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
4305
+ limit=100
4306
+ # A page as long as `--limit` may have been cut, so the limit doubles and
4307
+ # the query re-asks. The loop ends one of two ways: a short page, after
4308
+ # which `$HOST_ERR` is gone, or a failed call, which leaves `$HOST_ERR`
4309
+ # in place because the redirect creates it before `gh` runs.
4310
+ 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
4311
  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"
4312
+ [ "$(jq 'length' <<<"$out")" -lt "$limit" ] && break
4313
+ limit=$((limit * 2))
4314
+ done
4315
+ if [ -e "$HOST_ERR" ]; then
4316
+ host_err
4000
4317
  # A lookup miss is an answer: no PR, so no merge commit. Anything else
4001
4318
  # is the question failing, and silence must not read as "carried
4002
4319
  # nothing" — the caller distinguishes the two by the exit code.
4003
4320
  miss_or_exit3 "$err"
4321
+ else
4322
+ # Every merged PR carrying a sha, earliest-first ordering left to the
4323
+ # reader — `pickReleaseHop` and `pr-merge-commit`'s own `first` both sort.
4324
+ jq -r 'map(select(.mergedAt != null and .mergeCommit != null)
4325
+ | {n: .number, b: (.baseRefName // ""), s: .mergeCommit.oid, t: .mergedAt}) | '"$pick" <<<"$out"
4004
4326
  fi
4005
4327
  else
4006
4328
  bb_require_json
@@ -4009,11 +4331,10 @@ case "$op" in
4009
4331
  # `merge_commit.hash` on a merged PR.
4010
4332
  if out="$(bb_branch_query "$ref" merged ${repo_args[@]+"${repo_args[@]}"} 2>"$HOST_ERR")"; then
4011
4333
  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
4334
  jq -r 'map(select(.merge_commit.hash != null)
4014
4335
  | {n: .id, b: (.destination.branch.name // ""), s: .merge_commit.hash, t: (.updated_on // "")}) | '"$pick" <<<"$out"
4015
4336
  else
4016
- err="$(cat "$HOST_ERR" 2>/dev/null)"; rm -f "$HOST_ERR"
4337
+ host_err
4017
4338
  miss_or_exit3 "$err"
4018
4339
  fi
4019
4340
  fi
@@ -4030,8 +4351,7 @@ case "$op" in
4030
4351
  # A FAILURE WITH NO MESSAGE IS A FAILURE HERE, unlike `pr-state`: an empty
4031
4352
  # answer makes the caller fall back to a patch-id reading, so silence must
4032
4353
  # 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=()
4354
+ ref="${1:?pr-merged-heads needs a branch}"; shift || true; repo_args=()
4035
4355
  while [ $# -gt 0 ]; do
4036
4356
  case "$1" in
4037
4357
  --repo) repo_args=(-R "${2:?}"); shift 2 ;;
@@ -4043,8 +4363,8 @@ case "$op" in
4043
4363
  rm -f "$HOST_ERR"
4044
4364
  jq -r '.[] | select(.mergedAt != null and .headRefOid != null) | .headRefOid' <<<"$out" || exit 3
4045
4365
  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; }
4366
+ host_err
4367
+ [ -n "$err" ] && is_lookup_miss "$err" || die3 "${err:-gh pr list failed}"
4048
4368
  fi
4049
4369
  else
4050
4370
  bb_require_json
@@ -4053,27 +4373,33 @@ case "$op" in
4053
4373
  # `source.commit.hash`.
4054
4374
  if out="$(bb_branch_query "$ref" merged ${repo_args[@]+"${repo_args[@]}"} 2>"$HOST_ERR")"; then
4055
4375
  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
4376
  jq -r '.[] | (.source.commit.hash // empty)' <<<"$out" || exit 3
4058
4377
  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; }
4378
+ host_err
4379
+ [ -n "$err" ] && is_lookup_miss "$err" || die3 "${err:-the branch query failed}"
4061
4380
  fi
4062
4381
  fi
4063
4382
  ;;
4064
4383
 
4065
4384
  pr-review)
4066
4385
  if [ "$be" != "github" ]; then
4067
- pr="/repositories/{ws}/{repo}/pullrequests/${1:?pr-review needs a PR number}"
4386
+ 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"
4387
+ # `_bb_paged_walk` (its own header has the cap/failure rule) follows
4388
+ # `next` for both reads, so a `review-bypass:` comment or a status
4389
+ # recorded only on a later page is not missed (#2484). THE WRAP GOES
4390
+ # THROUGH STDIN, NOT `--argjson`: that flag passes its value through
4391
+ # argv, which Linux caps at 128 KB (`MAX_ARG_STRLEN`) — a large enough
4392
+ # page would die silently and read as "no rows" on CI while passing on
4393
+ # macOS, the exact fabricated-absence bug this slice removes.
4068
4394
  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
4395
+ && st="$(_bb_paged_walk "/repositories/{ws}/{repo}/commit/$sha/statuses?sort=-created_on&pagelen=50" "bitbucket pr-review" "$detail" "" | jq -c '{values: .}')" \
4396
+ && cm="$(_bb_paged_walk "$pr/comments?pagelen=100" "bitbucket pr-review" "$detail" "" | jq -c '{values: .}')" \
4397
+ && printf '%s\n%s\n%s\n' "$sha" "$st" "$cm" | node "$here/board/plot-jenkins-pr-checks.mjs" review \
4398
+ || die3 "pr-review: the read failed"
4399
+ exit 0; fi
4074
4400
  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
4401
  && 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; } ;;
4402
+ || die3 "pr-review: the read failed" ;;
4077
4403
 
4078
4404
  pr-create)
4079
4405
  title=""; body=""; base=""; head=""; draft=0
@@ -4115,14 +4441,14 @@ case "$op" in
4115
4441
  # answers 5 with its one-line notice where no key is declared: the merge
4116
4442
  # then runs as the signed-in `gh` identity. The token goes straight into
4117
4443
  # 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; }
4444
+ 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
4445
  merger_token=$(node "$here/plot-merger-token.mjs" "$merger_repo") || { mc=$?; [ "$mc" = 5 ] || exit "$mc"; }
4120
4446
  args=(pr merge "$num"); [ "$squash" = 1 ] && args+=(--squash) || args+=(--merge); [ "$delbranch" = 1 ] && args+=(--delete-branch)
4121
4447
  if [ -n "$merger_token" ]; then GH_TOKEN="$merger_token" gh "${args[@]}" --match-head-commit "$pin"; else gh "${args[@]}" --match-head-commit "$pin"; fi
4122
4448
  # Bitbucket's merge endpoint takes no head precondition (measured 2026-10-18,
4123
4449
  # see plan Notes), so the pin is enforced by re-reading the head via bb_state_row
4124
4450
  # 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[@]}"
4451
+ 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
4452
  else
4127
4453
  echo "plot-host: pr-merge: bitbucket needs --match-head <sha>; nothing was merged" >&2
4128
4454
  exit 1
@@ -4148,8 +4474,7 @@ case "$op" in
4148
4474
  ;;
4149
4475
 
4150
4476
  pr-list)
4151
- state="open"
4152
- rich=0
4477
+ state="open"; rich=0
4153
4478
  # Whether the rich fields are asked of the OPEN pull requests only. Set by
4154
4479
  # `--rich-open`, which also sets `rich`: the flag narrows what is ASKED and
4155
4480
  # never what is emitted.
@@ -4160,7 +4485,7 @@ case "$op" in
4160
4485
  # — so a caller comparing `origin/*` refs would join its refs against
4161
4486
  # another repository's PRs and report every branch as having none. The
4162
4487
  # caller knows which remote its refs came from; this op cannot guess it.
4163
- repo_args=()
4488
+ repo_args=(); repo_slug=""
4164
4489
  # `gh pr list` and `bb pr list` both cap at 30 by default. That is invisible
4165
4490
  # with --state open (few repos have 30 open PRs) and bites immediately with
4166
4491
  # --state all, where the newest 30 crowd out every older merged PR. A caller
@@ -4193,7 +4518,7 @@ case "$op" in
4193
4518
  # With `--state open` asked, both calls would list the same PRs and the
4194
4519
  # second would be waste, so this collapses to plain `--rich` there.
4195
4520
  --rich-open) rich=1; rich_open=1; shift ;;
4196
- --repo) repo_args=(-R "${2:?}"); shift 2 ;;
4521
+ --repo) repo_args=(-R "${2:?}"); repo_slug="${2:?}"; shift 2 ;;
4197
4522
  # `${2:?}` REFUSES AN EMPTY VALUE, and that is the point rather than
4198
4523
  # boilerplate. `--since ""` would reach GitHub as `--search "updated:>"`,
4199
4524
  # a syntax error the host may answer with everything or with nothing —
@@ -4244,6 +4569,8 @@ case "$op" in
4244
4569
  # travel to GitHub as part of the term and match nothing.
4245
4570
  search_args=()
4246
4571
  [ -n "$since" ] && search_args=(--search "updated:>$since")
4572
+ # One named branch is asked as one: `--head` filters server-side in the same single list call.
4573
+ head_args=(); [ "$(wc -w <<<"$branches")" -eq 1 ] && head_args=(--head "$branches")
4247
4574
 
4248
4575
  # --- Jenkins CI integration (orthogonal to Git host) ---
4249
4576
  # When `CI: jenkins` is configured, build status comes from Jenkins rather
@@ -4278,6 +4605,11 @@ case "$op" in
4278
4605
  fi
4279
4606
 
4280
4607
  if [ "$be" = "github" ]; then
4608
+ # `settled` HAS NO GITHUB QUERY OF ITS OWN: `gh pr list --state all`
4609
+ # already returns every row, and the caller using `settled` (the fleet
4610
+ # scan's second call) already strips the OPEN ones itself. A second
4611
+ # filter here would duplicate that stripping rather than replace it.
4612
+ [ "$state" = "settled" ] && state="all"
4281
4613
  # THE SPLIT READ, AND IT IS TWO CALLS BECAUSE THE COST IS PER ROW.
4282
4614
  # `gh pr list` pages internally and takes no page-size flag, so 1000 rich
4283
4615
  # rows cost 1000 rows' worth of `statusCheckRollup` whatever the page.
@@ -4411,7 +4743,7 @@ case "$op" in
4411
4743
  # $jstatus != "ok" → Jenkins could not answer; every row `unknown`.
4412
4744
  # $jentry == null → the branch has no Jenkins job; `none`.
4413
4745
  # 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[@]}"} \
4746
+ _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
4747
  --json number,title,state,headRefName,isDraft,mergeable,mergeStateStatus,reviewDecision,url,updatedAt,author,headRefOid,mergedAt)" || exit $?
4416
4748
  pr_list_report_truncation github "$limit" "$state" \
4417
4749
  "$(jq 'length' <<<"$_gh_raw" 2>/dev/null || echo 0)"
@@ -4456,7 +4788,7 @@ case "$op" in
4456
4788
  } + (if $jstatus == "ok" and $ambiguous and $eff == null then {checksLookup:"skipped"} else {} end)'
4457
4789
  else
4458
4790
  # 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[@]}"} \
4791
+ _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
4792
  --json number,title,state,headRefName,isDraft,statusCheckRollup,mergeable,mergeStateStatus,reviewDecision,url,updatedAt,author,headRefOid,mergedAt)" || exit $?
4461
4793
  pr_list_report_truncation github "$limit" "$state" \
4462
4794
  "$(jq 'length' <<<"$_gh_raw" 2>/dev/null || echo 0)"
@@ -4488,7 +4820,7 @@ case "$op" in
4488
4820
  # advances its watermark by. Without it a split full read would leave
4489
4821
  # the store unable to narrow and the daily full read would never fall
4490
4822
  # 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[@]}"} \
4823
+ _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
4824
  --json number,title,state,headRefName,isDraft,url,updatedAt,author,headRefOid,mergedAt)" || exit $?
4493
4825
  pr_list_report_truncation github "$limit" "$state" \
4494
4826
  "$(jq 'length' <<<"$_gh_raw" 2>/dev/null || echo 0)"
@@ -4517,16 +4849,11 @@ case "$op" in
4517
4849
  # integration GitHub uses, which is why it is ABOVE the backend branch.
4518
4850
  # Bitbucket's `unknown` becomes a real value.
4519
4851
  #
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
4852
+ # `bb pr list` REFUSES `--limit` OUTRIGHT ("unknown flag"), which is why
4853
+ # this goes through `bb api` rather than the CLI's own listing command.
4854
+ # The REST endpoint takes no such flag either; `--limit` is honoured by
4855
+ # `bb_state_listing` following `next` (see its header), not by anything
4856
+ # Bitbucket's API does on its own.
4530
4857
  # Establish that bb supports --json BEFORE calling it — Done-when 5.
4531
4858
  bb_require_json
4532
4859
  # Resolve the states BEFORE the loop. `for s in $(bb_states_for …)` runs
@@ -4596,19 +4923,37 @@ case "$op" in
4596
4923
  # `unknown`: its colour may belong to a commit this PR no longer
4597
4924
  # carries. A row `$named` lists but `$shamap` has no entry for is one
4598
4925
  # `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.
4926
+ # pass broke early. It reads `unknown` with `checksLookup: broken`
4927
+ # for the same reason: its colour may belong to an older commit.
4601
4928
  # `updatedAt` travels too: `rowsToBind` sorts by it to pick the most
4602
4929
  # recently updated rows, and a row list that never carries it sorts
4603
4930
  # 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
4931
+ # A MERGED or DECLINED row is settled; binding it spends a cap slot
4932
+ # on a row nobody acts on, the same waste `bb_fold_mergeable` was
4933
+ # fixed to skip for `mergeable` (wave 1, #2546). Filtered OUT before
4934
+ # `jenkins_bind_rows` ever sees the row, so it cannot be `$named`
4935
+ # either — a settled row reads its plain colour, never `skipped` or
4936
+ # `broken`.
4937
+ #
4938
+ # ONE CAP COVERS `--state all`. `pr_list_states` calls
4939
+ # `$PR_LIST_BIND_FN` once per state (open, merged, declined), and
4940
+ # each call starts at `SHA_LOOKUPS_PER_PASS`. Bitbucket's `state=`
4941
+ # filter returns only rows of that state, so only the open call holds
4942
+ # OPEN rows and only it can name any: the pass spends at most 5.
4943
+ _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
4944
  PR_LIST_BIND_FN=_bb_jen_bind
4606
4945
  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 |
4946
+ (.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
4947
  # 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`).
4948
+ # ANSWER THIS PASS — `$capped` (past the cap, never named this
4949
+ # pass) or `$broken` (named, but `jenkins_sha_runs` broke early
4950
+ # before reaching it). Distinct from Jenkins naming "unknown"
4951
+ # itself — own field rather than the same `checks` word
4952
+ # (`bitbucket-jenkins-a-pr-list-row`). A `$broken` row must not
4953
+ # stand on `$colour`: that colour may belong to a commit this
4954
+ # PR no longer carries, the same reason `$capped` already
4955
+ # refuses it — only the reason differs between `$capped` and
4956
+ # `$broken`.
4612
4957
  {
4613
4958
  number:.id, title:.title,
4614
4959
  state:(if .state=="DECLINED" then "CLOSED" else .state end),
@@ -4625,13 +4970,13 @@ case "$op" in
4625
4970
  updatedAt:(.updated_on // ""),headSha:(.source.commit.hash // ""),mergedAt:(if .state=="MERGED" then (.updated_on // "") else "" end),checksSha:($jentry.checksSha // ""),
4626
4971
  author:(.author.nickname // ""),
4627
4972
  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 $?
4973
+ } + (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
4974
  PR_LIST_BIND_FN=""
4630
4975
  else
4631
4976
  # Bitbucket without Jenkins: checks remain unknown
4632
4977
  pr_list_states bitbucket "$limit" "$bb_states" \
4633
4978
  '.[] | {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 $?
4979
+ "${bb_cmd[@]}" | bb_fold_mergeable_stream "$repo_slug" || exit $?
4635
4980
  fi
4636
4981
  else
4637
4982
  pr_list_states bitbucket "$limit" "$bb_states" \
@@ -4667,8 +5012,7 @@ case "$op" in
4667
5012
  # for a repository whose CI is not GitHub Actions. `CI` and `Git host` are
4668
5013
  # independent `## Plot Config` keys, and this is the op that reads the
4669
5014
  # first of them.
4670
- branch="${1:?runs needs a branch}"; shift
4671
- limit=10
5015
+ branch="${1:?runs needs a branch}"; shift; limit=10
4672
5016
  while [ $# -gt 0 ]; do
4673
5017
  case "$1" in
4674
5018
  --limit) limit="${2:?}"; shift 2 ;;
@@ -4844,7 +5188,10 @@ case "$op" in
4844
5188
  # ONE MORE CALL, ONLY FOR A CONCLUDED FAILURE (#1295): `gh run view --json
4845
5189
  # jobs` is the only place a 0-step job (no runner ever picked up the run)
4846
5190
  # shows up, apart from a real failure. A run still going or that
4847
- # succeeded costs no extra call.
5191
+ # succeeded costs no extra call. A second consumer reads the same `jobs`
5192
+ # field since 2026-10-20: `checks-verdict.ts`'s `runWasNotAcquired` and its
5193
+ # cancellation-fingerprint logic tell a genuine timeout from a near-instant
5194
+ # supersession by reading these same per-job step conclusions.
4848
5195
  _gh_db_id=$(printf '%s' "$_gh_match" | jq -r 'if (.conclusion == "failure" or .conclusion == "cancelled") then .databaseId else "" end')
4849
5196
  _gh_match=$(printf '%s' "$_gh_match" | jq -c 'del(.databaseId)') || exit 4
4850
5197
  [ -z "$_gh_db_id" ] && { printf '%s' "$_gh_match"; exit 0; }
@@ -4866,11 +5213,11 @@ case "$op" in
4866
5213
  # of them reproduces `an-outage-is-not-an-answer` — a board that says "no
4867
5214
  # issues" because it could not reach the tracker is stating a fact it does
4868
5215
  # not have.
4869
- limit=""; state="open"; since=""; page_token=""; paged=""; label=""; fix_version=""; title_has=""
5216
+ limit=""; state="open"; since=""; page_token=""; paged=""; label=""; fix_version=""; title_has=""; state_explicit=""
4870
5217
  while [ $# -gt 0 ]; do
4871
5218
  case "$1" in
4872
5219
  --limit) limit="${2:?}"; shift 2 ;;
4873
- --state) state="${2:?}"; shift 2 ;;
5220
+ --state) state="${2:?}"; state_explicit="$state"; shift 2 ;;
4874
5221
  --since) since="${2:?}"; shift 2 ;;
4875
5222
  --page-token) page_token="${2:?}"; shift 2 ;;
4876
5223
  --paged) paged=1; shift ;;
@@ -4880,6 +5227,18 @@ case "$op" in
4880
5227
  *) die "issue-list: unknown arg $1" ;;
4881
5228
  esac
4882
5229
  done
5230
+ # THIS ARM'S OWN USAGE CONTRACT EXITS 2, never `die`'s plain 1: both the
5231
+ # `--fix-version`/`--state` conflict below and the above-one-page `--limit`
5232
+ # guard further down are usage errors `issue-list` catches on itself rather
5233
+ # than a generic argument mistake, so a caller can tell the two apart.
5234
+ usage_refused() { echo "plot-host: issue-list: $*" >&2; exit 2; }
5235
+ # `--fix-version` AND AN EXPLICIT `--state` ARE NOT INDEPENDENTLY MEANINGFUL
5236
+ # (`--state version` alone has nowhere to get a name from), so one of two
5237
+ # flags silently winning would hide the other. Refused regardless of
5238
+ # argument order: the loop above always leaves `state=version` once
5239
+ # `--fix-version` is seen, so order itself cannot distinguish the two
5240
+ # un-refused outcomes a naive fix could produce.
5241
+ [ -z "$fix_version" ] || [ -z "$state_explicit" ] || [ "$state_explicit" = version ] || usage_refused "--fix-version and --state $state_explicit conflict; drop one"
4883
5242
  # `--since` is spliced into a JQL string and a search qualifier, so its shape
4884
5243
  # is checked here: a value outside it is a usage error, never a query.
4885
5244
  [[ "$state" =~ ^(open|closed|inbox|changed|version)$ ]] || die "issue-list: --state is open, closed, inbox, changed or version, not '$state'"
@@ -4934,7 +5293,25 @@ case "$op" in
4934
5293
  # THE CLOSED, CHANGED AND VERSION READS REQUIRE `Ticket prefixes`: an
4935
5294
  # unscoped `resolved >=`, `updated >=` or `fixVersion =` query reads every
4936
5295
  # 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
5296
+ [ -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; }
5297
+ # THE EXISTENCE CHECK RUNS ONCE PER QUESTION, NOT ONCE PER PAGE: `walk`
5298
+ # (tracker-shell.ts) calls this script once per page of a multi-page
5299
+ # `--fix-version` read, each call carrying `--page-token` from the second
5300
+ # page on. Re-running the check on every one of those re-asks Jira
5301
+ # `version-list` per `Ticket prefixes` project for a question already
5302
+ # answered on page one — 6 extra calls for a 3-page/2-project read,
5303
+ # measured 2026-10-21 (issue #2259). Gating on an absent `$page_token`
5304
+ # keeps `versionRead`'s `pages: issues.value.pages + projects.length`
5305
+ # (tracker-jira.ts) correct: one existence call per project, however many
5306
+ # pages the read takes. A malformed version-list body exits 3 like
5307
+ # `version-list`'s own parse failure does — "cannot parse" and "parsed,
5308
+ # found nothing" are different outcomes, and only the second is
5309
+ # version-not-found. `jq -e` ON A BOOLEAN RESULT IS THE THREE-WAY SWITCH:
5310
+ # exit 0 is a match (`found=1`), exit 1 is a clean no-match (the loop
5311
+ # moves on), and anything else is a parse failure jq itself could not
5312
+ # complete — `[ $? = 1 ]` is the one case that is NOT that failure, so
5313
+ # the `||` chain only reaches `exit 3` when the code is neither.
5314
+ 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
5315
  # A VERSION READ EXISTS BEFORE IT IS SEARCHED: `fixVersion = "<name>"` alone
4939
5316
  # matches nothing for a name Jira has never heard of and still exits 0 with
4940
5317
  # no rows (measured 2026-10-21) — the exact silent empty answer this guard
@@ -4999,7 +5376,17 @@ case "$op" in
4999
5376
  # refuses. `-gt`, not `-ge`: a full single page (100) is still one page
5000
5377
  # and must still answer. A non-numeric `--limit` skips this guard and
5001
5378
  # 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
5379
+ # BOUNDED BEFORE `-gt` EVER RUNS: `[0-9]+` matches a value like
5380
+ # `99999999999999999999` too, and bash's `-gt` only holds signed 64-bit
5381
+ # integers — past that it prints "integer expected" to stderr and the
5382
+ # whole `&&` chain reads as false, so the oversized value reached Jira's
5383
+ # `maxResults` unbounded (measured by hand). A run of 16+ digits is
5384
+ # outside that range regardless of value, so it refuses on digit count
5385
+ # alone, never reaching a comparison `-gt` cannot make; 1-15 digits is
5386
+ # always representable and falls through to the ordinary `-gt` check.
5387
+ if [ -n "$paged" ]; then max="${limit:-$ISSUE_PAGE_ROWS}"; [ "$max" -le "$ISSUE_PAGE_ROWS" ] || max="$ISSUE_PAGE_ROWS"
5388
+ 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"
5389
+ fi
5003
5390
  token_args=(); [ -z "$page_token" ] || token_args=(--data-urlencode "nextPageToken=$page_token")
5004
5391
  # jq builds the query string so a JQL with spaces/quotes is encoded once,
5005
5392
  # not hand-escaped. --data-urlencode via curl -G keeps the token out of the
@@ -5084,15 +5471,16 @@ case "$op" in
5084
5471
  if out="$(gh issue list --state "$ask_state" ${limit_args[@]+"${limit_args[@]}"} \
5085
5472
  ${search_args[@]+"${search_args[@]}"} --json "$gh_json" 2>"$HOST_ERR")"; then
5086
5473
  rm -f "$HOST_ERR"
5474
+ # `gh` pages inside ONE process and the wrapper records one call per
5475
+ # process, so each page past the first is recorded here. Run before the jq
5476
+ # print below so that print's exit status is the branch's, not this call's.
5477
+ budget_record_call github github graphql "$(node "$here/board/plot-listing-pages.mjs" <<<"$out" 2>/dev/null)"
5087
5478
  jq -c --arg status "$gh_state" \
5088
5479
  '.[] | ((.state // $status) | ascii_downcase) as $actual |
5089
5480
  {number:.number,title:.title,url:(.url // ""),createdAt:(.createdAt // ""),
5090
5481
  status:$actual,statusCategory:(if $actual == "open" then "To Do" else "Done" end),assignees:[.assignees[]?.login]}
5091
5482
  + (if .updatedAt then {updatedAt:.updatedAt} else {} end) + (if .issueType.name? then {type:.issueType.name} else {} end)
5092
5483
  + (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
5484
  else
5097
5485
  # NO empty-list fallback. `host_miss_or_fail` exists for a lookup whose
5098
5486
  # subject is absent — one PR that does not exist. A LIST has no absent
@@ -5130,8 +5518,7 @@ case "$op" in
5130
5518
  count=0
5131
5519
  while IFS= read -r line; do
5132
5520
  [[ "$line" =~ ^#0*([0-9]+)[[:space:]]+(.*)$ ]] || continue
5133
- num="${BASH_REMATCH[1]}"
5134
- rest="${BASH_REMATCH[2]}"
5521
+ num="${BASH_REMATCH[1]}"; rest="${BASH_REMATCH[2]}"
5135
5522
  # Lift the leading state badge word (NEW/OPEN/RESOLVED/…), then strip
5136
5523
  # it and its padding; the title starts after it. The badge was parsed
5137
5524
  # here before and THROWN AWAY to recover the title — it is captured
@@ -5140,8 +5527,7 @@ case "$op" in
5140
5527
  # that drifts from the one that strips.
5141
5528
  state=""
5142
5529
  if [[ "$rest" =~ ^(NEW|OPEN|ON\ HOLD|INVALID|RESOLVED|DUPLICATE|WONTFIX|CLOSED)[[:space:]]+(.*)$ ]]; then
5143
- state="${BASH_REMATCH[1]}"
5144
- rest="${BASH_REMATCH[2]}"
5530
+ state="${BASH_REMATCH[1]}"; rest="${BASH_REMATCH[2]}"
5145
5531
  fi
5146
5532
  # Map the badge onto the three-value category the board groups on.
5147
5533
  # NEW/OPEN are unstarted; RESOLVED/CLOSED are finished. The rest —
@@ -5195,16 +5581,15 @@ case "$op" in
5195
5581
  # the board. jira_check turns that 404 into exit 3 with empty stdout.
5196
5582
  jira_require_config
5197
5583
  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.
5584
+ -G --data-urlencode "fields=summary,description,status,resolution")" || exit $?
5585
+ # `state`: closed when `statusCategory.key` is `done` (`name` is localised)
5586
+ # or a resolution is set; absent is open.
5202
5587
  printf '%s' "$body_json" | jq -c --arg base "$(tracker_base_url)" '{
5203
5588
  number: .key,
5204
5589
  title: (.fields.summary // ""),
5205
5590
  body: (.fields.description // ""),
5206
5591
  url: ($base + "/browse/" + .key),
5207
- state: (if .fields.status.statusCategory.name == "Done" then "closed" else "open" end)
5592
+ state: (if .fields.status.statusCategory.key == "done" or .fields.resolution != null then "closed" else "open" end)
5208
5593
  }'
5209
5594
  elif [ "$be" = "github" ]; then
5210
5595
  if out="$(gh issue view "$num" --json number,title,body,url,state 2>"$HOST_ERR")"; then
@@ -5246,11 +5631,10 @@ case "$op" in
5246
5631
  url="$(grep -oE 'https?://[^[:space:]]+' <<<"$(grep -F 'View this issue on Bitbucket' <<<"$raw")" | head -1)"
5247
5632
  # Line 2 is `<STATE> • <reporter> opened <createdOn>` — the same badge
5248
5633
  # 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
5634
+ # discarded. The five finished words close it; ON HOLD, NEW, OPEN and any
5635
+ # state this vocabulary has no word for stay open, as issue-list leaves them.
5636
+ bb_state="$(sed -n '2p' <<<"$raw" | sed -E 's/^[[:space:]]*([A-Z ]+)[[:space:]]*•.*$/\1/; s/[[:space:]]+$//')"
5637
+ case "$bb_state" in RESOLVED|CLOSED|INVALID|DUPLICATE|WONTFIX) state=closed ;; *) state=open ;; esac
5254
5638
  # Body is the block between the metadata head and the footer. The head is
5255
5639
  # the title + the two fixed meta lines (state, Type:) plus an optional
5256
5640
  # Component/Milestone/Version line; the tail is the footer. This is the
@@ -5295,8 +5679,10 @@ case "$op" in
5295
5679
  #
5296
5680
  # IDEMPOTENT BY NATURE. The same status written twice is the same status,
5297
5681
  # 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.
5682
+ # naming no such transition. A no-match also covers the other case — the
5683
+ # status exists but the workflow has no transition to it from here — so the
5684
+ # no-match line carries the facts that tell the two apart, and the
5685
+ # connector (`tracker-jira.ts`) tells them apart.
5300
5686
  key="${1:?issue-status needs an issue key}"; want="${2:?issue-status needs a status}"
5301
5687
  [ "$(tracker_scheme)" = "jira" ] || exit 4
5302
5688
  jira_require_config
@@ -5304,17 +5690,21 @@ case "$op" in
5304
5690
  # workflow and per issue: the id for "In Progress" differs between projects
5305
5691
  # and the transition may not be available from the issue's current state at
5306
5692
  # all. A hardcoded id writes a status to the wrong column silently.
5307
- body_json="$(jira_ask "/rest/api/2/issue/$key/transitions")" || exit $?
5693
+ # ONE READ, TWO FACTS. The issue read with `expand=transitions` answers the
5694
+ # same transitions as `/transitions` and the current status beside them, so
5695
+ # a no-match costs no second call.
5696
+ body_json="$(jira_ask "/rest/api/2/issue/$key?fields=status&expand=transitions")" || exit $?
5308
5697
  tid="$(printf '%s' "$body_json" | jq -r --arg want "$want" \
5309
5698
  '[.transitions[]? | select((.name // "" | ascii_downcase) == ($want | ascii_downcase)
5310
5699
  or ((.to.name // "" | ascii_downcase) == ($want | ascii_downcase)))]
5311
5700
  | .[0].id // ""')"
5312
5701
  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'
5702
+ # NO MATCH IS NOT YET AN ANSWER. It covers two different facts — the
5703
+ # issue already holds the status (harmless), or the status exists but no
5704
+ # transition from here reaches it (the tracker is behind). The current
5705
+ # status and the offered transitions are printed as read; an absent
5706
+ # status prints as an empty field, which the connector reads as a failure.
5707
+ printf '%s' "$body_json" | jq -r '"no-match\t\(.fields.status.name // "")\t\([.transitions[]?.name] | join(", "))"'
5318
5708
  exit 0
5319
5709
  fi
5320
5710
  jira_ask "/rest/api/2/issue/$key/transitions" \
@@ -5345,7 +5735,7 @@ case "$op" in
5345
5735
  issue-label|issue-comment|issue-close)
5346
5736
  # THE PLAN-STATE WRITES, and one-way: Plot sets a `plan:*` label, keeps one
5347
5737
  # 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
5738
+ # 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
5739
  # issue-comment <n> <marker> <body> edits the comment holding <marker>, else posts; an empty <marker> always posts
5350
5740
  # issue-close <n>
5351
5741
  # GitHub issues only, dispatched on `issue_source` like issue-open. Exit 4,
@@ -5353,12 +5743,12 @@ case "$op" in
5353
5743
  num="${1:?$op needs an issue number}"; source_said="$(issue_source)" || exit 1
5354
5744
  [ "$be" = github ] && { [ "$source_said" = git-host ] || [ "$source_said" = $'tracker\tgithub-issues' ]; } || { echo "plot-host: $op: ${source_said#*$'\t'}" >&2; exit 4; }
5355
5745
  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 ;;
5746
+ 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
5747
  issue-close) gh issue close "$num" >/dev/null 2>"$HOST_ERR" || gh_fail ;;
5358
5748
  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 ;;
5749
+ cid=""; [ -z "${2-}" ] || cid="$(gh_marker_comment_id "$num" "$2")" || gh_fail
5750
+ if [ -n "$cid" ]; then gh api -X PATCH "repos/{owner}/{repo}/issues/comments/$cid" -f body="${3-}" >/dev/null 2>"$HOST_ERR"
5751
+ else gh issue comment "$num" --body "${3-}" >/dev/null 2>"$HOST_ERR"; fi || gh_fail ;;
5362
5752
  esac
5363
5753
  rm -f "$HOST_ERR" ;;
5364
5754
 
@@ -5373,8 +5763,7 @@ case "$op" in
5373
5763
  printf '%s' "$body" | jq -c '.[] | {name, released: (.released // false), releaseDate: (.releaseDate // null)}' || exit 3 ;;
5374
5764
 
5375
5765
  pr-body)
5376
- num="${1:?pr-body needs a PR number}"; shift
5377
- body=""
5766
+ num="${1:?pr-body needs a PR number}"; shift; body=""
5378
5767
  while [ $# -gt 0 ]; do
5379
5768
  case "$1" in
5380
5769
  --body) body="${2:?}"; shift 2 ;;
@@ -5424,7 +5813,7 @@ case "$op" in
5424
5813
  }
5425
5814
  }' <<<"$out"
5426
5815
  else
5427
- err="$(cat "$HOST_ERR" 2>/dev/null)"; rm -f "$HOST_ERR"
5816
+ host_err
5428
5817
  # The host could not be asked. Report unknown rather than failing outright,
5429
5818
  # because this is informational — a caller that cannot read the budget
5430
5819
  # should proceed with the default path, not error out.
@@ -5664,8 +6053,8 @@ case "$op" in
5664
6053
  # the signed-in CLI identity, so it needs no App credentials and no Node
5665
6054
  # helper.
5666
6055
  [ "$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" ;;
6056
+ [ -z "${3-}" ] || cid="$(gh_marker_comment_id "$num" "$3")" || gh_fail
6057
+ 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
6058
 
5670
6059
  *)
5671
6060
  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)"