@plot-pm/board 0.21.0 → 0.22.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
@@ -33,9 +33,26 @@
33
33
  # for free. Never prints `unknown`.
34
34
  # pr-state <number|branch> [--repo <owner/repo>] one JSON object:
35
35
  # {"number":N,"state":"OPEN|MERGED|CLOSED|NONE",
36
- # "draft":true|false,"url":"..."}
36
+ # "draft":true|false,"url":"...",
37
+ # "mergeable":"mergeable|conflicting|unknown"}
38
+ # Bitbucket Cloud's REST API has no field or
39
+ # endpoint that reports merge-conflict status
40
+ # for a pull request (measured 2026-10-20), so
41
+ # `mergeable` there comes from a local
42
+ # `git merge-tree --write-tree <base> <head>`
43
+ # read instead — the host stays unasked. A
44
+ # missing head/base, a failed fetch, or git
45
+ # older than 2.38 reads "unknown" with a
46
+ # `mergeableReason`, never "conflicting".
37
47
  # NONE = no PR found (exit 0 — callers branch on
38
48
  # state, not exit codes)
49
+ # ON BITBUCKET, a branch name asks the host
50
+ # PER BRANCH (`bb_branch_query`'s `q=` filter),
51
+ # never a repository-wide page — a PR merged
52
+ # 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.
39
56
  # pr-merged <branch> has ANY PR for this branch merged? prints one
40
57
  # word: merged|not-merged|unknown
41
58
  # READS `mergedAt`, NEVER `state`: a merged PR
@@ -74,18 +91,25 @@
74
91
  # empty answer sends the reaper to a weaker
75
92
  # reading, so only a recognised lookup miss is
76
93
  # empty.
94
+ # pr-merge-dest <branch> one tab-separated line `number\tbase\tsha\tmergedAt`
95
+ # per merged PR with this head branch, or EMPTY
96
+ # (exit 0) where none merged. The same query
97
+ # `pr-merge-commit` runs. EXIT 3 is the question
98
+ # failing.
77
99
  # pr-review <number> one JSON line `{"sha","state","bypass"}`: the PR's
78
100
  # head sha, the newest `plot/review` status on it
79
101
  # (`success|failure|pending|error`, or `absent`),
80
102
  # and whether a comment starts `review-bypass:`.
81
- # Bitbucket EXITS 4 (unaskable). EXIT 3 is the
103
+ # Bitbucket reads the same words from the
104
+ # `plot/review` commit status (SUCCESSFUL,
105
+ # FAILED, INPROGRESS, STOPPED). EXIT 3 is the
82
106
  # question failing.
83
107
  # pr-create --title T [--body B] [--base BR] [--head BR] [--draft]
84
108
  # create a PR, print its URL
85
109
  # pr-merge <number> [--squash] [--delete-branch] --match-head <sha>
86
- # github: --match-head is mandatory, refused
87
- # with no pin. bitbucket: cannot pin, refused
88
- # (exit 4) when one is given.
110
+ # mandatory on every backend. bitbucket
111
+ # re-reads the head before merging; a
112
+ # mismatch refuses `head-moved` (exit 1).
89
113
  # pr-ready <number> take a PR out of draft
90
114
  # merge the PR
91
115
  # pr-list [--state open|merged|closed|all] [--limit N] [--rich|--rich-open]
@@ -198,7 +222,11 @@
198
222
  # construct one (it is "" only if the host omits
199
223
  # it); `mergeable` is mergeable|conflicting|
200
224
  # unknown, and "unknown" is what a host that
201
- # cannot answer reports (absent is not false)
225
+ # cannot answer reports (absent is not false).
226
+ # Bitbucket Cloud's REST API has no field or
227
+ # endpoint that answers this at all (measured
228
+ # 2026-10-20), so `mergeable` is always
229
+ # "unknown" there.
202
230
  # --limit raises the host CLI's default page of
203
231
  # 30, which --state all exhausts immediately
204
232
  # THREE OUTCOMES, KEPT APART — the same rule
@@ -279,7 +307,20 @@
279
307
  # closed read and an open read given `--paged`
280
308
  # print that line, and on Jira ask 100 rows a
281
309
  # page; an open read without `--paged` prints
282
- # issue rows alone. EXIT 4 where the closed read
310
+ # issue rows alone — ON STDOUT. On Jira, an
311
+ # unpaged open or inbox read whose page was cut
312
+ # prints one STDERR line instead:
313
+ # `plot-host: jira issue-list state=<s> possibly
314
+ # truncated (<n> rows, requested limit <L>)` —
315
+ # stdout is unchanged, so a reader taking every
316
+ # stdout line as an issue still can. EXIT 2 on Jira where an open
317
+ # or inbox read's `--limit` exceeds 100 without
318
+ # `--paged`: Jira caps `maxResults` at 100
319
+ # itself, so the unpaged read would otherwise
320
+ # return 100 rows with no sign the rest exist —
321
+ # a usage error naming `--paged`, checked before
322
+ # any curl. `--limit 100` still answers; the
323
+ # guard is `>`, not `>=`. EXIT 4 where the closed read
283
324
  # cannot be asked at all: Bitbucket (`bb issue
284
325
  # list` prints no closing date) and Jira with no
285
326
  # `Ticket prefixes`, both before any bb or curl.
@@ -340,9 +381,10 @@
340
381
  # the question FAILING (exit 3), never an empty
341
382
  # inbox — an auth gap must not read *you have no
342
383
  # tickets*, the failure this story is named for.
343
- # issue-view <number> ONE open issue as a single JSON object:
344
- # {"number":N,"title":"…","body":"…","url":"…"}
345
- # READ-ONLY — the second of the two issue reads.
384
+ # issue-view <number> ONE issue, any state, as a single JSON object:
385
+ # {"number":N,"title":"…","body":"…","url":"…",
386
+ # "state":"open|closed"}. READ-ONLY — the
387
+ # second of the two issue reads.
346
388
  # The board's *Create plan* action needs
347
389
  # the issue's BODY as the problem statement, and
348
390
  # issue-list deliberately omits it: the list is
@@ -369,6 +411,30 @@
369
411
  # as issue-list. Jira answers 404 for a missing
370
412
  # key, which is exit 3 here (the tracker moved),
371
413
  # never an empty body.
414
+ # issue-list --state version --fix-version <name> [--limit N] [--page-token T]
415
+ # (jira only; exit 4 elsewhere) the issues whose
416
+ # fixVersion is <name>, in the `Ticket prefixes`
417
+ # projects, one page of at most 100 with a last
418
+ # `{"nextPageToken":"…"}` line. Exit 4 with no
419
+ # `Ticket prefixes`: an unscoped fixVersion query
420
+ # reads every project on a shared instance. EXIT
421
+ # 4 ALSO for a <name> none of those projects'
422
+ # `version-list` has — `plot-host: version-not-
423
+ # found: <name>` on stderr, checked before any
424
+ # issue search is spent; a 404/5xx on that
425
+ # version-list check propagates its own exit
426
+ # code instead, never read as not-found.
427
+ # version-list <project> (jira only; exit 4 elsewhere) the versions of
428
+ # one project, one JSON line each:
429
+ # {"name":…,"released":bool,"releaseDate":…|null}.
430
+ # It decides nothing: whether a name is known is
431
+ # the Tracker adapter's answer. Exit 3 for any
432
+ # failed request, a 404 on the project included.
433
+ # issue-comment <number> <marker> <body> (github)
434
+ # edits the comment holding <marker>, else posts
435
+ # one; an empty <marker> always posts, not idempotent.
436
+ # issue-list --label <label> keeps open issues carrying the label (github
437
+ # only; exit 4 on Bitbucket and on Jira).
372
438
  # issue-open <request-json> (jira)
373
439
  # issue-open <title> <body> [--label <label>...] (github-issues)
374
440
  # THE SECOND OF TWO WRITES TO A TRACKER: open
@@ -530,6 +596,10 @@ ISSUE_PAGE_ROWS=100
530
596
  # that failed, as opposed to exit 4 (cannot be asked) or an answered empty list.
531
597
  # An empty message or a recognised lookup miss is an answer; anything else exits 3.
532
598
  miss_or_exit3() { [ -z "$1" ] || is_lookup_miss "$1" || { echo "plot-host: $1" >&2; exit 3; }; }
599
+ # `pr-merged`'s own third value for a failed call: a lookup miss still means
600
+ # not-merged, anything else prints the host's words and answers `unknown`
601
+ # rather than exiting — the caller already branches on this word, not a code.
602
+ miss_or_unknown() { if [ -z "$1" ] || is_lookup_miss "$1"; then echo "not-merged"; else echo "plot-host: $1" >&2; echo "unknown"; fi; }
533
603
  gh_fail() { echo "plot-host: $(cat "$HOST_ERR" 2>/dev/null)" >&2; rm -f "$HOST_ERR"; exit 3; }
534
604
 
535
605
  # Exit 3 — reserved for "the op itself cannot proceed", distinct from `die`'s
@@ -548,6 +618,14 @@ CHECKS_OF='def ck: (.conclusion // "") as $k | (.status // "") as $s | (if $s !=
548
618
  def checks_of: if (.statusCheckRollup|length) == 0 then "none" elif any(.statusCheckRollup[]; ck == "bad") then "failing"
549
619
  elif any(.statusCheckRollup[]; ck == "wait") then "pending" else "green" end;'
550
620
 
621
+ # THE ONE FOLD of a PR's mergeability into a word, for `pr-list --rich` and both
622
+ # `pr-state` transports. GraphQL says `mergeable` CONFLICTING|MERGEABLE|UNKNOWN
623
+ # and `mergeStateStatus` DIRTY; REST's single-PR payload says `mergeable`
624
+ # true|false|null and `mergeable_state` dirty. REST's list payload carries
625
+ # neither, so a `pr-state` asked by branch over REST reads `unknown`.
626
+ MERGEABLE_OF='def mergeable_of: if .mergeable == "CONFLICTING" or .mergeable == false or .mergeStateStatus == "DIRTY" or .mergeable_state == "dirty" then "conflicting"
627
+ elif .mergeable == "MERGEABLE" or .mergeable == true then "mergeable" else "unknown" end;'
628
+
551
629
  # Exit 5 — the host refused to answer FOR NOW. A rate limit, primary or
552
630
  # secondary: nothing is broken, nothing needs fixing, and the same question
553
631
  # asked later will be answered.
@@ -814,9 +892,18 @@ PR_LIST_PARTIAL_RC=7
814
892
  # TWO VARIADIC LISTS, ONE `"$@"`. The host command and the jq arguments are
815
893
  # both open-ended, and bash has one positional array — so the jq side travels
816
894
  # in this global, set by the caller immediately before the call. It is read
817
- # once per state and never written here.
895
+ # once per state and never written here, UNLESS `PR_LIST_BIND_FN` names a
896
+ # function that recomputes it — see below.
818
897
  PR_LIST_JQ_ARGS=()
819
898
 
899
+ # The name of a function to call with this state's raw rows ($1) right before
900
+ # they are piped through `jq_prog`, or empty to skip it (every existing
901
+ # caller's behaviour). Runs INSIDE the one per-state loop below rather than a
902
+ # second walk, because the Jenkins sha-bind needs each state's own rows and
903
+ # `pr_list_states` is the one place that holds them before they are consumed.
904
+ # Set and cleared by the caller, same as `PR_LIST_JQ_ARGS`.
905
+ PR_LIST_BIND_FN=""
906
+
820
907
  # --- the per-branch sweep (#333) --------------------------------------------
821
908
  #
822
909
  # THE JOIN ASKS ABOUT BRANCHES AND THE LIST ANSWERS ABOUT A REPOSITORY, and the
@@ -972,6 +1059,13 @@ bb_branch_query() { # $1=branch $2=adapter state; rest=global bb args → values
972
1059
  printf '%s' "$_out" | jq -c '.values // []'
973
1060
  }
974
1061
 
1062
+ # A FULL `bb_branch_query` PAGE WITH NO MATCHING ROW CANNOT PROVE ABSENCE.
1063
+ # $1=the JSON array, $2=a jq `any(.[]; …)` predicate naming the field that
1064
+ # would carry the answer. True only at the 50-row ceiling with the predicate
1065
+ # finding nothing — the one condition `pr-merged`, `pr-merge-commit` and
1066
+ # `pr-merged-heads` each guard against before reading silence as a negative.
1067
+ bb_full_page_lacks() { [ "$(jq 'length' <<<"$1")" -ge 50 ] && ! jq -e "$2" >/dev/null 2>&1 <<<"$1"; }
1068
+
975
1069
  # Ask about EVERY tracked branch in one state, printing one combined array.
976
1070
  #
977
1071
  # THE SHAPE `pr_list_states` ALREADY EXPECTS. It calls its host command once
@@ -1161,7 +1255,13 @@ bb_window_listing() { # global bb args… --state <s> --json → one JSON array
1161
1255
  #
1162
1256
  # ONE PAGE, AS BEFORE. 50 is the endpoint's `pagelen` ceiling and the limit
1163
1257
  # `bb_paginate` applied, so a state holding more than 50 rows answers with its
1164
- # 50 most recent here too, and `pr_list_report_truncation` still says so.
1258
+ # 50 most recent here too, and `pr_list_report_truncation` still says so —
1259
+ # unless the envelope carries Bitbucket's own `page` marker and no `next`,
1260
+ # which it reads back from `BB_LIST_NEXT_FILE` (`pr_list_states` sets the
1261
+ # path; this runs in that call's own subshell, so a global here would never
1262
+ # reach the caller). `page` is what tells a real paginated envelope from a
1263
+ # `values`-only shape that never carries `next` at all regardless of total —
1264
+ # the latter proves nothing and must fall through to the version table.
1165
1265
  #
1166
1266
  # THE HOST'S FAILURE TEXT AND EXIT CODE LEAVE UNTOUCHED, as in
1167
1267
  # `bb_branch_query`: `pr_list_call` classifies once, so a `429` still reads as
@@ -1177,6 +1277,7 @@ bb_state_listing() { # global bb args… --state <s> --json → one JSON array
1177
1277
  done
1178
1278
  [ -n "$_st" ] || die "bb_state_listing: no --state"
1179
1279
  _out="$(bb ${_args[@]+"${_args[@]}"} api "/repositories/{ws}/{repo}/pullrequests?state=$(bb_query_state "$_st")&pagelen=$BB_LIST_PAGELEN")" || return $?
1280
+ [ -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"
1180
1281
  printf '%s' "$_out" | jq -c '.values // []'
1181
1282
  }
1182
1283
 
@@ -1262,15 +1363,19 @@ pr_sweep_report() { # $1=states answered $2=states asked
1262
1363
 
1263
1364
  pr_list_states() { # $1=backend $2=limit $3=states $4=jq-program; rest=the host command
1264
1365
  local backend="$1" limit="$2" states="$3" jq_prog="$4"; shift 4
1265
- local _s _raw _rc _err _tmp _ok=0 _failed=0 _first_rc=0 _failed_states=""
1366
+ local _s _raw _rc _err _tmp _ok=0 _failed=0 _first_rc=0 _failed_states="" BB_LIST_NEXT=""
1266
1367
  for _s in $states; do
1267
- plot_tmpfile _tmp "host-prlist-state-err-$_s" || return 3
1368
+ # `bb_state_listing` RUNS INSIDE THE SUBSTITUTION BELOW, its own subshell,
1369
+ # so a variable it sets cannot reach this one — the same trap `pr_list_call`
1370
+ # warns about for `die`. `BB_LIST_NEXT_FILE` is the channel out: a fresh,
1371
+ # already-empty temp path per state, read back once the substitution returns.
1372
+ plot_tmpfile _tmp "host-prlist-state-err-$_s" && plot_tmpfile BB_LIST_NEXT_FILE "host-prlist-next-$_s" || return 3
1268
1373
  # THE SUBSHELL'S CODE IS THE ONLY CHANNEL OUT, so it is captured rather
1269
1374
  # than propagated. `pr_list_failed` runs INSIDE the substitution and has
1270
1375
  # already composed its report and its repair line; that text is spooled
1271
1376
  # here only so the state's name can be added to it before it is passed on.
1272
1377
  _raw="$(pr_list_call "$@" --state "$_s" --json 2>"$_tmp")"; _rc=$?
1273
- _err="$(cat "$_tmp" 2>/dev/null)"; rm -f "$_tmp"
1378
+ BB_LIST_NEXT="$(cat "$BB_LIST_NEXT_FILE" 2>/dev/null)"; _err="$(cat "$_tmp" 2>/dev/null)"; rm -f "$BB_LIST_NEXT_FILE" "$_tmp"
1274
1379
  if [ "$_rc" -ne 0 ]; then
1275
1380
  # THE HOST'S OWN REPORT GOES FIRST AND IS NEVER PREFIXED. `pr_list_failed`
1276
1381
  # already composed the sentence that says WHY — a spent quota, a burst
@@ -1307,7 +1412,8 @@ pr_list_states() { # $1=backend $2=limit $3=states $4=jq-program; rest=the host
1307
1412
  # `PR_LIST_SINCE`; the GitHub arm carries its window as `--search`.
1308
1413
  [ -n "$PR_LIST_BRANCHES" ] || [ -n "$PR_LIST_SINCE" ] \
1309
1414
  || pr_list_report_truncation "$backend" "$limit" "$_s" \
1310
- "$(jq 'length' <<<"$_raw" 2>/dev/null || echo 0)"
1415
+ "$(jq 'length' <<<"$_raw" 2>/dev/null || echo 0)" "$BB_LIST_NEXT"
1416
+ [ -z "$PR_LIST_BIND_FN" ] || "$PR_LIST_BIND_FN" "$_raw"
1311
1417
  printf '%s' "$_raw" | jq -c ${PR_LIST_JQ_ARGS[@]+"${PR_LIST_JQ_ARGS[@]}"} "$jq_prog"
1312
1418
  done
1313
1419
  pr_sweep_report "$_ok" "$((_ok + _failed))"
@@ -1445,6 +1551,15 @@ ci_scheme() {
1445
1551
  # deliberately NOT `failed`, which claims the host did not answer.
1446
1552
  jenkins_build_map() {
1447
1553
  local instance="$1"
1554
+ # A Jenkins colour as a PR row's `checks` word, shared by both shapes of job.
1555
+ # Local, so the function lifts out of this file alone.
1556
+ local JEN_COLOUR_JQ='def color_to_checks:
1557
+ if . == null or . == "" then "none"
1558
+ elif endswith("_anime") then "pending"
1559
+ elif . == "blue" then "green"
1560
+ elif . == "red" or . == "yellow" then "failing"
1561
+ else "none"
1562
+ end; '
1448
1563
  local slug job
1449
1564
  slug="${instance%%/*}"
1450
1565
  if [ -n "${PLOT_JENKINS_JOB:-}" ]; then
@@ -1469,12 +1584,8 @@ jenkins_build_map() {
1469
1584
  # failure-shaped (cannot verify), never to ok — the probe's `classify` rule.
1470
1585
  local auth_out=""
1471
1586
  auth_out=$(jen -I "$slug" auth status 2>&1) || true
1472
- if printf '%s' "$auth_out" | grep -qiE 'jenkins auth:[[:space:]]*not reachable'; then
1473
- printf '{"status":"failed","map":{}}\n'; return 0
1474
- fi
1475
- if ! printf '%s' "$auth_out" | grep -qiE 'jenkins auth:[[:space:]]*(ok|reachable)'; then
1476
- printf '{"status":"unknown","map":{}}\n'; return 0
1477
- fi
1587
+ printf '%s' "$auth_out" | grep -qiE 'jenkins auth:[[:space:]]*not reachable' && { printf '{"status":"failed","map":{}}\n'; return 0; }
1588
+ printf '%s' "$auth_out" | grep -qiE 'jenkins auth:[[:space:]]*(ok|reachable)' || { printf '{"status":"unknown","map":{}}\n'; return 0; }
1478
1589
 
1479
1590
  # THE SHAPE, READ FROM THE CONFIGURED JOB ITSELF. `job view` returns that
1480
1591
  # job's own `_class` — never a child's — plus the `color` and `lastBuild` a
@@ -1503,14 +1614,7 @@ jenkins_build_map() {
1503
1614
  # find it — `runs` reads that key, and the op's caller asks by the name the
1504
1615
  # instance declares.
1505
1616
  *'.WorkflowJob')
1506
- printf '%s' "$view_out" | jq -c --arg job "$job" '
1507
- def color_to_checks:
1508
- if . == null or . == "" then "none"
1509
- elif endswith("_anime") then "pending"
1510
- elif . == "blue" then "green"
1511
- elif . == "red" or . == "yellow" then "failing"
1512
- else "none"
1513
- end;
1617
+ printf '%s' "$view_out" | jq -c --arg job "$job" "$JEN_COLOUR_JQ"'
1514
1618
  ($job | split("/") | last) as $name
1515
1619
  | { status: "ok",
1516
1620
  map: { ($name): { color: .color,
@@ -1540,9 +1644,7 @@ jenkins_build_map() {
1540
1644
  # One call, every branch — the spike's whole point (Done-when 5).
1541
1645
  local out=""
1542
1646
  out=$(jen -I "$slug" job list ${job:+"$job"} --json 2>&1) || true
1543
- if [ -z "$out" ] || ! printf '%s' "$out" | jq -e 'type=="array"' >/dev/null 2>&1; then
1544
- printf '{"status":"failed","map":{}}\n'; return 0
1545
- fi
1647
+ [ -n "$out" ] && printf '%s' "$out" | jq -e 'type=="array"' >/dev/null 2>&1 || { printf '{"status":"failed","map":{}}\n'; return 0; }
1546
1648
 
1547
1649
  # Transform to `branch → {color, checks, job}`, decoding percent-encoded names
1548
1650
  # (Done-when 6: `feature%2Ffoo` → `feature/foo`, else every slashed branch
@@ -1557,17 +1659,10 @@ jenkins_build_map() {
1557
1659
  # red | yellow → failing (yellow is UNSTABLE — tests failed; NOT green)
1558
1660
  # *_anime → pending (a build is running)
1559
1661
  # disabled | absent → none (no build to report — absent is not failed)
1560
- printf '%s' "$out" | jq -c --arg job "$job" '
1662
+ printf '%s' "$out" | jq -c --arg job "$job" "$JEN_COLOUR_JQ"'
1561
1663
  def urldecode:
1562
1664
  gsub("%(?<h>[0-9A-Fa-f]{2})";
1563
1665
  "\(.h | explode | reduce .[] as $c (0; . * 16 + (if $c >= 97 then $c - 87 elif $c >= 65 then $c - 55 else $c - 48 end)) | [.] | implode)");
1564
- def color_to_checks:
1565
- if . == null or . == "" then "none"
1566
- elif endswith("_anime") then "pending"
1567
- elif . == "blue" then "green"
1568
- elif . == "red" or . == "yellow" then "failing"
1569
- else "none"
1570
- end;
1571
1666
  # `job` NAMES the specific failing build for `failing_checks` — the whole
1572
1667
  # point of naming it is so a reader knows which Jenkins job to open. That is
1573
1668
  # the branch job, qualified by its container: `<container>/<branch>` (or the
@@ -1620,28 +1715,25 @@ jenkins_no_instance() {
1620
1715
  # estimate for. This draws it one step earlier, for a connector that does not
1621
1716
  # exist at all — and `resultOf` (`adapters/run-script.ts:211`) maps exit 4 onto
1622
1717
  # `unaskable`, which is the word the build port already answers with.
1623
- # The Jenkins REST credential, read from where `jen` already stores it.
1718
+ # The Jenkins REST credential: JENKINS_USER + JENKINS_API_TOKEN from the
1719
+ # environment, then `plot_env_file`, then the macOS keychain where `jen`
1720
+ # already stores it — the environment wins outright, same order and the same
1721
+ # both-or-neither rule as `jira_load_env_file`.
1624
1722
  #
1625
1723
  # NOT THE KEYCLOAK BEARER. `jen auth token` prints one and Jenkins answers it
1626
- # with an HTML login redirect — measured 2026-09-10, and it is the trap that
1627
- # made an earlier reading conclude the sha was unreachable. Jenkins' own API
1628
- # takes BASIC auth with a user and an API token, which `jen` keeps in the login
1629
- # keychain under service `jen`, accounts `jenkins-user:<host>` and
1630
- # `jenkins-token:<host>`.
1631
- #
1632
- # IT PRINTS `user:token` AND NOTHING ELSE, or nothing at all. The caller passes
1633
- # it straight to `curl -u`; no branch echoes it, and no failure path names it.
1634
- #
1635
- # EMPTY IS THE HONEST ANSWER on a machine with no `security` (Linux, CI), with
1636
- # no keychain entry, or with either half missing — a half credential is not a
1637
- # credential. The caller turns that into exit 4, which is *cannot be asked*.
1724
+ # with an HTML login redirect — measured 2026-09-10. Jenkins' own API takes
1725
+ # BASIC auth with a user and an API token.
1726
+ #
1727
+ # Prints `user:token` and nothing else, or nothing at all — never the value
1728
+ # on a failure path. Empty means no source held a full pair; the caller turns
1729
+ # that into exit 4, *cannot be asked*.
1638
1730
  jenkins_rest_credential() { # $1 = the bare host
1639
- command -v security >/dev/null 2>&1 || return 1
1640
- local u t
1641
- u=$(security find-generic-password -s jen -a "jenkins-user:$1" -w 2>/dev/null) || return 1
1731
+ local u="${JENKINS_USER:-}" t="${JENKINS_API_TOKEN:-}" src="the environment" found env_file
1732
+ [ -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")"; }
1733
+ [ -n "$u" ] && [ -n "$t" ] && { echo "plot-host: JENKINS_USER and JENKINS_API_TOKEN read from $src" >&2; printf '%s:%s' "$u" "$t"; return 0; }
1734
+ 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
1642
1735
  t=$(security find-generic-password -s jen -a "jenkins-token:$1" -w 2>/dev/null) || return 1
1643
- [ -n "$u" ] && [ -n "$t" ] || return 1
1644
- printf '%s:%s' "$u" "$t"
1736
+ [ -n "$u" ] && [ -n "$t" ] || return 1; printf '%s:%s' "$u" "$t"
1645
1737
  }
1646
1738
 
1647
1739
  # A job path as Jenkins' REST API spells it: every segment under `job/`.
@@ -1655,18 +1747,30 @@ jenkins_job_url_path() { # $1 = job path, $2 = branch or ""
1655
1747
  local IFS=/
1656
1748
  for seg in $1; do [ -n "$seg" ] && out="$out/job/$seg"; done
1657
1749
  unset IFS
1658
- if [ -n "${2:-}" ]; then
1659
- out="$out/job/$(printf '%s' "$2" | sed 's|/|%2F|g')"
1660
- fi
1750
+ [ -n "${2:-}" ] && out="$out/job/$(printf '%s' "$2" | sed 's|/|%2F|g')"
1661
1751
  printf '%s' "$out"
1662
1752
  }
1663
1753
 
1664
- # Every Jenkins build of one job that built ONE sha, as a JSON array (newest
1665
- # first), or exit 3 (no instance) / exit 4 (cannot be asked). Shared by
1666
- # `run-for-sha` and `runs-for-sha`, so the instance, the credential and the
1754
+ # The REST host for the Jenkins slug $1, read off `jen -I <slug> auth status`'s
1755
+ # `Instance:` line rather than reinvented here — `jen` already turns a slug
1756
+ # like `ewz` into `jenkins-ci-ewz.internal.quatico.dev` and keys its stored
1757
+ # credential by that resolved host, so a literal slug sent to `curl` or to
1758
+ # `jenkins_rest_credential` can only fail. Prints nothing (exit 1) when `jen`
1759
+ # is missing, unparseable, or the line is absent — the caller decides what an
1760
+ # unresolved host means, same contract as every other helper here.
1761
+ jenkins_resolve_host() {
1762
+ local line; line=$(jen -I "$1" auth status 2>&1 | grep -iE '^Instance:' | head -1) || true
1763
+ [ -n "$line" ] && sed -nE 's/.*\(https?:\/\/([^)\/]+).*/\1/p' <<<"$line" || return 1
1764
+ }
1765
+
1766
+ # Every Jenkins build of one job, as a JSON array (newest first), or exit 3
1767
+ # (no instance) / exit 4 (cannot be asked). Shared by `run-for-sha`,
1768
+ # `runs-for-sha` and `runs`, so the instance, the credential and the
1667
1769
  # multibranch-then-plain URL fallback are written once.
1668
1770
  #
1669
- # $1 = the op's name, $2 = branch, $3 = how many builds to list, $4 = the sha.
1771
+ # $1 = the op's name, $2 = branch, $3 = how many builds to list, $4 = the sha
1772
+ # to filter for, or "" for every build of the branch unfiltered (the shape
1773
+ # `runs` wants — branch-scoped history, not one sha's).
1670
1774
  # Run it in `$(...)` and read the exit code with `|| exit $?`: it exits rather
1671
1775
  # than returns, and a subshell's exit is the code the caller sees.
1672
1776
  #
@@ -1678,55 +1782,162 @@ jenkins_job_url_path() { # $1 = job path, $2 = branch or ""
1678
1782
  # A BRANCH IS A JOB SEGMENT ON A MULTIBRANCH JOB AND NOT ON A PLAIN ONE, and no
1679
1783
  # reading of the configured path says which this is. The multibranch URL is
1680
1784
  # tried first and the plain one is the fallback (measured 2026-09-11: asking
1681
- # the plain job for a branch segment answers 404). THE PLAIN JOB REPORTS ITS
1682
- # OWN BUILDS whatever branch was asked about; the `sha` says which it built.
1785
+ # the plain job for a branch segment answers 404). THE PLAIN JOB REPORTS EVERY
1786
+ # BRANCH'S BUILDS, so an unfiltered read of it keeps only the builds whose
1787
+ # recorded `lastBuiltRevision.branch` names the asked branch, and a build that
1788
+ # records no branch only when the asked branch is the job's own key (the last
1789
+ # path segment, as `jenkins_build_map` keys it). A multibranch container that
1790
+ # answers `jobs` and no `builds` has not indexed the branch: an empty history.
1683
1791
  #
1684
1792
  # NO CREDENTIAL IS *CANNOT BE ASKED*, never *no run*: the keychain is macOS-only
1685
1793
  # and a Linux agent legitimately has none. AN UNREACHABLE INSTANCE IS NOT AN
1686
1794
  # EMPTY HISTORY: a refused or redirected request answers HTML, which fails the
1687
1795
  # `builds` test.
1688
1796
  #
1689
- # ONLY THE ASKED-FOR SHA, never another build's. `result` is null while a build
1797
+ # A BRANCH THE MULTIBRANCH JOB NEVER INDEXED IS AN EMPTY HISTORY, NOT A
1798
+ # REFUSAL. Measured live on ewz-kus-portal: `develop` builds in a separate job
1799
+ # (`kus-portal/continuous-deploy`), so the branch segment 404s and the
1800
+ # multibranch root answers only `{"_class":"…WorkflowMultiBranchProject"}` —
1801
+ # `tree=builds[…]` strips `jobs`, so a `has("jobs")` test never matches and the
1802
+ # function exited 4 for a Jenkins that had, in fact, answered. The decision is
1803
+ # keyed on the ROOT's `_class` rather than on `jobs`: widening `tree=` to carry
1804
+ # `jobs` would make a root that merely LISTS children (not this branch's
1805
+ # absence) answer `{"builds":[]}` too. An HTML body or no answer at all still
1806
+ # fails every test here and stays exit 4.
1807
+ #
1808
+ # THE DEFAULT BRANCH CAN NAME ITS OWN JOB, read through `Default branch job` —
1809
+ # the same key-reading shape `jenkins_instance` uses. It applies only when
1810
+ # `$branch` is the repository's local `origin/HEAD`, never to every branch:
1811
+ # ewz's other branches still build on the multibranch job, and a map nobody
1812
+ # has asked for is out of scope (brief: "a map is a surface nobody has asked
1813
+ # for"). `PLOT_JENKINS_JOB` still overrides `$job` for every branch, same
1814
+ # precedence as today — it wins, because it already means "ignore the
1815
+ # instance's own job path" and a narrower override must not un-set a broader
1816
+ # one.
1817
+ #
1818
+ # WITH A SHA, ONLY THAT SHA'S BUILDS, never another's. `result` is null while a build
1690
1819
  # runs, Jenkins' own word for *in flight*, mapped to the `status`/`conclusion`
1691
1820
  # split the contract already uses so the shape does not fork per connector.
1692
1821
  jenkins_sha_runs() {
1693
- local op="$1" branch="$2" limit="$3" sha="$4" instance host job cred tree body try path
1822
+ local op="$1" branch="$2" limit="$3" sha="$4" instance slug host job cred tree body try path plain="" default_job root_path
1694
1823
  instance="$(jenkins_instance)"
1695
1824
  [ -n "$instance" ] || jenkins_no_instance
1696
- host="${instance%%/*}"
1697
- job="${instance#*/}"
1698
- [ "$job" = "$instance" ] && job=""
1699
- [ -n "${PLOT_JENKINS_JOB:-}" ] && job="$PLOT_JENKINS_JOB"
1700
- if [ -z "$job" ]; then
1701
- 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
1702
- exit 4
1703
- fi
1825
+ slug="${instance%%/*}"; job="${instance#*/}"; [ "$job" = "$instance" ] && job=""
1826
+ 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"
1827
+ [ -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; }
1828
+ # A dotted slug IS a host already, `jen`'s own passthrough rule — only a
1829
+ # bare slug (`ewz`) needs resolving to the host its credential is keyed by.
1830
+ 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
1704
1831
  cred="$(jenkins_rest_credential "$host")" || {
1705
1832
  echo "plot-host: $op — no Jenkins API credential for '$host'" >&2
1706
1833
  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
1707
1834
  exit 4
1708
1835
  }
1709
- tree="tree=builds%5Bnumber,result,building,timestamp,url,actions%5BlastBuiltRevision%5BSHA1%5D%5D%5D%7B0,$limit%7D"
1710
- body=""
1711
- for path in "$(jenkins_job_url_path "$job" "$branch")" "$(jenkins_job_url_path "$job" "")"; do
1836
+ tree="tree=builds%5Bnumber,result,building,timestamp,url,actions%5BlastBuiltRevision%5BSHA1,branch%5Bname%5D%5D%5D%5D%7B0,$limit%7D"
1837
+ body=""; root_path="$(jenkins_job_url_path "$job" "")"
1838
+ for path in "$(jenkins_job_url_path "$job" "$branch")" "$root_path"; do
1712
1839
  host_slot_take jenkins ''
1713
1840
  try=$(curl -sg --max-time 30 -u "$cred" "https://$host$path/api/json?$tree" 2>/dev/null) || true
1714
1841
  host_slot_give; budget_record_call jenkins ''
1715
1842
  if printf '%s' "$try" | jq -e 'has("builds")' >/dev/null 2>&1; then body="$try"; break; fi
1843
+ # ONLY AT THE ROOT: a multibranch container that answered its OWN `_class`
1844
+ # and no `builds` has not indexed this branch at all — an empty history,
1845
+ # not a refusal. Checking this on the BRANCH path too would be wrong: a
1846
+ # branch segment never carries a container's `_class`, so this arm would
1847
+ # never fire there anyway, but keying on "which path" rather than "which
1848
+ # body shape" keeps the empty-history reading from ever depending on what
1849
+ # a branch-level answer happens to contain.
1850
+ [ "$path" = "$root_path" ] && printf '%s' "$try" | jq -e '._class == "org.jenkinsci.plugins.workflow.multibranch.WorkflowMultiBranchProject"' >/dev/null 2>&1 && { body='{"builds":[]}'; break; }
1851
+ plain=1
1716
1852
  done
1717
1853
  cred=""
1718
1854
  if [ -z "$body" ]; then
1719
1855
  echo "plot-host: $op — Jenkins did not answer for '$host'" >&2
1720
1856
  exit 4
1721
1857
  fi
1722
- printf '%s' "$body" | jq -c --arg sha "$sha" '
1858
+ 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;
1723
1859
  [ .builds[]
1724
- | { sha: ([ .actions[]? | select(.lastBuiltRevision) | .lastBuiltRevision.SHA1 ] | first // ""),
1860
+ | { shas: [ .actions[]? | select(.lastBuiltRevision) | .lastBuiltRevision.SHA1 ],
1861
+ br: [ .actions[]? | .lastBuiltRevision.branch[]?.name // empty | sub("^(refs/remotes/|refs/heads/)"; "") | sub("^origin/"; "") ],
1725
1862
  status: (if .building then "in_progress" else "completed" end),
1726
1863
  conclusion: (if .building then null else (.result // null) end),
1727
1864
  url: (.url // ""),
1728
- startedAt: (if .timestamp then (.timestamp / 1000 | todate) else "" end) } ]
1729
- | map(select(.sha == $sha))' || exit 4
1865
+ 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)
1866
+ | 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 .
1867
+ else map(select(if (.br | length) > 0 then any(.br[]; . == $branch) else $branch == ($job | split("/") | last) end)) end
1868
+ | map(.sha = (if $sha != "" then headsha(if $plain == "" then $branch else ($job | split("/") | last) end) else headsha($branch) end) | del(.shas, .br))' || exit 4
1869
+ }
1870
+
1871
+ # The sha-bound readings of the PR rows $3 whose branch colour in $2 cannot
1872
+ # settle the head: a JSON object keyed by branch, or nothing where no lookup
1873
+ # was needed. $1 = the op's name, $4 = optional path to also receive the
1874
+ # branches `rowsToBind` named this pass (one per line), so a caller can tell
1875
+ # "named but the ask broke early" (the colour must still stand, per "absent is
1876
+ # not false") from "never named because the row is past the cap" (the colour
1877
+ # must not stand) without a second, duplicate run of the same `rows` verb.
1878
+ # $5 = optional JSON object, branch -> the checksSha the caller's PR index
1879
+ # already has on record; a branch bound there to its CURRENT head costs the
1880
+ # pass nothing to re-confirm, so `rowsToBind` (rotation) spends the cap's
1881
+ # lookups on branches that are absent or stale there first. Absent entirely
1882
+ # where the caller holds no index — every row then sorts exactly as before.
1883
+ # `jenkins_sha_runs` reads each named row by sha, the bundle binds them. A
1884
+ # lookup that cannot ask Jenkins ends the pass, and the colour stands.
1885
+ jenkins_bind_rows() {
1886
+ 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)"
1887
+ : >"${4:-/dev/null}"; [ -z "$_named" ] && return; cut -f1 <<<"$_named" >"${4:-/dev/null}"
1888
+ printf '%s\n' "$_named" | while IFS=$'\t' read -r _b _s _j; do
1889
+ _r=$(jenkins_sha_runs "$1" "$_b" 20 "$_s" </dev/null) || break; printf '%s\t%s\t%s\t%s\n' "$_b" "$_s" "$_j" "$_r"
1890
+ done | node "$here/board/plot-jenkins-pr-checks.mjs" bind 2>/dev/null
1891
+ }
1892
+
1893
+ # Overlays the `mergeable` reading on a Bitbucket `pr-state`/`pr-list` row ($1,
1894
+ # carrying `state`, `headSha` and `base`) from a local `git merge-tree
1895
+ # --write-tree` check; Bitbucket Cloud's REST API has no conflict field (see
1896
+ # `bitbucket-pr-reading.ts`). The bundle folds the reading into an OPEN row and
1897
+ # returns every other row unchanged, so git runs for OPEN rows only.
1898
+ #
1899
+ # The base is fetched ALONE, once per distinct base per invocation
1900
+ # (`BB_FETCHED`), and a failed fetch reads `unknown`: a fetch that names the
1901
+ # head too fails whole on Bitbucket's short hash, and the stale `origin/<base>`
1902
+ # it leaves behind answers wrongly with confidence (#2208). The head is never
1903
+ # fetched; a head commit absent from the clone reads `unknown` with its sha.
1904
+ # `git fetch` is a git read, not a host CLI call, so the host stays unasked.
1905
+ # A bundle that cannot answer prints the unchanged row.
1906
+ bb_fold_mergeable() {
1907
+ local row="$1" state head base fetch="" in_clone="" mt_code="" mt_err=""
1908
+ IFS=$'\x1f' read -r state head base < <(jq -r '[.state, (.headSha // ""), (.base // "")] | join("\u001f")' <<<"$row" 2>/dev/null)
1909
+ if [ "$state" = OPEN ] && [ -n "$head" ] && [ -n "$base" ]; then
1910
+ 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
1911
+ git cat-file -e "$head^{commit}" 2>/dev/null && in_clone=yes || in_clone=no
1912
+ [ "$fetch$in_clone" = okyes ] && { mt_err="$(git merge-tree --write-tree "origin/$base" "$head" 2>&1 >/dev/null)"; mt_code=$?; }
1913
+ fi
1914
+ 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"
1915
+ }
1916
+
1917
+ # `pr-list --rich`'s per-line fold. Each row carries a `base` key only for
1918
+ # `bb_fold_mergeable`, and this removes it again; an OPEN row whose reading is
1919
+ # `unknown` gains `mergeableReason`. The loop runs in one shell, so
1920
+ # `BB_FETCHED` holds across its rows.
1921
+ bb_fold_mergeable_stream() { local line; while IFS= read -r line; do [ -z "$line" ] || bb_fold_mergeable "$line"; done | jq -c 'del(.base)'; }
1922
+
1923
+ # Prints the `pr-state` row of the Bitbucket PR payload $1 (`null` for no PR).
1924
+ #
1925
+ # Without `CI: jenkins` the check is `unknown`, absent and not false, as in
1926
+ # `pr-list`'s plain Bitbucket arm. Under it the branch colour from
1927
+ # `jenkins_build_map` settles `none` and `pending`, and a head whose colour is
1928
+ # `green` or `failing` is read by sha through `jenkins_bind_rows`, because a
1929
+ # colour carries no commit. Jenkins unreachable or no instance reads `unknown`.
1930
+ # `headSha` is `source.commit.hash`, a short hash `jenkins_sha_runs` prefix-matches.
1931
+ # `mergeable` is `unknown` here; `pr-state` folds the real reading on top with
1932
+ # `bb_fold_mergeable`, and `pr-merge --match-head` reads only `headSha`.
1933
+ bb_state_row() {
1934
+ local colours=null bound=null inst
1935
+ if jq -e '.id' >/dev/null 2>&1 <<<"$1" && [ "$(ci_scheme)" = "jenkins" ]; then
1936
+ inst="$(jenkins_instance)"
1937
+ [ -z "$inst" ] || colours="$(jenkins_build_map "$inst" | jq -c 'if .status == "ok" then (.map // {}) else null end' 2>/dev/null)" || colours=null
1938
+ [ "$colours" = null ] || bound="$(jenkins_bind_rows pr-state "$colours" "$(jq -c '[{headRefName:.source.branch.name,headRefOid:.source.commit.hash}]' <<<"$1")")"
1939
+ fi
1940
+ printf '%s\n%s\n%s\n' "$(jq -c . <<<"$1")" "$colours" "${bound:-null}" | node "$here/board/plot-jenkins-pr-checks.mjs" state
1730
1941
  }
1731
1942
 
1732
1943
  ci_unaskable() { # $1 = the op's name, $2 = the CI word (may be empty)
@@ -2058,14 +2269,14 @@ gh_rest_repo() {
2058
2269
  }
2059
2270
 
2060
2271
  rest_pr_to_state() {
2061
- jq -c '
2272
+ jq -c "$MERGEABLE_OF"'
2062
2273
  (if (.merged == true) or (.merged_at != null) then "MERGED"
2063
2274
  else (.state // "" | ascii_upcase) end) as $state
2064
2275
  | { number: .number,
2065
2276
  state: $state,
2066
2277
  draft: (.draft // false),
2067
2278
  url: (.html_url // ""),
2068
- mergeCommit: (.merge_commit_sha // ""), headSha: (.head.sha // ""), base: (.base.ref // ""), checks: "unknown" }
2279
+ mergeCommit: (.merge_commit_sha // ""), headSha: (.head.sha // ""), base: (.base.ref // ""), checks: "unknown", mergeable: mergeable_of }
2069
2280
  '
2070
2281
  }
2071
2282
 
@@ -2153,11 +2364,7 @@ bb_strip_ansi() {
2153
2364
  # means. Reads the already-stripped, already-lowercased error text.
2154
2365
  bb_issue_exit_code() {
2155
2366
  local err="$1"
2156
- if LC_ALL=C grep -qiE 'are you sure this is a bitbucket repo|\b40[34]\b|not found|no issue tracker|issue tracker.*(disabled|not enabled)|repository not found' <<<"$err"; then
2157
- echo 4
2158
- else
2159
- echo 3
2160
- fi
2367
+ LC_ALL=C grep -qiE 'are you sure this is a bitbucket repo|\b40[34]\b|not found|no issue tracker|issue tracker.*(disabled|not enabled)|repository not found' <<<"$err" && echo 4 || echo 3
2161
2368
  }
2162
2369
 
2163
2370
  # Assert the format the parse below was written against. `bb` puts its version
@@ -2174,13 +2381,20 @@ bb_issue_exit_code() {
2174
2381
  # that lists a `pr` command and no `issue` command is a bb that cannot be asked
2175
2382
  # about issues, which is exit 4 — the same answer as a disabled tracker. Any
2176
2383
  # other help text keeps the refusal below, exit 3. Exits 4 or 3; 0 passes.
2384
+ #
2385
+ # The `Tracker` advice below fits only where nobody declared one — asked of
2386
+ # the domain (`--bb-issue-missing`) rather than re-read here, since this is
2387
+ # the same declared value `issue_source` already read. A failed ask keeps
2388
+ # the advice: naming `Tracker` to a repository that declared one is
2389
+ # harmless, dropping it for one that has not would hide the fix.
2177
2390
  bb_assert_issue_version() {
2178
2391
  [ -n "${PLOT_BB_SKIP_VERSION_CHECK:-}" ] && return 0
2179
- local v
2180
- v="$(bb --version 2>/dev/null | bb_strip_ansi | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | head -1)"
2392
+ local v="$(bb --version 2>/dev/null | bb_strip_ansi | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | head -1)"
2181
2393
  if [ "$v" != "$BB_ISSUE_VERSION" ]; then
2182
2394
  if bb_lacks_issue_command; then
2183
- echo "plot-host: bb ${v:-unknown} lists no issue command — Quatico bb has none, unlike craftamap/bb — so this repository's issues cannot be read through it; declare the issue tracker with the \`Tracker\` config key" >&2
2395
+ local missing="$(tracker_raw | node "$here/board/plot-issue-source.mjs" --bb-issue-missing 2>/dev/null)"
2396
+ [ -n "$missing" ] || missing="bb lists no issue command — Quatico bb has none, unlike craftamap/bb — so this repository's issues cannot be read through it; declare the issue tracker with the \`Tracker\` config key"
2397
+ echo "plot-host: bb ${v:-unknown} $missing" >&2
2184
2398
  return 4
2185
2399
  fi
2186
2400
  echo "plot-host: bb issue parse targets $BB_ISSUE_VERSION but found '${v:-unknown}' — refusing to mis-read a format that may have moved" >&2
@@ -2305,9 +2519,7 @@ bb_test_json_support() {
2305
2519
  fi
2306
2520
 
2307
2521
  # A "not a bitbucket repo" error is about the repo, not the flag.
2308
- if grep -qiE 'not a bitbucket repo|repository not found' <<<"$out"; then
2309
- return 0
2310
- fi
2522
+ grep -qiE 'not a bitbucket repo|repository not found' <<<"$out" && return 0
2311
2523
 
2312
2524
  # AN UNRECOGNISED FAILURE ACCEPTS, and this is a behaviour change the plan
2313
2525
  # argued for in round 1. Refusing on wording outside the three formats above
@@ -2499,16 +2711,10 @@ tracker_base_url() {
2499
2711
  # cannot express ABSENCE — an empty override falls through to the config — so
2500
2712
  # the absent case is tested with a repository that declares nothing.
2501
2713
  tracker_projects() {
2502
- local raw
2503
- if [ -n "${PLOT_TICKET_PREFIXES:-}" ]; then
2504
- raw="$PLOT_TICKET_PREFIXES"
2505
- else
2506
- raw="$(bash "$here/plot-config.sh" get "Ticket prefixes" "")"
2507
- fi
2508
2714
  # One per line, trimmed, empties dropped. `plot-config.sh` already normalises
2509
2715
  # `A,B` to `A, B`, but an override arrives unnormalised and a hand-edited
2510
2716
  # value can carry a stray comma — so the split is done here regardless.
2511
- printf '%s' "$raw" | tr ',' '\n' | sed -E 's/^[[:space:]]+//; s/[[:space:]]+$//' | grep -v '^$' || true
2717
+ printf '%s' "${PLOT_TICKET_PREFIXES:-$(bash "$here/plot-config.sh" get "Ticket prefixes" "")}" | tr ',' '\n' | sed -E 's/^[[:space:]]+//; s/[[:space:]]+$//' | grep -v '^$' || true
2512
2718
  }
2513
2719
 
2514
2720
  # Reads ONE variable from a `.env`-shaped file. Evaluates nothing.
@@ -2538,6 +2744,25 @@ read_env_var() { # $1=name $2=file → the value, or nothing
2538
2744
  -e 's/[[:space:]]*$//'
2539
2745
  }
2540
2746
 
2747
+ # The `.env` candidate for this checkout, and which of two locations it came
2748
+ # from. `.env` is untracked, so it lives only in the MAIN checkout — a fleet
2749
+ # desk or a scratch worktree under `Worktree root` has none of its own, and
2750
+ # `git rev-parse --show-toplevel` there answers with the WORKTREE, which never
2751
+ # holds one. Prints "<path>|" (worktree) or "<path>|the main checkout's" on a
2752
+ # readable candidate, or nothing when neither location has one.
2753
+ #
2754
+ # NO UPWARD WALK past either location — the fallback is exactly one more
2755
+ # place to look, not a search. `--git-common-dir`'s parent is the main
2756
+ # checkout root only for a standard `git worktree add` checkout; where the
2757
+ # command fails, prints nothing, or its parent directory does not exist, this
2758
+ # falls through to "no main checkout .env" rather than inventing a path.
2759
+ plot_env_file() {
2760
+ local root env_file common; root="$(git rev-parse --show-toplevel 2>/dev/null)" || root="."; env_file="$root/.env"
2761
+ [ -r "$env_file" ] && { printf '%s|' "$env_file"; return 0; }
2762
+ common="$(git rev-parse --git-common-dir 2>/dev/null)" && [ -n "$common" ] || return 0
2763
+ env_file="$(dirname "$common")/.env"; [ -r "$env_file" ] && printf "%s|the main checkout's " "$env_file"
2764
+ }
2765
+
2541
2766
  # The env var scheme for Jira auth. The plan left the EXACT names open, to be
2542
2767
  # confirmed against a real instance; these follow Jira Cloud's documented Basic
2543
2768
  # scheme (email + API token, base64'd into an Authorization header):
@@ -2551,48 +2776,24 @@ read_env_var() { # $1=name $2=file → the value, or nothing
2551
2776
  # `die3` exits the whole script only from there, not from inside a command
2552
2777
  # substitution where it would end only the subshell and leak a second error.
2553
2778
  #
2554
- # WHERE BOTH ARE UNSET, THE REPOSITORY'S `.env` IS READ. The refusal below named
2555
- # two variables without ever looking where a repository puts them, so an
2556
- # operator holding working credentials — measured 2026-09-17, a 200 from
2557
- # `/rest/api/3/myself` with the same pair — was sent to create a second token.
2558
- # "Export it in your shell" does not reach the board either: it is a long-lived
2559
- # process, which is why `plot-fleetctl.sh` bakes an environment into its unit.
2560
- #
2561
- # THE ENVIRONMENT WINS AND NOTHING IS READ WHERE IT ANSWERS. The file is opened
2562
- # only when BOTH are unset, so a deliberate export is never second-guessed and
2563
- # the common path touches no disk.
2564
- #
2565
- # AND THE SOURCE IS NAMED, which is a requirement rather than a nicety: two
2566
- # tokens may exist, and an operator debugging a 401 must be able to tell which
2567
- # one was used. `plot-board-probe.sh` reports `auth` as three words rather than
2568
- # a boolean for the same reason. THE VALUE IS NEVER PRINTED — only the source.
2779
+ # WHERE BOTH ARE UNSET, `plot_env_file` IS READ, same order and both-or-neither
2780
+ # rule as `jenkins_rest_credential` — measured 2026-09-17, an operator holding
2781
+ # a working pair was sent to create a second token before this fallback
2782
+ # existed. THE VALUE IS NEVER PRINTED, only the source, so a 401 can be
2783
+ # debugged against the right one of two possible tokens.
2569
2784
  jira_load_env_file() {
2570
- local root env_file email token
2785
+ local found env_file source email token
2571
2786
  [ -z "${JIRA_EMAIL:-}" ] && [ -z "${JIRA_API_TOKEN:-}" ] || return 0
2572
-
2573
- # The repository root, `plot-config.sh:145`'s idiom. NO UPWARD WALK past it:
2574
- # a search toward $HOME would read a file the operator did not mean for this
2575
- # repository.
2576
- root="$(git rev-parse --show-toplevel 2>/dev/null)" || root="."
2577
- env_file="$root/.env"
2578
- [ -r "$env_file" ] || return 0
2579
-
2580
- email="$(read_env_var JIRA_EMAIL "$env_file")"
2581
- token="$(read_env_var JIRA_API_TOKEN "$env_file")"
2787
+ found="$(plot_env_file)"; [ -n "$found" ] || return 0; env_file="${found%|*}"; source="${found#*|}"
2788
+ email="$(read_env_var JIRA_EMAIL "$env_file")"; token="$(read_env_var JIRA_API_TOKEN "$env_file")"
2582
2789
  # BOTH OR NEITHER. Half a Basic credential authenticates nothing, and a
2583
2790
  # partial pickup would turn today's honest refusal into a 401 further in.
2584
2791
  [ -n "$email" ] && [ -n "$token" ] || return 0
2585
-
2586
- JIRA_EMAIL="$email"
2587
- JIRA_API_TOKEN="$token"
2588
- export JIRA_EMAIL JIRA_API_TOKEN
2589
- echo "plot-host: JIRA_EMAIL and JIRA_API_TOKEN read from .env" >&2
2792
+ export JIRA_EMAIL="$email" JIRA_API_TOKEN="$token"; echo "plot-host: JIRA_EMAIL and JIRA_API_TOKEN read from ${source}.env" >&2
2590
2793
  }
2591
2794
 
2592
2795
  jira_require_config() {
2593
- if [ -z "$(tracker_base_url)" ]; then
2594
- die3 "Tracker is jira but no base URL is configured (write 'Tracker: jira https://your.atlassian.net' or set PLOT_JIRA_BASE_URL)"
2595
- fi
2796
+ [ -n "$(tracker_base_url)" ] || die3 "Tracker is jira but no base URL is configured (write 'Tracker: jira https://your.atlassian.net' or set PLOT_JIRA_BASE_URL)"
2596
2797
  jira_load_env_file
2597
2798
  if [ -z "${JIRA_EMAIL:-}" ] || [ -z "${JIRA_API_TOKEN:-}" ]; then
2598
2799
  echo "plot-host: Jira needs JIRA_EMAIL and JIRA_API_TOKEN in the environment — an unauthenticated Jira must not read as an empty inbox" >&2
@@ -2677,20 +2878,14 @@ budget_record_jira() {
2677
2878
  # CAN be asked; if it cannot be reached, that is a failure to answer, not a host
2678
2879
  # that structurally has no tracker (the bitbucket-DISABLED case exit 4 is for).
2679
2880
  jira_check() {
2680
- local raw="$1" curl_rc="$2"
2681
- local status body
2682
- if [ "$curl_rc" -ne 0 ]; then
2683
- echo "plot-host: jira request failed (curl exit $curl_rc) — a network failure is not an empty inbox" >&2
2684
- return 3
2685
- fi
2881
+ local raw="$1" curl_rc="$2" status body detail
2882
+ [ "$curl_rc" -eq 0 ] || { echo "plot-host: jira request failed (curl exit $curl_rc) — a network failure is not an empty inbox" >&2; return 3; }
2686
2883
  # The status is the last line; the body is everything before it.
2687
- status="$(printf '%s' "$raw" | tail -n1)"
2688
- body="$(printf '%s' "$raw" | sed '$d')"
2884
+ status="$(printf '%s' "$raw" | tail -n1)"; body="$(printf '%s' "$raw" | sed '$d')"
2689
2885
  if [ "$status" -lt 200 ] || [ "$status" -ge 300 ]; then
2690
2886
  # Name the status AND Jira's own errorMessages if it sent any (it returns
2691
2887
  # {"errorMessages":[…],"errors":{…}} on 4xx). 401/403 are the auth failures
2692
2888
  # this story exists to keep out of the inbox; 5xx is an outage. Both are 3.
2693
- local detail
2694
2889
  detail="$(printf '%s' "$body" | jq -r 'try (.errorMessages | join("; ")) catch empty' 2>/dev/null)"
2695
2890
  echo "plot-host: jira HTTP $status${detail:+ — $detail}" >&2
2696
2891
  return 3
@@ -2801,11 +2996,25 @@ bb_list_page_length() {
2801
2996
  # never see both for one state, and silence now means only that no claim was
2802
2997
  # owed — no `--limit`, or an empty page.
2803
2998
  #
2999
+ # THE ENVELOPE'S OWN `next` SUPERSEDES THE PAGE-LENGTH TEST, for any `bb`
3000
+ # version. #1757: `BB_LIST_PAGE_VERSIONS` names only versions this estate has
3001
+ # measured, so a page from any other version (1.11.1 included) could never be
3002
+ # proven complete by row count alone — 9 rows with no `next` read as "possibly
3003
+ # truncated" even though the envelope already answered. A page WITH `next`
3004
+ # proves nothing either way (Bitbucket could in principle set it with zero rows
3005
+ # left), so it falls through to the length test exactly as before. Absence,
3006
+ # never presence, is the signal — `$5` is "0" only when `bb_state_listing` read
3007
+ # an envelope with no `next` key; "1" means `next` was present; "" means no
3008
+ # envelope shape was read at all, and the version table alone decides, as
3009
+ # before this slice.
3010
+ #
2804
3011
  # $1 backend $2 requested limit (may be "") $3 state word $4 row count
3012
+ # $5 envelope's own completeness reading: "0" no next, "1" next present, ""
3013
+ # unknown (`BB_LIST_NEXT`, bitbucket only — github's listing carries none)
2805
3014
  pr_list_report_truncation() {
2806
- local be="$1" limit="$2" state="$3" count="$4" len=""
2807
- [ -n "$limit" ] || return 0 # no --limit → no completeness claim owed
2808
- [ "$count" -gt 0 ] 2>/dev/null || return 0 # an empty page had nothing to hide
3015
+ local be="$1" limit="$2" state="$3" count="$4" next="${5:-}" len=""
3016
+ # no --limit → no completeness claim owed; an empty page had nothing to hide
3017
+ [ -n "$limit" ] || return 0; [ "$count" -gt 0 ] 2>/dev/null || return 0
2809
3018
  if [ "$be" = "github" ]; then
2810
3019
  # github honours the limit: complete unless the page came back AT the limit.
2811
3020
  # Measured 2026-10-02 on this repository (1064 PRs): `--limit 1100`
@@ -2814,9 +3023,10 @@ pr_list_report_truncation() {
2814
3023
  # exist rather than the rows requested.
2815
3024
  if [ "$count" -lt "$limit" ] 2>/dev/null; then pr_list_report_complete "$be" "$limit" "$state" "$count"; return 0; fi
2816
3025
  else
2817
- # A fixed page: complete below a measured page length, unprovable otherwise.
2818
- [ "$be" = "bitbucket" ] && len="$(bb_list_page_length)"
2819
- if [ -n "$len" ] && [ "$count" -lt "$len" ] 2>/dev/null; then pr_list_report_complete "$be" "$limit" "$state" "$count"; return 0; fi
3026
+ # A fixed page: complete below a measured length, or whose own envelope
3027
+ # named no further page — unprovable otherwise.
3028
+ [ "$next" = "0" ] || len="$(bb_list_page_length)"
3029
+ if [ "$next" = "0" ] || { [ -n "$len" ] && [ "$count" -lt "$len" ] 2>/dev/null; }; then pr_list_report_complete "$be" "$limit" "$state" "$count"; return 0; fi
2820
3030
  fi
2821
3031
  # Named per state so a caller can resolve exactly the states that were
2822
3032
  # capped, not a whole-call flag that over-reports.
@@ -3420,9 +3630,7 @@ be="$(backend)" || exit $?
3420
3630
  # `gh_route`, never reads a budget, and `$route` stays empty for it. That
3421
3631
  # emptiness is the honest value — there is no route where there is no fork.
3422
3632
  route=""
3423
- if [ "$be" = "github" ]; then
3424
- route="$(gh_route "$op")"
3425
- fi
3633
+ [ "$be" = "github" ] && route="$(gh_route "$op")"
3426
3634
 
3427
3635
  case "$op" in
3428
3636
  backend)
@@ -3560,9 +3768,9 @@ case "$op" in
3560
3768
  # mergeCommit is what lets a caller ask "which release contains this?" —
3561
3769
  # `git tag --contains <sha>` answers exactly, where dates cannot. It is ""
3562
3770
  # for anything unmerged, which is the honest answer rather than a guess.
3563
- elif out="$(gh ${repo_args[@]+"${repo_args[@]}"} pr view "$ref" --json number,state,isDraft,url,mergeCommit,headRefOid,baseRefName,statusCheckRollup 2>"$HOST_ERR")"; then
3771
+ 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
3564
3772
  rm -f "$HOST_ERR"
3565
- jq -c "$CHECKS_OF"'{number:.number,state:.state,draft:.isDraft,url:.url,mergeCommit:(.mergeCommit.oid // ""),headSha:(.headRefOid // ""),base:(.baseRefName // ""),checks:checks_of,checksSha:(.headRefOid // "")}' <<<"$out"
3773
+ 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"
3566
3774
  else
3567
3775
  err="$(cat "$HOST_ERR" 2>/dev/null)"; rm -f "$HOST_ERR"
3568
3776
  # REFUSED FOR RATE IS NOT ANSWERED. The budget gate above could not see
@@ -3599,7 +3807,7 @@ case "$op" in
3599
3807
  if [[ "$ref" =~ ^[0-9]+$ ]]; then
3600
3808
  if out="$(bb ${repo_args[@]+"${repo_args[@]}"} pr view "$ref" --json 2>"$HOST_ERR")"; then
3601
3809
  rm -f "$HOST_ERR"
3602
- jq -c '{number:.id,state:(if .state=="DECLINED" then "CLOSED" else .state end),draft:(.draft // false),url:.links.html.href,mergeCommit:(.merge_commit.hash // ""),base:(.destination.branch.name // "")}' <<<"$out"
3810
+ bb_fold_mergeable "$(bb_state_row "$out")"
3603
3811
  else
3604
3812
  err="$(cat "$HOST_ERR" 2>/dev/null)"; rm -f "$HOST_ERR"
3605
3813
  host_miss_or_fail "$err" '{"number":0,"state":"NONE","draft":false,"url":"","mergeCommit":""}' || exit $?
@@ -3623,16 +3831,25 @@ case "$op" in
3623
3831
  #
3624
3832
  # A declined-only or PR-less branch still pays for all three; those are
3625
3833
  # the cases where the third call is the one carrying the answer.
3834
+ #
3835
+ # ASK THE HOST FOR THE BRANCH; DO NOT PAGE FURTHER. `bb_branch_query`
3836
+ # replaces each state's whole-repository page with the per-branch REST
3837
+ # filter, costing one request per state asked instead of one page that
3838
+ # cannot see past its first 50 rows — `pr-merged`'s header has the
3839
+ # measurement. `bb_states_for all` still expands to three calls because
3840
+ # `bb pr list` (and this REST filter) has no `all` state.
3841
+ #
3842
+ # NO "FULL PAGE, NO MATCH" GUARD HERE, unlike the single-state arms
3843
+ # below. The loop breaks on the first non-empty page, and every row in
3844
+ # it already matches `$ref` — `bb_branch_query` filtered server-side —
3845
+ # so a full page is 50 real answers, never a truncated non-match. The
3846
+ # condition the other arms guard against cannot occur in this walk.
3626
3847
  out=""; bb_rc=0
3627
3848
  bb_all_states="$(bb_states_for all)" || exit 1
3628
3849
  for _s in $bb_all_states; do
3629
- if _part="$(bb ${repo_args[@]+"${repo_args[@]}"} pr list --state "$_s" --json 2>"$HOST_ERR")"; then
3850
+ if _part="$(bb_branch_query "$ref" "$_s" ${repo_args[@]+"${repo_args[@]}"} 2>"$HOST_ERR")"; then
3630
3851
  out="$out$_part"
3631
- # `jq -e` exits non-zero on null/false, so this asks "did this state
3632
- # contain the branch?" without a second parse of the whole page.
3633
- if jq -e --arg b "$ref" 'any(.[]; .source.branch.name==$b)' >/dev/null 2>&1 <<<"$_part"; then
3634
- break
3635
- fi
3852
+ [ "$(jq 'length' <<<"$_part")" -gt 0 ] && break
3636
3853
  else
3637
3854
  bb_rc=1; break
3638
3855
  fi
@@ -3646,11 +3863,10 @@ case "$op" in
3646
3863
  # from the answer. A fix touching only the numeric pair above would
3647
3864
  # leave that caller reading an absent key on every Bitbucket repo.
3648
3865
  #
3649
- # The hash rides on the page the state walk already fetched, so this
3650
- # costs no extra call.
3651
- jq -c --arg b "$ref" '[.[] | select(.source.branch.name==$b)][0] // null
3652
- | if .==null then {number:0,state:"NONE",draft:false,url:"",mergeCommit:""}
3653
- else {number:.id,state:(if .state=="DECLINED" then "CLOSED" else .state end),draft:(.draft // false),url:.links.html.href,mergeCommit:(.merge_commit.hash // ""),base:(.destination.branch.name // "")} end' <<<"$out"
3866
+ # The hash rides on the page the branch query already fetched, so this
3867
+ # costs no extra call. `bb_branch_query` already filtered to the
3868
+ # branch, so every row in `out` already matches it.
3869
+ bb_fold_mergeable "$(bb_state_row "$(jq -c '.[0] // null' <<<"$out")")"
3654
3870
  else
3655
3871
  err="$(cat "$HOST_ERR" 2>/dev/null)"; rm -f "$HOST_ERR"
3656
3872
  host_miss_or_fail "$err" '{"number":0,"state":"NONE","draft":false,"url":"","mergeCommit":""}' || exit $?
@@ -3681,57 +3897,47 @@ case "$op" in
3681
3897
  esac
3682
3898
  done
3683
3899
  # NO REMOTE, NO PR: no repository holds one, so nothing merged, whatever gh's auth says.
3684
- if [ ${#repo_args[@]} -eq 0 ] && [ -z "$(git remote 2>/dev/null)" ]; then echo "not-merged"; elif [ "$be" = "github" ]; then
3685
- # --state all, because a merged PR reports CLOSED and the default `open`
3686
- # would hide every one of them. --limit 100 rather than 1: the newest PR
3687
- # is not the merge, exactly as the state is not the merge.
3688
- if out="$(gh ${repo_args[@]+"${repo_args[@]}"} pr list --head "$ref" --state all --limit 100 --json mergedAt 2>"$HOST_ERR")"; then
3689
- rm -f "$HOST_ERR"
3690
- if jq -e 'any(.[]; .mergedAt != null)' >/dev/null 2>&1 <<<"$out"; then
3691
- echo "merged"
3692
- else
3693
- echo "not-merged"
3694
- fi
3695
- else
3696
- err="$(cat "$HOST_ERR" 2>/dev/null)"; rm -f "$HOST_ERR"
3697
- # A LOOKUP MISS IS AN ANSWER — the branch has no PR, so nothing merged.
3698
- # Anything else is the host failing to be asked, and that is `unknown`
3699
- # rather than exit 3: the caller asked a question with a third value
3700
- # for exactly this case, and the answer fails safe toward keeping.
3701
- if [ -z "$err" ] || is_lookup_miss "$err"; then
3702
- echo "not-merged"
3703
- else
3704
- echo "plot-host: $err" >&2
3705
- echo "unknown"
3706
- fi
3707
- fi
3708
- else
3709
- bb_require_json
3710
- # Bitbucket has no `--head` filter, so the branch is matched locally.
3711
- # MERGED is bb's own state word here rather than a timestamp: the API
3712
- # exposes no `mergedAt`, so this is the closest fact the backend holds,
3713
- # and it is a positive statement about the merge rather than an inference
3714
- # from CLOSED — `DECLINED` is bb's closed-unmerged word and is distinct.
3715
- if out="$(bb ${repo_args[@]+"${repo_args[@]}"} pr list --state merged --json 2>"$HOST_ERR")"; then
3716
- rm -f "$HOST_ERR"
3717
- if jq -e --arg b "$ref" 'any(.[]; .source.branch.name==$b)' >/dev/null 2>&1 <<<"$out"; then
3718
- echo "merged"
3900
+ if [ ${#repo_args[@]} -eq 0 ] && [ -z "$(git remote 2>/dev/null)" ]; then echo "not-merged"; else
3901
+ if [ "$be" = "github" ]; then
3902
+ # --state all, because a merged PR reports CLOSED and the default `open`
3903
+ # would hide every one of them. --limit 100 rather than 1: the newest PR
3904
+ # is not the merge, exactly as the state is not the merge.
3905
+ if out="$(gh ${repo_args[@]+"${repo_args[@]}"} pr list --head "$ref" --state all --limit 100 --json mergedAt 2>"$HOST_ERR")"; then
3906
+ rm -f "$HOST_ERR"
3907
+ jq -e 'any(.[]; .mergedAt != null)' >/dev/null 2>&1 <<<"$out" && echo "merged" || echo "not-merged"
3719
3908
  else
3720
- echo "not-merged"
3909
+ err="$(cat "$HOST_ERR" 2>/dev/null)"; rm -f "$HOST_ERR"
3910
+ miss_or_unknown "$err"
3721
3911
  fi
3722
3912
  else
3723
- err="$(cat "$HOST_ERR" 2>/dev/null)"; rm -f "$HOST_ERR"
3724
- if [ -z "$err" ] || is_lookup_miss "$err"; then
3725
- echo "not-merged"
3913
+ bb_require_json
3914
+ # ASK THE HOST FOR THE BRANCH; DO NOT PAGE FURTHER. `bb pr list --state
3915
+ # merged` returns one fixed page of 50, newest first, and a branch whose
3916
+ # merge is older than that page reads as unmerged — measured 2026-10-20
3917
+ # on ewz-kus-portal: PR #3644 merged 2026-09-26, invisible to a page that
3918
+ # reached back only to 2026-09-30. `bb_branch_query` puts
3919
+ # `source.branch.name` inside `q=` so the host filters, costing one
3920
+ # request instead of a listing this adapter refuses to page past its
3921
+ # ceiling (see `bb_branch_sweep`'s header).
3922
+ if out="$(bb_branch_query "$ref" merged ${repo_args[@]+"${repo_args[@]}"} 2>"$HOST_ERR")"; then
3923
+ rm -f "$HOST_ERR"
3924
+ # A FULL PAGE CANNOT PROVE ABSENCE. `bb_branch_query` asks pagelen=50,
3925
+ # and a branch carrying more than 50 merged PRs could hide a MERGED row
3926
+ # past it — so 50 rows with none matching answers `unknown`, not
3927
+ # `not-merged`, the same rule a failed call follows below.
3928
+ if jq -e 'any(.[]; .state == "MERGED")' >/dev/null 2>&1 <<<"$out"; then echo "merged"
3929
+ 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"
3930
+ else echo "not-merged"
3931
+ fi
3726
3932
  else
3727
- echo "plot-host: $err" >&2
3728
- echo "unknown"
3933
+ err="$(cat "$HOST_ERR" 2>/dev/null)"; rm -f "$HOST_ERR"
3934
+ miss_or_unknown "$err"
3729
3935
  fi
3730
3936
  fi
3731
3937
  fi
3732
3938
  ;;
3733
3939
 
3734
- pr-merge-commit)
3940
+ pr-merge-commit|pr-merge-dest)
3735
3941
  # THE MERGE COMMIT OF A BRANCH'S MERGED PR, and nothing else.
3736
3942
  #
3737
3943
  # A SECOND SUBCOMMAND RATHER THAN A FIELD ON `pr-merged`, because that one
@@ -3751,22 +3957,29 @@ case "$op" in
3751
3957
  #
3752
3958
  # PRINTS NOTHING AND EXITS 0 where no PR merged — an ANSWER, the same shape
3753
3959
  # `pr-state` gives for a missing PR. Exit 3 is the question failing.
3754
- ref="${1:?pr-merge-commit needs a branch}"; shift || true
3960
+ #
3961
+ # `pr-merge-dest` RUNS THE SAME QUERY and prints every merged PR instead of
3962
+ # the first sha: one `number<TAB>base<TAB>sha<TAB>mergedAt` line each, read
3963
+ # off the same payload. `plot-release-chain.mjs` asks it once per hop of a
3964
+ # release-chain walk. Bitbucket names no merge time, so `mergedAt` is
3965
+ # `updated_on`, as in `pr-list`.
3966
+ ref="${1:?$op needs a branch}"; shift || true
3755
3967
  repo_args=()
3756
3968
  while [ $# -gt 0 ]; do
3757
3969
  case "$1" in
3758
3970
  --repo) repo_args=(-R "${2:?}"); shift 2 ;;
3759
- *) die "pr-merge-commit: unknown arg $1" ;;
3971
+ *) die "$op: unknown arg $1" ;;
3760
3972
  esac
3761
3973
  done
3974
+ if [ "$op" = pr-merge-dest ]; then pick='.[] | [.n, .b, .s, .t] | @tsv'; else pick='first.s // empty'; fi
3762
3975
  if [ "$be" = "github" ]; then
3763
- if out="$(gh ${repo_args[@]+"${repo_args[@]}"} pr list --head "$ref" --state all --limit 100 --json mergedAt,mergeCommit 2>"$HOST_ERR")"; then
3976
+ if out="$(gh ${repo_args[@]+"${repo_args[@]}"} pr list --head "$ref" --state all --limit 100 --json number,mergedAt,mergeCommit,baseRefName 2>"$HOST_ERR")"; then
3764
3977
  rm -f "$HOST_ERR"
3765
3978
  # The FIRST merged PR carrying a sha. A branch may hold several merged
3766
3979
  # PRs; each names its own merge commit, and any of them is a commit that
3767
3980
  # landed this branch's work.
3768
- jq -r 'map(select(.mergedAt != null and .mergeCommit != null))
3769
- | map(.mergeCommit.oid) | first // empty' <<<"$out"
3981
+ jq -r 'map(select(.mergedAt != null and .mergeCommit != null)
3982
+ | {n: .number, b: (.baseRefName // ""), s: .mergeCommit.oid, t: .mergedAt}) | '"$pick" <<<"$out"
3770
3983
  else
3771
3984
  err="$(cat "$HOST_ERR" 2>/dev/null)"; rm -f "$HOST_ERR"
3772
3985
  # A lookup miss is an answer: no PR, so no merge commit. Anything else
@@ -3776,11 +3989,14 @@ case "$op" in
3776
3989
  fi
3777
3990
  else
3778
3991
  bb_require_json
3779
- # Bitbucket names the merge commit `merge_commit.hash` on a merged PR.
3780
- if out="$(bb ${repo_args[@]+"${repo_args[@]}"} pr list --state merged --json 2>"$HOST_ERR")"; then
3992
+ # ASK THE HOST FOR THE BRANCH; DO NOT PAGE FURTHER — `pr-merged`'s header
3993
+ # states the measurement and the cost. Bitbucket names the merge commit
3994
+ # `merge_commit.hash` on a merged PR.
3995
+ if out="$(bb_branch_query "$ref" merged ${repo_args[@]+"${repo_args[@]}"} 2>"$HOST_ERR")"; then
3781
3996
  rm -f "$HOST_ERR"
3782
- jq -r --arg b "$ref" 'map(select(.source.branch.name==$b))
3783
- | map(.merge_commit.hash // empty) | first // empty' <<<"$out"
3997
+ 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; }
3998
+ jq -r 'map(select(.merge_commit.hash != null)
3999
+ | {n: .id, b: (.destination.branch.name // ""), s: .merge_commit.hash, t: (.updated_on // "")}) | '"$pick" <<<"$out"
3784
4000
  else
3785
4001
  err="$(cat "$HOST_ERR" 2>/dev/null)"; rm -f "$HOST_ERR"
3786
4002
  miss_or_exit3 "$err"
@@ -3813,33 +4029,33 @@ case "$op" in
3813
4029
  jq -r '.[] | select(.mergedAt != null and .headRefOid != null) | .headRefOid' <<<"$out" || exit 3
3814
4030
  else
3815
4031
  err="$(cat "$HOST_ERR" 2>/dev/null)"; rm -f "$HOST_ERR"
3816
- if [ -n "$err" ] && is_lookup_miss "$err"; then
3817
- :
3818
- else
3819
- echo "plot-host: ${err:-gh pr list failed}" >&2
3820
- exit 3
3821
- fi
4032
+ [ -n "$err" ] && is_lookup_miss "$err" || { echo "plot-host: ${err:-gh pr list failed}" >&2; exit 3; }
3822
4033
  fi
3823
4034
  else
3824
4035
  bb_require_json
3825
- # Bitbucket names the merged head `source.commit.hash`.
3826
- if out="$(bb ${repo_args[@]+"${repo_args[@]}"} pr list --state merged --json 2>"$HOST_ERR")"; then
4036
+ # ASK THE HOST FOR THE BRANCH; DO NOT PAGE FURTHER — `pr-merged`'s header
4037
+ # states the measurement and the cost. Bitbucket names the merged head
4038
+ # `source.commit.hash`.
4039
+ if out="$(bb_branch_query "$ref" merged ${repo_args[@]+"${repo_args[@]}"} 2>"$HOST_ERR")"; then
3827
4040
  rm -f "$HOST_ERR"
3828
- jq -r --arg b "$ref" '.[] | select(.source.branch.name==$b) | (.source.commit.hash // empty)' <<<"$out" || exit 3
4041
+ 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; }
4042
+ jq -r '.[] | (.source.commit.hash // empty)' <<<"$out" || exit 3
3829
4043
  else
3830
4044
  err="$(cat "$HOST_ERR" 2>/dev/null)"; rm -f "$HOST_ERR"
3831
- if [ -n "$err" ] && is_lookup_miss "$err"; then
3832
- :
3833
- else
3834
- echo "plot-host: ${err:-bb pr list failed}" >&2
3835
- exit 3
3836
- fi
4045
+ [ -n "$err" ] && is_lookup_miss "$err" || { echo "plot-host: ${err:-the branch query failed}" >&2; exit 3; }
3837
4046
  fi
3838
4047
  fi
3839
4048
  ;;
3840
4049
 
3841
4050
  pr-review)
3842
- [ "$be" = "github" ] || { echo "plot-host: pr-review: bitbucket is not supported yet" >&2; exit 4; }
4051
+ if [ "$be" != "github" ]; then
4052
+ pr="/repositories/{ws}/{repo}/pullrequests/${1:?pr-review needs a PR number}"
4053
+ out="$(bb api "$pr")" && sha="$(jq -re '.source.commit.hash' <<<"$out")" \
4054
+ && st="$(bb api "/repositories/{ws}/{repo}/commit/$sha/statuses?sort=-created_on&pagelen=50")" && cm="$(bb api "$pr/comments?pagelen=100")" \
4055
+ && printf '%s\n%s\n%s\n' "$sha" "$(jq -c . <<<"$st")" "$(jq -c . <<<"$cm")" | node "$here/board/plot-jenkins-pr-checks.mjs" review \
4056
+ || { echo "plot-host: pr-review: the read failed" >&2; exit 3; }
4057
+ exit 0
4058
+ fi
3843
4059
  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")" \
3844
4060
  && jq -c --argjson st "$st" '{sha: .headRefOid, state: ([$st[] | select(.context == "plot/review")][0].state // "absent"), bypass: any(.comments[]?; .body | startswith("review-bypass:"))}' <<<"$out" \
3845
4061
  || { echo "plot-host: pr-review: the read failed" >&2; exit 3; } ;;
@@ -3857,19 +4073,11 @@ case "$op" in
3857
4073
  esac
3858
4074
  done
3859
4075
  [ -n "$title" ] || die "pr-create needs --title"
3860
- if [ "$be" = "github" ]; then
3861
- args=(pr create --title "$title" --body "$body")
3862
- [ -n "$base" ] && args+=(--base "$base")
3863
- [ -n "$head" ] && args+=(--head "$head")
3864
- [ "$draft" = 1 ] && args+=(--draft)
3865
- gh "${args[@]}"
3866
- else
3867
- args=(pr create --title "$title" --body "$body")
3868
- [ -n "$base" ] && args+=(--base "$base")
3869
- [ -n "$head" ] && args+=(--head "$head")
3870
- [ "$draft" = 1 ] && args+=(--draft)
3871
- bb "${args[@]}"
3872
- fi
4076
+ args=(pr create --title "$title" --body "$body")
4077
+ [ -n "$base" ] && args+=(--base "$base")
4078
+ [ -n "$head" ] && args+=(--head "$head")
4079
+ [ "$draft" = 1 ] && args+=(--draft)
4080
+ if [ "$be" = "github" ]; then gh "${args[@]}"; else bb "${args[@]}"; fi
3873
4081
  ;;
3874
4082
 
3875
4083
  pr-merge)
@@ -3892,16 +4100,17 @@ case "$op" in
3892
4100
  # answers 5 with its one-line notice where no key is declared: the merge
3893
4101
  # then runs as the signed-in `gh` identity. The token goes straight into
3894
4102
  # GH_TOKEN — never into argv, a file, or a log line.
3895
- merger_repo=$(gh repo view --json nameWithOwner --jq '.nameWithOwner' 2>/dev/null)
4103
+ 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; }
3896
4104
  merger_token=$(node "$here/plot-merger-token.mjs" "$merger_repo") || { mc=$?; [ "$mc" = 5 ] || exit "$mc"; }
3897
4105
  args=(pr merge "$num"); [ "$squash" = 1 ] && args+=(--squash) || args+=(--merge); [ "$delbranch" = 1 ] && args+=(--delete-branch)
3898
4106
  if [ -n "$merger_token" ]; then GH_TOKEN="$merger_token" gh "${args[@]}" --match-head-commit "$pin"; else gh "${args[@]}" --match-head-commit "$pin"; fi
3899
- elif [ -n "$pin" ]; then echo "plot-host: pr-merge --match-head: bitbucket cannot pin a merge to a commit; nothing was merged" >&2; exit 4
4107
+ # Bitbucket's merge endpoint takes no head precondition (measured 2026-10-18,
4108
+ # see plan Notes), so the pin is enforced by re-reading the head via bb_state_row
4109
+ # right before merging; it matches by prefix, 7+ hex (domain's sameCommit).
4110
+ 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[@]}"
3900
4111
  else
3901
- args=(pr merge "$num")
3902
- [ "$squash" = 1 ] && args+=(--squash)
3903
- [ "$delbranch" = 1 ] && args+=(--delete-branch)
3904
- bb "${args[@]}"
4112
+ echo "plot-host: pr-merge: bitbucket needs --match-head <sha>; nothing was merged" >&2
4113
+ exit 1
3905
4114
  fi
3906
4115
  ;;
3907
4116
 
@@ -3942,13 +4151,12 @@ case "$op" in
3942
4151
  # --state all, where the newest 30 crowd out every older merged PR. A caller
3943
4152
  # that wants history says how much; the default stays the host's, so no
3944
4153
  # existing caller's result changes.
3945
- limit=""
3946
- branches=""
4154
+ limit=""; branches=""
3947
4155
  # THE WINDOW, AND IT IS THE HOST'S OWN STAMP. Empty means ask about
3948
4156
  # everything, which is what every caller predating this asks and what a
3949
4157
  # caller with no stored watermark must ask. A caller that has one sends it
3950
4158
  # verbatim — see the header: re-rendering it is how a window closes forever.
3951
- since=""
4159
+ since=""; _bound_shas=""
3952
4160
  while [ $# -gt 0 ]; do
3953
4161
  case "$1" in
3954
4162
  --state) state="${2:?}"; shift 2 ;;
@@ -3991,6 +4199,14 @@ case "$op" in
3991
4199
  # over the wrong set answers confidently about branches nobody asked
3992
4200
  # about while missing the ones they did.
3993
4201
  --branch) branches="${branches:+$branches }${2:?}"; shift 2 ;;
4202
+ # ROTATION'S READ-ONLY INPUT (`bitbucket-jenkins-a-pr-list-row`):
4203
+ # branch -> the `checksSha` the caller's PR index already has on
4204
+ # record, JSON, so `jenkins_bind_rows` spends this pass's capped
4205
+ # lookups on branches the index does NOT yet confirm bound to their
4206
+ # current head. OPT-IN, like `--branch` above — a caller with no
4207
+ # index (or none built yet) passes nothing, and every row sorts
4208
+ # exactly as it always has.
4209
+ --bound-shas) _bound_shas="${2:?}"; shift 2 ;;
3994
4210
  *) die "pr-list: unknown arg $1" ;;
3995
4211
  esac
3996
4212
  done
@@ -4167,10 +4383,12 @@ case "$op" in
4167
4383
  # a GitHub repo without Jenkins still reads its own rollup exactly as
4168
4384
  # before.
4169
4385
  # COMMIT FIELDS PER ARM. `headSha` is `headRefOid` on all three GitHub
4170
- # arms. `checksSha` is emitted ONLY by the rollup arm: `statusCheckRollup`
4171
- # belongs to the head commit, so it equals `headSha`. The Jenkins colours
4172
- # are per branch and carry no commit, and the plain arm reads no checks,
4173
- # so neither emits `checksSha`. `mergedAt` is the host's, `""` on an open PR.
4386
+ # arms. `checksSha` is emitted by the rollup arm (`statusCheckRollup`
4387
+ # belongs to the head commit, so it equals `headSha`) and by the
4388
+ # Jenkins arm wherever a sha-bound Jenkins read (`board/plot-jenkins-pr-checks.mjs`)
4389
+ # found a build for that exact head — never from the branch-colour map,
4390
+ # which carries no commit. The plain arm reads no checks and emits none.
4391
+ # `mergedAt` is the host's, `""` on an open PR.
4174
4392
  if [ "$ci" = "jenkins" ]; then
4175
4393
  # GitHub PR list, but `checks` comes from Jenkins, joined on branch
4176
4394
  # name. `statusCheckRollup` is NOT even requested — the GitHub rollup
@@ -4183,31 +4401,45 @@ case "$op" in
4183
4401
  --json number,title,state,headRefName,isDraft,mergeable,mergeStateStatus,reviewDecision,url,updatedAt,author,headRefOid,mergedAt)" || exit $?
4184
4402
  pr_list_report_truncation github "$limit" "$state" \
4185
4403
  "$(jq 'length' <<<"$_gh_raw" 2>/dev/null || echo 0)"
4404
+ # GAPS 3/4/10: `jmap` names no commit, so a push between builds would
4405
+ # carry the OLD head's colour onto the new one. The bundle names the
4406
+ # rows `jmap` cannot settle (green/failing with a head sha, at most
4407
+ # `SHA_LOOKUPS_PER_PASS`); this reads each one's builds by sha, and the
4408
+ # bundle binds them. A lookup that exits non-zero could not ask: no row
4409
+ # gets a reading from it, the pass asks no further row.
4410
+ # 20 builds per lookup: one round trip at any window, and a plain job lists every branch's builds.
4411
+ #
4412
+ # A ROW PAST THE CAP IS NOT THE SAME AS A ROW A BROKEN ASK LEAVES
4413
+ # UNBOUND. `none`/`pending` need no commit, so `$jmap` answers them
4414
+ # safely either way. For `green`/`failing`: a row `$named` lists but
4415
+ # `$shamap` has no entry for is one `jenkins_sha_runs` never reached
4416
+ # because an earlier ask in the same pass broke — "a lookup that
4417
+ # cannot ask is not an answer", carried over unchanged from #2053/
4418
+ # #2075, so its colour stands. A row `$named` never listed is past
4419
+ # `SHA_LOOKUPS_PER_PASS` (`rowsToBind`) and reads `unknown`: its
4420
+ # colour may belong to a commit this PR no longer carries (same gap
4421
+ # as the Bitbucket arm, `bitbucket-jenkins-pr-list-rows-past`).
4422
+ plot_tmpfile _named_file host-prlist-named; _sha_map=$(jenkins_bind_rows pr-list "$jen_map" "$_gh_raw" "$_named_file" "$_bound_shas"); _named=$(jq -R -c -s 'split("\n") | map(select(length > 0))' <"$_named_file")
4186
4423
  printf '%s' "$_gh_raw" \
4187
- | jq -c --argjson jmap "$jen_map" --arg jstatus "$jen_status" '.[] |
4188
- ($jmap[.headRefName] // null) as $jentry |
4424
+ | jq -c --argjson jmap "$jen_map" --argjson shamap "${_sha_map:-null}" --argjson named "${_named:-[]}" --arg jstatus "$jen_status" "$MERGEABLE_OF"'.[] |
4425
+ ($jmap[.headRefName]) as $colour | (($colour.checks == "green" or $colour.checks == "failing")) as $ambiguous | (.headRefName) as $head | ((.headRefOid // "") != "") as $hasSha | (($named | index($head)) != null) as $wasNamed | ($shamap[.headRefName] // (if ($ambiguous and $hasSha and ($wasNamed | not)) then null else $colour end) // null) as $eff |
4426
+ # A ROW `$eff == null` WITH `$ambiguous` NEVER GOT A JENKINS ANSWER
4427
+ # THIS PASS — past the cap, or a lookup that broke early. That is a
4428
+ # different fact from Jenkins NAMING "unknown", so it carries its
4429
+ # own field rather than collapsing into the same `checks` word
4430
+ # (`bitbucket-jenkins-a-pr-list-row`).
4189
4431
  {
4190
4432
  number:.number, title:.title, state:.state, head:.headRefName,
4191
4433
  draft:.isDraft,
4192
- checks:(
4193
- if $jstatus != "ok" then "unknown"
4194
- elif $jentry == null then "none"
4195
- else $jentry.checks
4196
- end),
4197
- mergeable:(
4198
- if .mergeable=="CONFLICTING" or .mergeStateStatus=="DIRTY" then "conflicting"
4199
- elif .mergeable=="MERGEABLE" then "mergeable"
4200
- else "unknown" end),
4434
+ checks:(if $jstatus != "ok" then "unknown" elif $eff == null then (if $ambiguous then "unknown" else "none" end) else $eff.checks end),
4435
+ mergeable:mergeable_of,
4201
4436
  review:(.reviewDecision // ""),
4202
4437
  url:.url,
4203
4438
  updatedAt:(.updatedAt // ""),headSha:(.headRefOid // ""),mergedAt:(.mergedAt // ""),
4439
+ checksSha:($eff.checksSha // ""),
4204
4440
  author:(.author.login // ""),
4205
- failing_checks:(
4206
- if $jentry != null and $jentry.checks == "failing"
4207
- then [$jentry.job]
4208
- else []
4209
- end)
4210
- }'
4441
+ failing_checks:(if $eff.checks == "failing" then [$eff.job] else [] end)
4442
+ } + (if $jstatus == "ok" and $ambiguous and $eff == null then {checksLookup:"skipped"} else {} end)'
4211
4443
  else
4212
4444
  # GitHub without Jenkins (or Jenkins not configured): use GitHub rollup
4213
4445
  _gh_raw="$(pr_list_call gh ${repo_args[@]+"${repo_args[@]}"} pr list --state "$state" ${limit_args[@]+"${limit_args[@]}"} ${search_args[@]+"${search_args[@]}"} \
@@ -4215,14 +4447,11 @@ case "$op" in
4215
4447
  pr_list_report_truncation github "$limit" "$state" \
4216
4448
  "$(jq 'length' <<<"$_gh_raw" 2>/dev/null || echo 0)"
4217
4449
  printf '%s' "$_gh_raw" \
4218
- | jq -c "$CHECKS_OF"'.[] | {
4450
+ | jq -c "$CHECKS_OF$MERGEABLE_OF"'.[] | {
4219
4451
  number:.number, title:.title, state:.state, head:.headRefName,
4220
4452
  draft:.isDraft,
4221
4453
  checks:checks_of,
4222
- mergeable:(
4223
- if .mergeable=="CONFLICTING" or .mergeStateStatus=="DIRTY" then "conflicting"
4224
- elif .mergeable=="MERGEABLE" then "mergeable"
4225
- else "unknown" end),
4454
+ mergeable:mergeable_of,
4226
4455
  review:(.reviewDecision // ""),
4227
4456
  url:.url,
4228
4457
  updatedAt:(.updatedAt // ""),headSha:(.headRefOid // ""),checksSha:(.headRefOid // ""),mergedAt:(.mergedAt // ""),
@@ -4283,9 +4512,7 @@ case "$op" in
4283
4512
  # listing; a per-branch query returns that branch's pull requests and
4284
4513
  # nothing was capped, so the notice would describe a truncation that did
4285
4514
  # not happen. Said only for the listing it is about.
4286
- if [ -n "$limit" ] && [ -z "$branches" ] && [ -z "$since" ]; then
4287
- echo "plot-host: bitbucket ignores --limit $limit; the listing returns one page of 50 per state" >&2
4288
- fi
4515
+ [ -n "$limit" ] && [ -z "$branches" ] && [ -z "$since" ] && echo "plot-host: bitbucket ignores --limit $limit; the listing returns one page of 50 per state" >&2
4289
4516
  # Establish that bb supports --json BEFORE calling it — Done-when 5.
4290
4517
  bb_require_json
4291
4518
  # Resolve the states BEFORE the loop. `for s in $(bb_states_for …)` runs
@@ -4313,7 +4540,6 @@ case "$op" in
4313
4540
  # caller that asked for a window and got a full listing must not read the
4314
4541
  # answer as a delta.
4315
4542
  PR_LIST_SINCE="$since"
4316
- PR_SWEEP_ASKED=0
4317
4543
  # THE PLAIN LISTING IS `bb_state_listing`, one request per state at
4318
4544
  # `pagelen=50`, where `bb pr list` walks 10-row pages. Its header has the
4319
4545
  # measurement.
@@ -4333,9 +4559,42 @@ case "$op" in
4333
4559
  # Bitbucket PR list, `checks` filled from Jenkins — the SAME overlay
4334
4560
  # the GitHub arm uses, which is why it lives above the backend branch.
4335
4561
  # `bb`'s standing `unknown` becomes a real value where Jenkins answers.
4336
- PR_LIST_JQ_ARGS=(--argjson jmap "$jen_map" --arg jstatus "$jen_status")
4562
+ #
4563
+ # A PUSH BETWEEN BUILDS LEAVES `$jmap`'S COLOUR STALE, same gap the
4564
+ # GitHub arm closed (#1959/#1974): the branch-colour map carries no
4565
+ # commit, so a green row can describe a head Jenkins never built. The
4566
+ # fix is `jenkins_bind_rows` (`pr-state`'s own bind path, #1974),
4567
+ # called here via `PR_LIST_BIND_FN` because `pr_list_states` loops
4568
+ # per Bitbucket state and each state's rows are the only place the
4569
+ # head shas live — see that global's header.
4570
+ #
4571
+ # A ROW `jenkins_bind_rows` DROPPED FOR THE CAP (`SHA_LOOKUPS_PER_PASS`,
4572
+ # `rowsToBind`) IS NOT THE SAME AS A ROW IT NEVER NEEDED TO ASK ABOUT.
4573
+ # `$jmap`'s colour binds safely for `none`/`pending` — neither needs a
4574
+ # commit — but `green`/`failing` carry the PREVIOUS head's result, the
4575
+ # defect `rowsToBind` exists to flag by leaving the row out of
4576
+ # `$shamap`.
4577
+ #
4578
+ # AND A ROW PAST THE CAP IS NOT THE SAME AS ONE THE CAP NAMED WHOSE
4579
+ # ASK THEN BROKE EARLY. `$named` (`jenkins_bind_rows`'s own 4th-arg
4580
+ # side file, pure and network-free) lists exactly what `rowsToBind`
4581
+ # selected. A row `$named` never lists is past the cap and reads
4582
+ # `unknown`: its colour may belong to a commit this PR no longer
4583
+ # carries. A row `$named` lists but `$shamap` has no entry for is one
4584
+ # `jenkins_sha_runs` never reached because an earlier ask in the same
4585
+ # pass broke early — "a lookup that cannot ask is not an answer",
4586
+ # carried over unchanged from #2053/#2075, so its colour stands.
4587
+ # `updatedAt` travels too: `rowsToBind` sorts by it to pick the most
4588
+ # recently updated rows, and a row list that never carries it sorts
4589
+ # as a no-op, leaving the cap keyed on array order instead.
4590
+ _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
4591
+ PR_LIST_BIND_FN=_bb_jen_bind
4337
4592
  pr_list_states bitbucket "$limit" "$bb_states" '.[] |
4338
- ($jmap[.source.branch.name] // null) as $jentry |
4593
+ ($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 |
4594
+ # A ROW `$jentry == null` WITH `$ambiguous` NEVER GOT A JENKINS
4595
+ # ANSWER THIS PASS — past the cap, or a lookup that broke early.
4596
+ # Distinct from Jenkins naming "unknown" itself — own field
4597
+ # rather than the same `checks` word (`bitbucket-jenkins-a-pr-list-row`).
4339
4598
  {
4340
4599
  number:.id, title:.title,
4341
4600
  state:(if .state=="DECLINED" then "CLOSED" else .state end),
@@ -4343,29 +4602,24 @@ case "$op" in
4343
4602
  draft:(.draft // false),
4344
4603
  checks:(
4345
4604
  if $jstatus != "ok" then "unknown"
4346
- elif $jentry == null then "none"
4605
+ elif $jentry == null then (if $ambiguous then "unknown" else "none" end)
4347
4606
  else $jentry.checks
4348
4607
  end),
4349
4608
  mergeable:"unknown",
4350
4609
  review:"",
4351
4610
  url:(.links.html.href // ""),
4352
- updatedAt:(.updated_on // ""),headSha:(.source.commit.hash // ""),mergedAt:(if .state=="MERGED" then (.updated_on // "") else "" end),
4611
+ updatedAt:(.updated_on // ""),headSha:(.source.commit.hash // ""),mergedAt:(if .state=="MERGED" then (.updated_on // "") else "" end),checksSha:($jentry.checksSha // ""),
4353
4612
  author:(.author.nickname // ""),
4354
- failing_checks:(
4355
- if $jentry != null and $jentry.checks == "failing"
4356
- then [$jentry.job]
4357
- else []
4358
- end)
4359
- }' "${bb_cmd[@]}" || exit $?
4613
+ failing_checks:(if $jentry != null and $jentry.checks == "failing" then [$jentry.job] else [] end), base:(.destination.branch.name // "")
4614
+ } + (if $jstatus == "ok" and $ambiguous and $jentry == null then {checksLookup:"skipped"} else {} end)' "${bb_cmd[@]}" | bb_fold_mergeable_stream || exit $?
4615
+ PR_LIST_BIND_FN=""
4360
4616
  else
4361
4617
  # Bitbucket without Jenkins: checks remain unknown
4362
- PR_LIST_JQ_ARGS=()
4363
4618
  pr_list_states bitbucket "$limit" "$bb_states" \
4364
- '.[] | {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:[]}' \
4365
- "${bb_cmd[@]}" || exit $?
4619
+ '.[] | {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 // "")}' \
4620
+ "${bb_cmd[@]}" | bb_fold_mergeable_stream || exit $?
4366
4621
  fi
4367
4622
  else
4368
- PR_LIST_JQ_ARGS=()
4369
4623
  pr_list_states bitbucket "$limit" "$bb_states" \
4370
4624
  '.[] | {number:.id,title:.title,state:(if .state=="DECLINED" then "CLOSED" else .state end),head:.source.branch.name,author:(.author.nickname // "")}' \
4371
4625
  "${bb_cmd[@]}" || exit $?
@@ -4428,35 +4682,16 @@ case "$op" in
4428
4682
  startedAt:.startedAt, url:.url}' 2>/dev/null || true
4429
4683
  ;;
4430
4684
  jenkins)
4431
- # ONE STATE PER BRANCH, REPORTED AS A HISTORY OF ONE — and the PR says
4432
- # so, because it is the honest limit of the transport this arm has.
4433
- # `jenkins_build_map` answers `{color, checks, job}` for every branch in
4434
- # one call: a CURRENT state, with no timestamps, no URL and no earlier
4435
- # runs. A history is what Jenkins holds and what its REST API answers;
4436
- # reading it is `the-ci-connector-is-jenkins`'s own slice, and inventing
4437
- # entries here to fill the shape would be the collector reaching a
4438
- # verdict (Principle 3).
4685
+ # THE BRANCH'S BUILD HISTORY, newest first, read through
4686
+ # `jenkins_sha_runs` with no sha — the REST call `run-for-sha` and
4687
+ # `runs-for-sha` make. `startedAt` and `url` are Jenkins' own fields.
4439
4688
  #
4440
- # SO THE FIELDS THIS CANNOT MEASURE ARE EMPTY, never guessed. `workflow`
4441
- # names the Jenkins job, which is the one thing the map does carry and
4442
- # the detail a reader opens; `conclusion` is the `checks` word the
4443
- # colour table already settled; `startedAt` and `url` are empty,
4444
- # because a timestamp this arm invented would read as measurement.
4445
- _jen_instance="$(jenkins_instance)"
4446
- [ -n "$_jen_instance" ] || jenkins_no_instance
4447
- _jen_payload=$(jenkins_build_map "$_jen_instance")
4448
- _jen_status=$(printf '%s' "$_jen_payload" | jq -r '.status // "failed"' 2>/dev/null || echo "failed")
4449
- if [ "$_jen_status" != "ok" ]; then
4450
- # UNREACHABLE IS NOT EMPTY EITHER. `pr-list --rich` can mark its rows
4451
- # `unknown` and keep them; this op has no row to carry the word, so
4452
- # the only way to say *cannot verify* is the exit code. Printing
4453
- # nothing at exit 0 would read as *this branch has never run*.
4454
- echo "plot-host: runs — jenkins unreachable ($_jen_status)" >&2
4455
- exit 4
4456
- fi
4457
- printf '%s' "$_jen_payload" | jq -c --arg branch "$branch" \
4458
- '.map[$branch] // empty
4459
- | {workflow:(.job // ""), conclusion:(.checks // ""), startedAt:"", url:""}' 2>/dev/null || true
4689
+ # CONCLUSION IS HOST-NEUTRAL, as in the GitHub arm above: Jenkins' raw
4690
+ # `.result` (`SUCCESS`/`FAILURE`/...), and the `status` (`in_progress`)
4691
+ # while a build runs — not the `checks` word the colour table settles
4692
+ # for `pr-list --rich`.
4693
+ _jen_all=$(jenkins_sha_runs runs "$branch" "$limit" "") || exit $?
4694
+ printf '%s' "$_jen_all" | jq -c '.[] | {workflow:.workflow, conclusion:(.conclusion // .status), startedAt:.startedAt, url:.url}' 2>/dev/null || true
4460
4695
  ;;
4461
4696
  *)
4462
4697
  ci_unaskable runs "$_ci"
@@ -4602,7 +4837,7 @@ case "$op" in
4602
4837
  # Slurped via stdin, never `--argjson`: that flag caps at 128 KB on Linux.
4603
4838
  _gh_jobs=$(gh run view "$_gh_db_id" --json jobs 2>/dev/null) || { echo "plot-host: run-for-sha — gh run view failed" >&2; exit 4; }
4604
4839
  jq -n -c --slurpfile match <(printf '%s' "$_gh_match") --slurpfile run <(printf '%s' "$_gh_jobs") \
4605
- '$match[0] + {jobs: [$run[0].jobs[] | {conclusion, steps: (.steps | length)}]}' || exit 4
4840
+ '$match[0] + {jobs: [$run[0].jobs[] | {conclusion, startedAt, completedAt, steps: [(.steps // [])[].conclusion]}]}' || exit 4
4606
4841
  ;;
4607
4842
 
4608
4843
  issue-list)
@@ -4617,7 +4852,7 @@ case "$op" in
4617
4852
  # of them reproduces `an-outage-is-not-an-answer` — a board that says "no
4618
4853
  # issues" because it could not reach the tracker is stating a fact it does
4619
4854
  # not have.
4620
- limit=""; state="open"; since=""; page_token=""; paged=""
4855
+ limit=""; state="open"; since=""; page_token=""; paged=""; label=""; fix_version=""
4621
4856
  while [ $# -gt 0 ]; do
4622
4857
  case "$1" in
4623
4858
  --limit) limit="${2:?}"; shift 2 ;;
@@ -4625,13 +4860,15 @@ case "$op" in
4625
4860
  --since) since="${2:?}"; shift 2 ;;
4626
4861
  --page-token) page_token="${2:?}"; shift 2 ;;
4627
4862
  --paged) paged=1; shift ;;
4863
+ --label) label="${2:?}"; shift 2 ;;
4864
+ --fix-version) fix_version="${2:?}"; state=version; shift 2 ;;
4628
4865
  *) die "issue-list: unknown arg $1" ;;
4629
4866
  esac
4630
4867
  done
4631
4868
  # `--since` is spliced into a JQL string and a search qualifier, so its shape
4632
4869
  # is checked here: a value outside it is a usage error, never a query.
4633
- [[ "$state" =~ ^(open|closed|inbox)$ ]] || die "issue-list: --state is open, closed or inbox, not '$state'"
4634
- [ "$state" != closed ] || [[ "$since" =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}(T[0-9]{2}:[0-9]{2}[0-9:.]*Z?)?$ ]] || die "issue-list: --state closed needs --since <iso>"
4870
+ [[ "$state" =~ ^(open|closed|inbox|changed|version)$ ]] || die "issue-list: --state is open, closed, inbox, changed or version, not '$state'"
4871
+ [[ "$state" =~ ^(closed|changed)$ ]] && ! [[ "$since" =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}(T[0-9]{2}:[0-9]{2}[0-9:.]*Z?)?$ ]] && die "issue-list: --state $state needs --since <iso>"
4635
4872
  limit_args=()
4636
4873
  [ -n "$limit" ] && limit_args=(--limit "$limit")
4637
4874
  # WHO LISTS THESE ISSUES IS ASKED ONCE, HERE, BEFORE THE ARMS — after the
@@ -4643,6 +4880,7 @@ case "$op" in
4643
4880
  # asked at all* — a configuration a person fixes, not a call to retry.
4644
4881
  # NOTHING HAS BEEN SPENT: no `gh`, no `bb`, no curl has run yet.
4645
4882
  [ "${source_said%%$'\t'*}" != nobody ] || { echo "plot-host: ${source_said#*$'\t'}" >&2; exit 4; }
4883
+ [ "$state" != version ] || [ "$source_said" = $'tracker\tjira' ] || { echo "plot-host: only a Jira tracker has fix versions" >&2; exit 4; }
4646
4884
  if [ "$source_said" = $'tracker\tjira' ]; then
4647
4885
  # Jira, resolved through the REST API — DISPATCHED ON `Tracker`, never on
4648
4886
  # `backend()`: a Bitbucket repo tracking in Jira is the normal enterprise
@@ -4654,6 +4892,7 @@ case "$op" in
4654
4892
  # the board. `PLOT_JIRA_JQL` overrides it for a team that wants a wider or
4655
4893
  # narrower inbox. ORDER BY created DESC so the newest ticket is first, the
4656
4894
  # same order `createdAt` gives the GitHub arm.
4895
+ [ -z "$label" ] || { echo "plot-host: jira cannot list issues by label" >&2; exit 4; }
4657
4896
  jira_require_config
4658
4897
  # `Ticket prefixes` SCOPES THE DEFAULT to this repository's projects. The
4659
4898
  # default alone scopes by person and by state, so on a shared instance it
@@ -4677,6 +4916,18 @@ case "$op" in
4677
4916
  # closed reads keep `assignee = currentUser()` only where `$scope` is
4678
4917
  # empty. The inbox read below keeps it unconditionally, and the scope too.
4679
4918
  person=""; [ -n "$scope" ] || person="assignee = currentUser() AND "
4919
+ # THE CLOSED, CHANGED AND VERSION READS REQUIRE `Ticket prefixes`: an
4920
+ # unscoped `resolved >=`, `updated >=` or `fixVersion =` query reads every
4921
+ # project on the instance, the hazard `tracker_projects` measured.
4922
+ [ -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
4923
+ # A VERSION READ EXISTS BEFORE IT IS SEARCHED: `fixVersion = "<name>"` alone
4924
+ # matches nothing for a name Jira has never heard of and still exits 0 with
4925
+ # no rows (measured 2026-10-21) — the exact silent empty answer this guard
4926
+ # exists to refuse. `version-list` per `Ticket prefixes` project is the
4927
+ # same read `versionRead` (tracker-jira.ts) makes to decide the same
4928
+ # question, so a same-named version outside those projects still counts as
4929
+ # unknown. A failed list (`|| exit $?`) propagates rather than reading as
4930
+ # not-found: absent is not false.
4680
4931
  # PLOT_JIRA_JQL STILL WINS OVER BOTH. Teams worked around this bug with
4681
4932
  # their own JQL; an override that stopped overriding would break exactly
4682
4933
  # the people who noticed the problem first.
@@ -4693,21 +4944,47 @@ case "$op" in
4693
4944
  # THE CLOSED READ REQUIRES `Ticket prefixes` AND READS NOT PLOT_JIRA_JQL.
4694
4945
  # An unscoped `resolved >=` query reads the whole instance — the hazard
4695
4946
  # `tracker_projects` measured for the open read — so with none declared
4696
- # the read exits 4 before any curl. `jira_require_config` follows. The
4947
+ # the read exits 4 before any curl, at the guard above. The
4697
4948
  # closed read is always paged: a page is ISSUE_PAGE_ROWS, and the
4698
4949
  # TypeScript adapter walks the pages, so this arm holds no loop. JQL dates take
4699
4950
  # `yyyy-MM-dd` or `yyyy-MM-dd HH:mm`, so the ISO `since` is cut to the
4700
4951
  # shape it has: a date-only `since` sends the date alone. JQL takes no
4701
4952
  # offset, so Jira reads the time in the reader's profile zone. Its
4702
4953
  # person clause drops with the open read's (D20), same reason.
4703
- [ -n "$scope" ] || { echo "plot-host: closed Jira issues need 'Ticket prefixes' declared; an unscoped resolved query reads the whole instance" >&2; exit 4; }
4704
4954
  when="${since:0:10} ${since:11:5}"; jql="resolved >= \"${when% }\"${scope} ORDER BY resolved DESC"
4705
4955
  fields="$fields,resolutiondate"; paged=1
4706
4956
  # THE D23 INBOX READ: always person-scoped, and project-scoped by `$scope`
4707
4957
  # like the open read, so *Waiting on you* shows the reader's own tickets of this repository's projects.
4708
4958
  elif [ "$state" = inbox ]; then jql="${PLOT_JIRA_JQL:-assignee = currentUser() AND resolution = EMPTY${scope} ORDER BY created DESC}"
4959
+ # THE CHANGED READ IS GATED LIKE THE CLOSED READ, for the same reason: an
4960
+ # unscoped `updated >=` query reads the whole instance. It asks `updated`
4961
+ # rather than `resolved`, since a changed row may still be open, and
4962
+ # carries `updatedAt` so the adapter's fold can compare it. It sends
4963
+ # `since` as a RELATIVE `-Nm`, the minutes from `since` to now plus 5:
4964
+ # Jira reads an absolute JQL time in the reader's profile zone, so a UTC
4965
+ # `since` cut to `yyyy-MM-dd HH:mm` starts hours late for a reader behind
4966
+ # UTC, and a relative time names the same instant in every zone. The 5
4967
+ # minutes cover clock skew; the fold drops the rows read twice.
4968
+ elif [ "$state" = changed ]; then
4969
+ mins="$(jq -nr --arg s "$since" '($s[11:19] | . + "00:00:00"[length:]) as $t | (now - ("\($s[0:10])T\($t)Z" | fromdateiso8601)) / 60 | ceil + 5 | if . < 5 then 5 else . end')"; jql="updated >= \"-${mins}m\"${scope} ORDER BY updated DESC"; fields="$fields,updated,resolutiondate"; paged=1
4970
+ # THE VERSION READ, gated with the closed read above: `fixVersion = "<name>"`
4971
+ # alone matches a same-named version in every project on a shared
4972
+ # instance. The name is escaped for a JQL string literal.
4973
+ elif [ "$state" = version ]; then jql="fixVersion = \"$(printf '%s' "$fix_version" | sed 's/\\/\\\\/g; s/"/\\"/g')\"${scope} ORDER BY created DESC"; paged=1
4709
4974
  fi
4710
- [ -z "$paged" ] || { max="${limit:-$ISSUE_PAGE_ROWS}"; [ "$max" -le "$ISSUE_PAGE_ROWS" ] || max="$ISSUE_PAGE_ROWS"; }
4975
+ # AN UNPAGED READ'S --limit ABOVE ONE PAGE IS REFUSED, NOT CLAMPED. Open
4976
+ # and inbox are the only states still unpaged here — closed and changed
4977
+ # forced `paged=1` above. Jira caps maxResults at 100 itself, so an
4978
+ # unpaged `--limit 200` silently returned 100 rows with no sign the other
4979
+ # 100 existed (measured 2026-10-21, ewz-kus-portal). Exit 2 is new here —
4980
+ # this arm otherwise uses `die` (1) for usage and 3/4 for host states —
4981
+ # because a stderr warning is lost wherever stderr is discarded, and the
4982
+ # three-outcomes rule above says a partial answer must not look like a
4983
+ # complete one. Checked BEFORE any curl: nothing is spent on a call this
4984
+ # refuses. `-gt`, not `-ge`: a full single page (100) is still one page
4985
+ # and must still answer. A non-numeric `--limit` skips this guard and
4986
+ # reaches Jira as an invalid `maxResults` instead — not this guard's job.
4987
+ 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
4711
4988
  token_args=(); [ -z "$page_token" ] || token_args=(--data-urlencode "nextPageToken=$page_token")
4712
4989
  # jq builds the query string so a JQL with spaces/quotes is encoded once,
4713
4990
  # not hand-escaped. --data-urlencode via curl -G keeps the token out of the
@@ -4717,7 +4994,14 @@ case "$op" in
4717
4994
  --data-urlencode "jql=$jql" \
4718
4995
  --data-urlencode "fields=$fields" \
4719
4996
  --data-urlencode "maxResults=$max" \
4720
- ${token_args[@]+"${token_args[@]}"})" || exit $?
4997
+ ${token_args[@]+"${token_args[@]}"})" || exit $?; cut=false; [ -n "$paged" ] || read -r rows cut <<<"$(jq -r '[(.issues|length), ((.nextPageToken // "")!="")] | @tsv' <<<"$body")"; [ "$cut" = true ] && echo "plot-host: jira issue-list state=$state possibly truncated ($rows rows, requested limit $max)" >&2
4998
+ # AN UNPAGED OPEN OR INBOX READ NEVER PRINTS ITS OWN "more rows exist"
4999
+ # signal — a paged read's `{"nextPageToken":…}` line IS that signal, and
5000
+ # printing it here too would duplicate it (open question 2). So this is
5001
+ # the only place that reads the response's own `nextPageToken` for an
5002
+ # unpaged read, on stderr, one line, before `$body` is reprojected below.
5003
+ # `// ""` reads a missing key and an empty one alike as "no more pages" —
5004
+ # a full page with no token (50 of 50) is Jira's own answer, not "cut".
4721
5005
  # `number` is the Jira KEY (PROJ-123), a string — #447 taught the parser to
4722
5006
  # read that form. `url` is built from the base + /browse/<key>; Jira's
4723
5007
  # search payload carries no browse URL, and the base is ours to know
@@ -4741,7 +5025,7 @@ case "$op" in
4741
5025
  createdAt: (.fields.created // ""),
4742
5026
  status: (.fields.status.name // ""),
4743
5027
  statusCategory: (.fields.status.statusCategory.name // ""), assignees: ([.fields.assignee.emailAddress // .fields.assignee.accountId] | map(select(. != null)))
4744
- } + (if .fields.issuetype.name then {type: .fields.issuetype.name} else {} end) + (if $state == "closed" then {closedAt: (.fields.resolutiondate // "")} else {} end)),
5028
+ } + (if .fields.issuetype.name then {type: .fields.issuetype.name} else {} end) + (if .fields.updated then {updatedAt: .fields.updated} else {} end) + (if ($state == "closed") or ($state == "changed" and .fields.status.statusCategory.name == "Done") then {closedAt: (.fields.resolutiondate // "")} else {} end)),
4745
5029
  (select($paged == "1") | (.nextPageToken // empty) | {nextPageToken: .})'
4746
5030
  elif [ "$be" = "github" ]; then
4747
5031
  # `gh issue list` — not `gh api /issues`. On GitHub every PR IS an issue,
@@ -4760,15 +5044,25 @@ case "$op" in
4760
5044
  # keeps what closed since `$since`. GitHub search has no close-date sort
4761
5045
  # (`sort:closed-desc` was measured ignored, 2026-10-13), so the adapter
4762
5046
  # sorts by `closedAt`.
4763
- gh_json="number,title,url,createdAt,assignees,issueType"; search_args=()
4764
- [ "$gh_state" = open ] || { gh_json+=",closedAt"; search_args=(--search "closed:>=$since"); }
4765
- if out="$(gh issue list --state "$gh_state" ${limit_args[@]+"${limit_args[@]}"} \
5047
+ #
5048
+ # A CHANGED READ ASKS `--state all`, SINCE IT CAN RETURN EITHER STATE, so
5049
+ # `status`/`statusCategory` are projected from EACH ROW'S OWN `.state`
5050
+ # rather than from `$gh_state` — the one read here where the issue
5051
+ # itself, not the call, says what it is. `updatedAt` rides along so the
5052
+ # adapter's fold can compare it the way `foldIssueRows` already does.
5053
+ gh_json="number,title,url,createdAt,assignees,issueType"; search_args=(); ask_state="$gh_state"
5054
+ [ -z "$label" ] || search_args=(--label "$label")
5055
+ if [ "$gh_state" = changed ]; then gh_json+=",updatedAt,state,closedAt"; ask_state=all; search_args+=(--search "updated:>=$since")
5056
+ elif [ "$gh_state" != open ]; then gh_json+=",closedAt"; search_args+=(--search "closed:>=$since"); fi
5057
+ if out="$(gh issue list --state "$ask_state" ${limit_args[@]+"${limit_args[@]}"} \
4766
5058
  ${search_args[@]+"${search_args[@]}"} --json "$gh_json" 2>"$HOST_ERR")"; then
4767
5059
  rm -f "$HOST_ERR"
4768
5060
  jq -c --arg status "$gh_state" \
4769
- '.[] | {number:.number,title:.title,url:(.url // ""),createdAt:(.createdAt // ""),
4770
- status:$status,statusCategory:(if $status == "open" then "To Do" else "Done" end),assignees:[.assignees[]?.login]} + (if .issueType.name? then {type:.issueType.name} else {} end)
4771
- + (if $status == "closed" then {closedAt:(.closedAt // "")} else {} end)' <<<"$out"
5061
+ '.[] | ((.state // $status) | ascii_downcase) as $actual |
5062
+ {number:.number,title:.title,url:(.url // ""),createdAt:(.createdAt // ""),
5063
+ status:$actual,statusCategory:(if $actual == "open" then "To Do" else "Done" end),assignees:[.assignees[]?.login]}
5064
+ + (if .updatedAt then {updatedAt:.updatedAt} else {} end) + (if .issueType.name? then {type:.issueType.name} else {} end)
5065
+ + (if $actual == "closed" then {closedAt:(.closedAt // "")} else {} end)' <<<"$out"
4772
5066
  # `gh` pages by 100 inside ONE process and the wrapper records one call
4773
5067
  # per process, so each page past the first is recorded here.
4774
5068
  jq -r "[range(1; length / $ISSUE_PAGE_ROWS | ceil)] | .[]" <<<"$out" | while read -r _; do budget_record_call github github graphql; done
@@ -4787,9 +5081,10 @@ case "$op" in
4787
5081
  # after parsing; (3) the list carries no per-issue URL, so `url` is "" —
4788
5082
  # the same answer the header documents for a host that omits it.
4789
5083
  #
4790
- # A CLOSED READ IS EXIT 4: `bb issue list` prints no closing date, so there
4791
- # is nothing honest to return. It runs before any `bb` command.
4792
- [ "$state" = open ] || { echo "plot-host: bitbucket cannot list closed issues; bb prints no closing date" >&2; exit 4; }
5084
+ # A CLOSED OR CHANGED READ IS EXIT 4: `bb issue list` prints no closing or
5085
+ # update date, so there is nothing honest to return for either. It runs
5086
+ # before any `bb` command.
5087
+ { [ "$state" = open ] && [ -z "$label" ]; } || { echo "plot-host: bitbucket cannot list closed or changed issues, or issues by label" >&2; exit 4; }
4793
5088
  bb_assert_issue_version || exit $?
4794
5089
  # `--state new,open` is bb's own default for `issue list` and is what
4795
5090
  # "open tracker issues" means; stated explicitly so a bb default change
@@ -4797,12 +5092,9 @@ case "$op" in
4797
5092
  # call (the request-budget comment in fleet.ts counts exactly this).
4798
5093
  raw="$(bb issue list --state new --state open 2>&1)"; rc=$?
4799
5094
  raw="$(bb_strip_ansi <<<"$raw")"
4800
- if [ "$rc" -ne 0 ]; then
4801
- # bb's error is on stdout, now folded into `raw`. Report it and choose
4802
- # 4-vs-3 from its wording — never parse it as an issue (Done-when 6).
4803
- echo "plot-host: $raw" >&2
4804
- exit "$(bb_issue_exit_code "$(tr '[:upper:]' '[:lower:]' <<<"$raw")")"
4805
- fi
5095
+ # bb's error is on stdout, now folded into `raw`. Report it and choose
5096
+ # 4-vs-3 from its wording — never parse it as an issue (Done-when 6).
5097
+ [ "$rc" -eq 0 ] || { echo "plot-host: $raw" >&2; exit "$(bb_issue_exit_code "$(tr '[:upper:]' '[:lower:]' <<<"$raw")")"; }
4806
5098
  # A row is `#NNN <STATE> <title> by <reporter>`. Anchor on the `#NNN`
4807
5099
  # prefix (the header line ` :: Showing …` has none and is skipped for
4808
5100
  # free), lift the number, strip the known state badge word, then drop the
@@ -4876,18 +5168,21 @@ case "$op" in
4876
5168
  # the board. jira_check turns that 404 into exit 3 with empty stdout.
4877
5169
  jira_require_config
4878
5170
  body_json="$(jira_ask "/rest/api/2/issue/$num" \
4879
- -G --data-urlencode "fields=summary,description")" || exit $?
4880
- base="$(tracker_base_url)"
4881
- printf '%s' "$body_json" | jq -c --arg base "$base" '{
5171
+ -G --data-urlencode "fields=summary,description,status")" || exit $?
5172
+ # `state` FOLLOWS issue-list's OWN WORD: `statusCategory.name == "Done"`
5173
+ # is closed, same mapping as the list's open/closed reader — a second
5174
+ # vocabulary here would drift from the one issue-list already keeps.
5175
+ printf '%s' "$body_json" | jq -c --arg base "$(tracker_base_url)" '{
4882
5176
  number: .key,
4883
5177
  title: (.fields.summary // ""),
4884
5178
  body: (.fields.description // ""),
4885
- url: ($base + "/browse/" + .key)
5179
+ url: ($base + "/browse/" + .key),
5180
+ state: (if .fields.status.statusCategory.name == "Done" then "closed" else "open" end)
4886
5181
  }'
4887
5182
  elif [ "$be" = "github" ]; then
4888
- if out="$(gh issue view "$num" --json number,title,body,url 2>"$HOST_ERR")"; then
5183
+ if out="$(gh issue view "$num" --json number,title,body,url,state 2>"$HOST_ERR")"; then
4889
5184
  rm -f "$HOST_ERR"
4890
- jq -c '{number:.number,title:(.title // ""),body:(.body // ""),url:(.url // "")}' <<<"$out"
5185
+ jq -c '{number:.number,title:(.title // ""),body:(.body // ""),url:(.url // ""),state:((.state // "open") | ascii_downcase)}' <<<"$out"
4891
5186
  else
4892
5187
  # NO miss/fail split here, and that is deliberate. `host_miss_or_fail`
4893
5188
  # exists where an absent subject is a NORMAL answer — a branch with no
@@ -4916,15 +5211,19 @@ case "$op" in
4916
5211
  bb_assert_issue_version || exit $?
4917
5212
  raw="$(bb issue view "$num" 2>&1)"; rc=$?
4918
5213
  raw="$(bb_strip_ansi <<<"$raw")"
4919
- if [ "$rc" -ne 0 ]; then
4920
- echo "plot-host: $raw" >&2
4921
- exit "$(bb_issue_exit_code "$(tr '[:upper:]' '[:lower:]' <<<"$raw")")"
4922
- fi
5214
+ [ "$rc" -eq 0 ] || { echo "plot-host: $raw" >&2; exit "$(bb_issue_exit_code "$(tr '[:upper:]' '[:lower:]' <<<"$raw")")"; }
4923
5215
  # Title is the first line. URL is lifted from the footer, which is bb's
4924
5216
  # only place that prints one for a viewed issue — so the contract's `url`
4925
5217
  # is real here even though issue-list's is "".
4926
5218
  title="$(sed -n '1p' <<<"$raw")"
4927
5219
  url="$(grep -oE 'https?://[^[:space:]]+' <<<"$(grep -F 'View this issue on Bitbucket' <<<"$raw")" | head -1)"
5220
+ # Line 2 is `<STATE> • <reporter> opened <createdOn>` — the same badge
5221
+ # word `issue-list` strips from its own row, read here instead of
5222
+ # discarded. RESOLVED/CLOSED close it; everything else (including states
5223
+ # this vocabulary has no word for) stays open, the same default
5224
+ # issue-list's mapping leaves for an unmapped badge.
5225
+ bb_state="$(sed -n '2p' <<<"$raw" | sed -E 's/^([A-Z ]+)[[:space:]]*•.*$/\1/; s/[[:space:]]+$//')"
5226
+ case "$bb_state" in RESOLVED|CLOSED) state=closed ;; *) state=open ;; esac
4928
5227
  # Body is the block between the metadata head and the footer. The head is
4929
5228
  # the title + the two fixed meta lines (state, Type:) plus an optional
4930
5229
  # Component/Milestone/Version line; the tail is the footer. This is the
@@ -4946,8 +5245,8 @@ case "$op" in
4946
5245
  { lines[NR]=$0; if ($0 ~ /[^[:space:]]/) { if (!first) first=NR; last=NR } }
4947
5246
  END { for (i=first; i<=last; i++) print lines[i] }
4948
5247
  ' <<<"$body")"
4949
- jq -cn --argjson number "$num" --arg title "$title" --arg body "$body" --arg url "$url" \
4950
- '{number:$number,title:$title,body:$body,url:$url}'
5248
+ jq -cn --argjson number "$num" --arg title "$title" --arg body "$body" --arg url "$url" --arg state "$state" \
5249
+ '{number:$number,title:$title,body:$body,url:$url,state:$state}'
4951
5250
  fi
4952
5251
  ;;
4953
5252
 
@@ -5007,13 +5306,45 @@ case "$op" in
5007
5306
  # verbatim; prints Jira's JSON answer.
5008
5307
  # github-issues <title> <body> [--label <label>...]; prints the new
5009
5308
  # issue's address.
5010
- # Exit 4, with the reason, for any other tracker.
5011
- case "$(tracker_scheme)" in
5012
- jira) jira_require_config; jira_ask /rest/api/2/issue -X POST -H 'Content-Type: application/json' --data-raw "${1:?issue-open needs a request}" || exit $? ;;
5013
- github-issues) gh issue create --title "${1:?issue-open needs a title}" --body "${2-}" "${@:3}" 2>"$HOST_ERR" || gh_fail ;;
5014
- *) echo "plot-host: issue-open answers for jira and github-issues only, not '$(tracker_scheme)'" >&2; exit 4 ;;
5309
+ # Exit 4, with the reason, for any other source — dispatched on the domain's
5310
+ # `issueSource` answer like issue-list, never on `tracker_scheme`.
5311
+ source_said="$(issue_source)" || exit 1
5312
+ case "$source_said" in
5313
+ $'tracker\tjira') jira_require_config; jira_ask /rest/api/2/issue -X POST -H 'Content-Type: application/json' --data-raw "${1:?issue-open needs a request}" || exit $? ;;
5314
+ $'tracker\tgithub-issues') gh issue create --title "${1:?issue-open needs a title}" --body "${2-}" "${@:3}" 2>"$HOST_ERR" || gh_fail ;;
5315
+ *) echo "plot-host: issue-open: ${source_said#*$'\t'}" >&2; exit 4 ;;
5015
5316
  esac ;;
5016
5317
 
5318
+ issue-label|issue-comment|issue-close)
5319
+ # THE PLAN-STATE WRITES, and one-way: Plot sets a `plan:*` label, keeps one
5320
+ # comment per issue and closes the issue at release; nothing reads any back.
5321
+ # issue-label <n> <add> [<remove,...>] adds one label, removes the rest
5322
+ # issue-comment <n> <marker> <body> edits the comment holding <marker>, else posts; an empty <marker> always posts
5323
+ # issue-close <n>
5324
+ # GitHub issues only, dispatched on `issue_source` like issue-open. Exit 4,
5325
+ # with the reason, for a source that cannot be asked.
5326
+ num="${1:?$op needs an issue number}"; source_said="$(issue_source)" || exit 1
5327
+ [ "$be" = github ] && { [ "$source_said" = git-host ] || [ "$source_said" = $'tracker\tgithub-issues' ]; } || { echo "plot-host: $op: ${source_said#*$'\t'}" >&2; exit 4; }
5328
+ case "$op" in
5329
+ 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 ;;
5330
+ issue-close) gh issue close "$num" >/dev/null 2>"$HOST_ERR" || gh_fail ;;
5331
+ issue-comment)
5332
+ 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
5333
+ if [ -n "$cid" ]; then gh api -X PATCH "repos/{owner}/{repo}/issues/comments/$cid" -f body="${3-}" >/dev/null 2>"$HOST_ERR" || gh_fail
5334
+ else gh issue comment "$num" --body "${3-}" >/dev/null 2>"$HOST_ERR" || gh_fail; fi ;;
5335
+ esac
5336
+ rm -f "$HOST_ERR" ;;
5337
+
5338
+ # The projects `Ticket prefixes` scopes to, one per line, honoring
5339
+ # PLOT_TICKET_PREFIXES — the one answer the TypeScript connector asks.
5340
+ ticket-projects) tracker_projects ;;
5341
+
5342
+ version-list)
5343
+ # A Jira project's versions, unfiltered — see the usage header.
5344
+ source_said="$(issue_source)" || exit 1; [ "$source_said" = $'tracker\tjira' ] || { echo "plot-host: version-list needs 'Tracker: jira'" >&2; exit 4; }
5345
+ jira_require_config; body="$(jira_ask "/rest/api/2/project/${1:?version-list needs a project key}/versions")" || exit $?
5346
+ printf '%s' "$body" | jq -c '.[] | {name, released: (.released // false), releaseDate: (.releaseDate // null)}' || exit 3 ;;
5347
+
5017
5348
  pr-body)
5018
5349
  num="${1:?pr-body needs a PR number}"; shift
5019
5350
  body=""
@@ -5190,8 +5521,6 @@ case "$op" in
5190
5521
  # decides how much to trust it; a `throttled` observed during the session
5191
5522
  # is what corrects it.
5192
5523
  echo '{"connector":"bitbucket","bucket":"api","limit":1000,"remaining":null,"reset":null,"basis":"predicted"}'
5193
- else
5194
- echo "{\"connector\":\"$be\",\"bucket\":\"\",\"limit\":null,\"remaining\":null,\"reset\":null,\"basis\":\"unknown\"}"
5195
5524
  fi
5196
5525
  ;;
5197
5526
 
@@ -5292,18 +5621,18 @@ case "$op" in
5292
5621
  # `plot-commit-status.mjs` holds the GitHub App JWT/installation-token
5293
5622
  # exchange; `plot-bitbucket-commit-status.mjs` holds the Bitbucket state
5294
5623
  # mapping and Basic-auth build-status write, given a workspace/repo slug
5295
- # parsed here from `origin` (never from `bb`, which would mean asking
5296
- # whichever identity is signed in on this machine) — `.git` is stripped
5297
- # before capturing the slug, not inside a trailing optional group, or a
5298
- # greedy match absorbs it into the slug itself. A port after the host
5299
- # (`ssh://git@altssh.bitbucket.org:443/ws/repo`) is dropped first, or the
5300
- # `:` before it reads `443` as the workspace.
5301
- [ "$be" = "github" ] || { node "$here/plot-bitbucket-commit-status.mjs" "$(git config --get remote.origin.url 2>/dev/null | sed -E 's#\.git$##; s#(bitbucket\.org):[0-9]+/#\1/#' | sed -nE 's#^.*bitbucket\.org[:/]([^/]+)/(.+)$#\1/\2#p')" "$@" || exit $?; exit 0; }
5624
+ # parsed from `origin` by the `plot-bitbucket-slug.mjs` bundle (never from
5625
+ # `bb`, which would mean asking whichever identity is signed in on this
5626
+ # machine). The bundle reads a port after the host of a scheme'd URL
5627
+ # (`ssh://git@altssh.bitbucket.org:443/ws/repo`) as a port, and the colon
5628
+ # of an scp-style remote (`git@bitbucket.org:12345/repo`) as the start of
5629
+ # the path, so a numeric workspace survives. An empty slug is `unsupported`.
5630
+ [ "$be" = "github" ] || { node "$here/plot-bitbucket-commit-status.mjs" "$(node "$here/board/plot-bitbucket-slug.mjs" "$(git config --get remote.origin.url 2>/dev/null)")" "$@" || exit $?; exit 0; }
5302
5631
  node "$here/plot-commit-status.mjs" --check "$@" || exit $?
5303
- node "$here/plot-commit-status.mjs" --repo "$(gh repo view --json nameWithOwner --jq '.nameWithOwner' 2>/dev/null)" "$@" || exit $?
5632
+ node "$here/plot-commit-status.mjs" --repo "$(gh repo view --json nameWithOwner --jq '.nameWithOwner' 2>/dev/null || echo GH_REPO_VIEW_FAILED)" "$@" || exit $?
5304
5633
  ;;
5305
5634
 
5306
5635
  *)
5307
- die "unknown op '$op' (backend|default-branch|pr-state|pr-create|pr-merge|pr-list|issue-list|issue-view|issue-status|issue-open|pr-body|pr-review|rate-limit|limit|ci-limit|spend-rate|commit-status)"
5636
+ 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)"
5308
5637
  ;;
5309
5638
  esac